xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSCore/mDNS.c (revision 472cd20d26008f77084ade4c2048159b98c2b705)
1*472cd20dSToomas Soome /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
2c65ebfc7SToomas Soome  *
3*472cd20dSToomas Soome  * Copyright (c) 2002-2020 Apple Inc. All rights reserved.
4c65ebfc7SToomas Soome  *
5c65ebfc7SToomas Soome  * Licensed under the Apache License, Version 2.0 (the "License");
6c65ebfc7SToomas Soome  * you may not use this file except in compliance with the License.
7c65ebfc7SToomas Soome  * You may obtain a copy of the License at
8c65ebfc7SToomas Soome  *
9c65ebfc7SToomas Soome  *     http://www.apache.org/licenses/LICENSE-2.0
10c65ebfc7SToomas Soome  *
11c65ebfc7SToomas Soome  * Unless required by applicable law or agreed to in writing, software
12c65ebfc7SToomas Soome  * distributed under the License is distributed on an "AS IS" BASIS,
13c65ebfc7SToomas Soome  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14c65ebfc7SToomas Soome  * See the License for the specific language governing permissions and
15c65ebfc7SToomas Soome  * limitations under the License.
16c65ebfc7SToomas Soome  *
17c65ebfc7SToomas Soome  * This code is completely 100% portable C. It does not depend on any external header files
18c65ebfc7SToomas Soome  * from outside the mDNS project -- all the types it expects to find are defined right here.
19c65ebfc7SToomas Soome  *
20c65ebfc7SToomas Soome  * The previous point is very important: This file does not depend on any external
21c65ebfc7SToomas Soome  * header files. It should compile on *any* platform that has a C compiler, without
22c65ebfc7SToomas Soome  * making *any* assumptions about availability of so-called "standard" C functions,
23c65ebfc7SToomas Soome  * routines, or types (which may or may not be present on any given platform).
24c65ebfc7SToomas Soome  */
25c65ebfc7SToomas Soome 
26c65ebfc7SToomas Soome #include "DNSCommon.h"                  // Defines general DNS utility routines
27c65ebfc7SToomas Soome #include "uDNS.h"                       // Defines entry points into unicast-specific routines
28*472cd20dSToomas Soome 
29*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
30*472cd20dSToomas Soome #include "D2D.h"
31*472cd20dSToomas Soome #endif
32*472cd20dSToomas Soome 
33*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
34*472cd20dSToomas Soome #include <bsm/libbsm.h>
35*472cd20dSToomas Soome #endif
36*472cd20dSToomas Soome 
37*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
38*472cd20dSToomas Soome #include "dnssd_analytics.h"
39*472cd20dSToomas Soome #endif
40*472cd20dSToomas Soome 
41*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
42*472cd20dSToomas Soome #include "QuerierSupport.h"
43*472cd20dSToomas Soome #endif
44c65ebfc7SToomas Soome 
45c65ebfc7SToomas Soome // Disable certain benign warnings with Microsoft compilers
46c65ebfc7SToomas Soome #if (defined(_MSC_VER))
47c65ebfc7SToomas Soome // Disable "conditional expression is constant" warning for debug macros.
48c65ebfc7SToomas Soome // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
49c65ebfc7SToomas Soome // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
50c65ebfc7SToomas Soome     #pragma warning(disable:4127)
51c65ebfc7SToomas Soome 
52c65ebfc7SToomas Soome // Disable "assignment within conditional expression".
53c65ebfc7SToomas Soome // Other compilers understand the convention that if you place the assignment expression within an extra pair
54c65ebfc7SToomas Soome // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
55c65ebfc7SToomas Soome // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
56c65ebfc7SToomas Soome // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
57c65ebfc7SToomas Soome     #pragma warning(disable:4706)
58c65ebfc7SToomas Soome #endif
59c65ebfc7SToomas Soome 
60c65ebfc7SToomas Soome #include "dns_sd.h" // for kDNSServiceFlags* definitions
61c65ebfc7SToomas Soome #include "dns_sd_internal.h"
62c65ebfc7SToomas Soome 
63c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
64c65ebfc7SToomas Soome // Delay in seconds before disabling multicast after there are no active queries or registrations.
65c65ebfc7SToomas Soome #define BONJOUR_DISABLE_DELAY 60
66*472cd20dSToomas Soome #endif
67c65ebfc7SToomas Soome 
68*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
69*472cd20dSToomas Soome #include <WebFilterDNS/WebFilterDNS.h>
70*472cd20dSToomas Soome 
71c65ebfc7SToomas Soome WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
72c65ebfc7SToomas Soome void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
73*472cd20dSToomas Soome #endif
74c65ebfc7SToomas Soome 
75*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
76c65ebfc7SToomas Soome #include "Metrics.h"
77c65ebfc7SToomas Soome #endif
78c65ebfc7SToomas Soome 
79*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
80c65ebfc7SToomas Soome #include "DNS64.h"
81c65ebfc7SToomas Soome #endif
82c65ebfc7SToomas Soome 
83*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
84*472cd20dSToomas Soome #include "dnssec_v2.h"
85*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
86c65ebfc7SToomas Soome 
87c65ebfc7SToomas Soome // Forward declarations
88c65ebfc7SToomas Soome mDNSlocal void BeginSleepProcessing(mDNS *const m);
89c65ebfc7SToomas Soome mDNSlocal void RetrySPSRegistrations(mDNS *const m);
90c65ebfc7SToomas Soome mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly);
91*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
92c65ebfc7SToomas Soome mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
93*472cd20dSToomas Soome #endif
943b436d06SToomas Soome mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
95c65ebfc7SToomas Soome mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
96c65ebfc7SToomas Soome mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
97c65ebfc7SToomas Soome                                          mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
98c65ebfc7SToomas Soome 
99*472cd20dSToomas Soome typedef mDNSu32 DeadvertiseFlags;
100*472cd20dSToomas Soome #define kDeadvertiseFlag_NormalHostname (1U << 0)
101*472cd20dSToomas Soome #define kDeadvertiseFlag_RandHostname   (1U << 1)
102*472cd20dSToomas Soome #define kDeadvertiseFlag_All            (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
103c65ebfc7SToomas Soome 
104*472cd20dSToomas Soome mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags);
105*472cd20dSToomas Soome mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set);
106*472cd20dSToomas Soome mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
107c65ebfc7SToomas Soome 
108c65ebfc7SToomas Soome // ***************************************************************************
109c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
110c65ebfc7SToomas Soome #pragma mark - Program Constants
111c65ebfc7SToomas Soome #endif
112c65ebfc7SToomas Soome 
113c65ebfc7SToomas Soome // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
114c65ebfc7SToomas Soome #define MDNS_TRACER 1
115c65ebfc7SToomas Soome 
116c65ebfc7SToomas Soome // Any records bigger than this are considered 'large' records
117c65ebfc7SToomas Soome #define SmallRecordLimit 1024
118c65ebfc7SToomas Soome 
119c65ebfc7SToomas Soome #define kMaxUpdateCredits 10
120c65ebfc7SToomas Soome #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
121c65ebfc7SToomas Soome 
122c65ebfc7SToomas Soome // define special NR_AnswerTo values
123c65ebfc7SToomas Soome #define NR_AnswerMulticast  (mDNSu8*)~0
124c65ebfc7SToomas Soome #define NR_AnswerUnicast    (mDNSu8*)~1
125c65ebfc7SToomas Soome 
126c65ebfc7SToomas Soome // Question default timeout values
127c65ebfc7SToomas Soome #define DEFAULT_MCAST_TIMEOUT       5
128c65ebfc7SToomas Soome #define DEFAULT_LO_OR_P2P_TIMEOUT   5
129c65ebfc7SToomas Soome 
130c65ebfc7SToomas Soome // The code (see SendQueries() and BuildQuestion()) needs to have the
131c65ebfc7SToomas Soome // RequestUnicast value set to a value one greater than the number of times you want the query
132c65ebfc7SToomas Soome // sent with the "request unicast response" (QU) bit set.
133c65ebfc7SToomas Soome #define SET_QU_IN_FIRST_QUERY   2
134c65ebfc7SToomas Soome #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
135c65ebfc7SToomas Soome 
136c65ebfc7SToomas Soome // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
137c65ebfc7SToomas Soome #define DARK_WAKE_DELAY_SLEEP  5
138c65ebfc7SToomas Soome #define kDarkWakeDelaySleep    (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
139c65ebfc7SToomas Soome 
140c65ebfc7SToomas Soome // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
141c65ebfc7SToomas Soome #define MAX_CONFLICT_PROCESSING_DELAYS 3
142c65ebfc7SToomas Soome 
143c65ebfc7SToomas Soome // RFC 6762 defines Passive Observation Of Failures (POOF)
144c65ebfc7SToomas Soome //
145c65ebfc7SToomas Soome //    A host observes the multicast queries issued by the other hosts on
146c65ebfc7SToomas Soome //    the network.  One of the major benefits of also sending responses
147c65ebfc7SToomas Soome //    using multicast is that it allows all hosts to see the responses
148c65ebfc7SToomas Soome //    (or lack thereof) to those queries.
149c65ebfc7SToomas Soome //
150c65ebfc7SToomas Soome //    If a host sees queries, for which a record in its cache would be
151c65ebfc7SToomas Soome //    expected to be given as an answer in a multicast response, but no
152c65ebfc7SToomas Soome //    such answer is seen, then the host may take this as an indication
153c65ebfc7SToomas Soome //    that the record may no longer be valid.
154c65ebfc7SToomas Soome //
155c65ebfc7SToomas Soome //    After seeing two or more of these queries, and seeing no multicast
156c65ebfc7SToomas Soome //    response containing the expected answer within ten seconds, then even
157c65ebfc7SToomas Soome //    though its TTL may indicate that it is not yet due to expire, that
158c65ebfc7SToomas Soome //    record SHOULD be flushed from the cache.
159c65ebfc7SToomas Soome //
160c65ebfc7SToomas Soome // <https://tools.ietf.org/html/rfc6762#section-10.5>
161c65ebfc7SToomas Soome 
162c65ebfc7SToomas Soome #define POOF_ENABLED 1
163c65ebfc7SToomas Soome 
164c65ebfc7SToomas Soome mDNSexport const char *const mDNS_DomainTypeNames[] =
165c65ebfc7SToomas Soome {
166c65ebfc7SToomas Soome     "b._dns-sd._udp.",      // Browse
167c65ebfc7SToomas Soome     "db._dns-sd._udp.",     // Default Browse
168c65ebfc7SToomas Soome     "lb._dns-sd._udp.",     // Automatic Browse
169c65ebfc7SToomas Soome     "r._dns-sd._udp.",      // Registration
170c65ebfc7SToomas Soome     "dr._dns-sd._udp."      // Default Registration
171c65ebfc7SToomas Soome };
172c65ebfc7SToomas Soome 
173c65ebfc7SToomas Soome #ifdef UNICAST_DISABLED
174c65ebfc7SToomas Soome #define uDNS_IsActiveQuery(q, u) mDNSfalse
175c65ebfc7SToomas Soome #endif
176c65ebfc7SToomas Soome 
177c65ebfc7SToomas Soome // ***************************************************************************
178c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
179c65ebfc7SToomas Soome #pragma mark -
180c65ebfc7SToomas Soome #pragma mark - General Utility Functions
181c65ebfc7SToomas Soome #endif
182c65ebfc7SToomas Soome 
183*472cd20dSToomas Soome #if MDNS_MALLOC_DEBUGGING
184*472cd20dSToomas Soome // When doing memory allocation debugging, this function traverses all lists in the mDNS query
185*472cd20dSToomas Soome // structures and caches and checks each entry in the list to make sure it's still good.
mDNS_ValidateLists(void * context)186*472cd20dSToomas Soome mDNSlocal void mDNS_ValidateLists(void *context)
187*472cd20dSToomas Soome {
188*472cd20dSToomas Soome     mDNS *m = context;
189*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
190*472cd20dSToomas Soome     mDNSu32 NumAllInterfaceRecords   = 0;
191*472cd20dSToomas Soome     mDNSu32 NumAllInterfaceQuestions = 0;
192*472cd20dSToomas Soome #endif
193*472cd20dSToomas Soome 
194*472cd20dSToomas Soome     // Check core mDNS lists
195*472cd20dSToomas Soome     AuthRecord                  *rr;
196*472cd20dSToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
197*472cd20dSToomas Soome     {
198*472cd20dSToomas Soome         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
199*472cd20dSToomas Soome             LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
200*472cd20dSToomas Soome         if (rr->resrec.name != &rr->namestorage)
201*472cd20dSToomas Soome             LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
202*472cd20dSToomas Soome                              rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
203*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
204*472cd20dSToomas Soome         if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
205*472cd20dSToomas Soome #endif
206*472cd20dSToomas Soome     }
207*472cd20dSToomas Soome 
208*472cd20dSToomas Soome     for (rr = m->DuplicateRecords; rr; rr=rr->next)
209*472cd20dSToomas Soome     {
210*472cd20dSToomas Soome         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
211*472cd20dSToomas Soome             LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
212*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
213*472cd20dSToomas Soome         if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
214*472cd20dSToomas Soome #endif
215*472cd20dSToomas Soome     }
216*472cd20dSToomas Soome 
217*472cd20dSToomas Soome     rr = m->NewLocalRecords;
218*472cd20dSToomas Soome     if (rr)
219*472cd20dSToomas Soome         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
220*472cd20dSToomas Soome             LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType);
221*472cd20dSToomas Soome 
222*472cd20dSToomas Soome     rr = m->CurrentRecord;
223*472cd20dSToomas Soome     if (rr)
224*472cd20dSToomas Soome         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
225*472cd20dSToomas Soome             LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType);
226*472cd20dSToomas Soome 
227*472cd20dSToomas Soome     DNSQuestion                 *q;
228*472cd20dSToomas Soome     for (q = m->Questions; q; q=q->next)
229*472cd20dSToomas Soome     {
230*472cd20dSToomas Soome         if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0)
231*472cd20dSToomas Soome             LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next);
232*472cd20dSToomas Soome         if (q->DuplicateOf && q->LocalSocket)
233*472cd20dSToomas Soome             LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
234*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
235*472cd20dSToomas Soome         if (!LocalOnlyOrP2PInterface(q->InterfaceID) && mDNSOpaque16IsZero(q->TargetQID))
236*472cd20dSToomas Soome             NumAllInterfaceQuestions++;
237*472cd20dSToomas Soome #endif
238*472cd20dSToomas Soome     }
239*472cd20dSToomas Soome 
240*472cd20dSToomas Soome     CacheGroup                  *cg;
241*472cd20dSToomas Soome     CacheRecord                 *cr;
242*472cd20dSToomas Soome     mDNSu32 slot;
243*472cd20dSToomas Soome     FORALL_CACHERECORDS(slot, cg, cr)
244*472cd20dSToomas Soome     {
245*472cd20dSToomas Soome         if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
246*472cd20dSToomas Soome             LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType);
247*472cd20dSToomas Soome         if (cr->CRActiveQuestion)
248*472cd20dSToomas Soome         {
249*472cd20dSToomas Soome             for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break;
250*472cd20dSToomas Soome             if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr));
251*472cd20dSToomas Soome         }
252*472cd20dSToomas Soome     }
253*472cd20dSToomas Soome 
254*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
255*472cd20dSToomas Soome     if (m->NumAllInterfaceRecords != NumAllInterfaceRecords)
256*472cd20dSToomas Soome     	LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords);
257*472cd20dSToomas Soome 
258*472cd20dSToomas Soome     if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions)
259*472cd20dSToomas Soome     	LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions);
260*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
261*472cd20dSToomas Soome }
262*472cd20dSToomas Soome #endif // MDNS_MALLOC_DEBUGGING
263*472cd20dSToomas Soome 
264c65ebfc7SToomas Soome // Returns true if this is a  unique, authoritative LocalOnly record that answers questions of type
265c65ebfc7SToomas Soome // A, AAAA , CNAME, or PTR.  The caller should answer the question with this record and not send out
266c65ebfc7SToomas Soome // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
267c65ebfc7SToomas Soome // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
268c65ebfc7SToomas Soome #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
269c65ebfc7SToomas Soome                                         (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
270c65ebfc7SToomas Soome                                         ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
271c65ebfc7SToomas Soome                                          (rr)->resrec.rrtype == kDNSType_CNAME || \
272c65ebfc7SToomas Soome                                          (rr)->resrec.rrtype == kDNSType_PTR))
273c65ebfc7SToomas Soome 
SetNextQueryStopTime(mDNS * const m,const DNSQuestion * const q)274c65ebfc7SToomas Soome mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
275c65ebfc7SToomas Soome {
276c65ebfc7SToomas Soome     mDNS_CheckLock(m);
277c65ebfc7SToomas Soome 
278c65ebfc7SToomas Soome     if (m->NextScheduledStopTime - q->StopTime > 0)
279c65ebfc7SToomas Soome         m->NextScheduledStopTime = q->StopTime;
280c65ebfc7SToomas Soome }
281c65ebfc7SToomas Soome 
SetNextQueryTime(mDNS * const m,const DNSQuestion * const q)282c65ebfc7SToomas Soome mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
283c65ebfc7SToomas Soome {
284c65ebfc7SToomas Soome     mDNS_CheckLock(m);
285c65ebfc7SToomas Soome 
286c65ebfc7SToomas Soome     if (ActiveQuestion(q))
287c65ebfc7SToomas Soome     {
288c65ebfc7SToomas Soome         // Depending on whether this is a multicast or unicast question we want to set either:
289c65ebfc7SToomas Soome         // m->NextScheduledQuery = NextQSendTime(q) or
290c65ebfc7SToomas Soome         // m->NextuDNSEvent      = NextQSendTime(q)
291c65ebfc7SToomas Soome         mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
292c65ebfc7SToomas Soome         if (*timer - NextQSendTime(q) > 0)
293c65ebfc7SToomas Soome             *timer = NextQSendTime(q);
294c65ebfc7SToomas Soome     }
295c65ebfc7SToomas Soome }
296c65ebfc7SToomas Soome 
ReleaseAuthEntity(AuthHash * r,AuthEntity * e)297c65ebfc7SToomas Soome mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
298c65ebfc7SToomas Soome {
299*472cd20dSToomas Soome #if MDNS_MALLOC_DEBUGGING >= 1
300c65ebfc7SToomas Soome     unsigned int i;
301c65ebfc7SToomas Soome     for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
302c65ebfc7SToomas Soome #endif
303c65ebfc7SToomas Soome     e->next = r->rrauth_free;
304c65ebfc7SToomas Soome     r->rrauth_free = e;
305c65ebfc7SToomas Soome     r->rrauth_totalused--;
306c65ebfc7SToomas Soome }
307c65ebfc7SToomas Soome 
ReleaseAuthGroup(AuthHash * r,AuthGroup ** cp)308c65ebfc7SToomas Soome mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
309c65ebfc7SToomas Soome {
310c65ebfc7SToomas Soome     AuthEntity *e = (AuthEntity *)(*cp);
311c65ebfc7SToomas Soome     LogMsg("ReleaseAuthGroup:  Releasing AuthGroup %##s", (*cp)->name->c);
312c65ebfc7SToomas Soome     if ((*cp)->rrauth_tail != &(*cp)->members)
313c65ebfc7SToomas Soome         LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
314c65ebfc7SToomas Soome     if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
315c65ebfc7SToomas Soome     (*cp)->name = mDNSNULL;
316c65ebfc7SToomas Soome     *cp = (*cp)->next;          // Cut record from list
317c65ebfc7SToomas Soome     ReleaseAuthEntity(r, e);
318c65ebfc7SToomas Soome }
319c65ebfc7SToomas Soome 
GetAuthEntity(AuthHash * r,const AuthGroup * const PreserveAG)320c65ebfc7SToomas Soome mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
321c65ebfc7SToomas Soome {
322c65ebfc7SToomas Soome     AuthEntity *e = mDNSNULL;
323c65ebfc7SToomas Soome 
324c65ebfc7SToomas Soome     if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
325c65ebfc7SToomas Soome     r->rrauth_lock = 1;
326c65ebfc7SToomas Soome 
327c65ebfc7SToomas Soome     if (!r->rrauth_free)
328c65ebfc7SToomas Soome     {
329c65ebfc7SToomas Soome         // We allocate just one AuthEntity at a time because we need to be able
330c65ebfc7SToomas Soome         // free them all individually which normally happens when we parse /etc/hosts into
331c65ebfc7SToomas Soome         // AuthHash where we add the "new" entries and discard (free) the already added
332c65ebfc7SToomas Soome         // entries. If we allocate as chunks, we can't free them individually.
333*472cd20dSToomas Soome         AuthEntity *storage = (AuthEntity *) mDNSPlatformMemAllocateClear(sizeof(*storage));
334c65ebfc7SToomas Soome         storage->next = mDNSNULL;
335c65ebfc7SToomas Soome         r->rrauth_free = storage;
336c65ebfc7SToomas Soome     }
337c65ebfc7SToomas Soome 
338c65ebfc7SToomas Soome     // If we still have no free records, recycle all the records we can.
339c65ebfc7SToomas Soome     // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
340c65ebfc7SToomas Soome     if (!r->rrauth_free)
341c65ebfc7SToomas Soome     {
342c65ebfc7SToomas Soome         mDNSu32 oldtotalused = r->rrauth_totalused;
343c65ebfc7SToomas Soome         mDNSu32 slot;
344c65ebfc7SToomas Soome         for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
345c65ebfc7SToomas Soome         {
346c65ebfc7SToomas Soome             AuthGroup **cp = &r->rrauth_hash[slot];
347c65ebfc7SToomas Soome             while (*cp)
348c65ebfc7SToomas Soome             {
349c65ebfc7SToomas Soome                 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
350c65ebfc7SToomas Soome                 else ReleaseAuthGroup(r, cp);
351c65ebfc7SToomas Soome             }
352c65ebfc7SToomas Soome         }
353c65ebfc7SToomas Soome         LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
354c65ebfc7SToomas Soome                 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
355c65ebfc7SToomas Soome     }
356c65ebfc7SToomas Soome 
357c65ebfc7SToomas Soome     if (r->rrauth_free) // If there are records in the free list, take one
358c65ebfc7SToomas Soome     {
359c65ebfc7SToomas Soome         e = r->rrauth_free;
360c65ebfc7SToomas Soome         r->rrauth_free = e->next;
361c65ebfc7SToomas Soome         if (++r->rrauth_totalused >= r->rrauth_report)
362c65ebfc7SToomas Soome         {
363c65ebfc7SToomas Soome             LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
364c65ebfc7SToomas Soome             if      (r->rrauth_report <  100) r->rrauth_report += 10;
365c65ebfc7SToomas Soome             else if (r->rrauth_report < 1000) r->rrauth_report += 100;
366c65ebfc7SToomas Soome             else r->rrauth_report += 1000;
367c65ebfc7SToomas Soome         }
368c65ebfc7SToomas Soome         mDNSPlatformMemZero(e, sizeof(*e));
369c65ebfc7SToomas Soome     }
370c65ebfc7SToomas Soome 
371c65ebfc7SToomas Soome     r->rrauth_lock = 0;
372c65ebfc7SToomas Soome 
373c65ebfc7SToomas Soome     return(e);
374c65ebfc7SToomas Soome }
375c65ebfc7SToomas Soome 
AuthGroupForName(AuthHash * r,const mDNSu32 namehash,const domainname * const name)376c65ebfc7SToomas Soome mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name)
377c65ebfc7SToomas Soome {
378c65ebfc7SToomas Soome     AuthGroup *ag;
379c65ebfc7SToomas Soome     const mDNSu32 slot = namehash % AUTH_HASH_SLOTS;
380c65ebfc7SToomas Soome 
381c65ebfc7SToomas Soome     for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
382c65ebfc7SToomas Soome         if (ag->namehash == namehash && SameDomainName(ag->name, name))
383c65ebfc7SToomas Soome             break;
384c65ebfc7SToomas Soome     return(ag);
385c65ebfc7SToomas Soome }
386c65ebfc7SToomas Soome 
AuthGroupForRecord(AuthHash * r,const ResourceRecord * const rr)387c65ebfc7SToomas Soome mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr)
388c65ebfc7SToomas Soome {
389c65ebfc7SToomas Soome     return(AuthGroupForName(r, rr->namehash, rr->name));
390c65ebfc7SToomas Soome }
391c65ebfc7SToomas Soome 
GetAuthGroup(AuthHash * r,const ResourceRecord * const rr)392c65ebfc7SToomas Soome mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr)
393c65ebfc7SToomas Soome {
394c65ebfc7SToomas Soome     mDNSu16 namelen = DomainNameLength(rr->name);
395c65ebfc7SToomas Soome     AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
396c65ebfc7SToomas Soome     const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS;
397c65ebfc7SToomas Soome     if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
398c65ebfc7SToomas Soome     ag->next         = r->rrauth_hash[slot];
399c65ebfc7SToomas Soome     ag->namehash     = rr->namehash;
400c65ebfc7SToomas Soome     ag->members      = mDNSNULL;
401c65ebfc7SToomas Soome     ag->rrauth_tail  = &ag->members;
402c65ebfc7SToomas Soome     ag->NewLocalOnlyRecords = mDNSNULL;
403c65ebfc7SToomas Soome     if (namelen > sizeof(ag->namestorage))
404*472cd20dSToomas Soome         ag->name = (domainname *) mDNSPlatformMemAllocate(namelen);
405c65ebfc7SToomas Soome     else
406c65ebfc7SToomas Soome         ag->name = (domainname*)ag->namestorage;
407c65ebfc7SToomas Soome     if (!ag->name)
408c65ebfc7SToomas Soome     {
409c65ebfc7SToomas Soome         LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
410c65ebfc7SToomas Soome         ReleaseAuthEntity(r, (AuthEntity*)ag);
411c65ebfc7SToomas Soome         return(mDNSNULL);
412c65ebfc7SToomas Soome     }
413c65ebfc7SToomas Soome     AssignDomainName(ag->name, rr->name);
414c65ebfc7SToomas Soome 
415c65ebfc7SToomas Soome     if (AuthGroupForRecord(r, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
416c65ebfc7SToomas Soome     r->rrauth_hash[slot] = ag;
417c65ebfc7SToomas Soome     if (AuthGroupForRecord(r, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
418c65ebfc7SToomas Soome 
419c65ebfc7SToomas Soome     return(ag);
420c65ebfc7SToomas Soome }
421c65ebfc7SToomas Soome 
422c65ebfc7SToomas Soome // Returns the AuthGroup in which the AuthRecord was inserted
InsertAuthRecord(mDNS * const m,AuthHash * r,AuthRecord * rr)423c65ebfc7SToomas Soome mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
424c65ebfc7SToomas Soome {
425c65ebfc7SToomas Soome     AuthGroup *ag;
426c65ebfc7SToomas Soome 
427c65ebfc7SToomas Soome     (void)m;
428c65ebfc7SToomas Soome     ag = AuthGroupForRecord(r, &rr->resrec);
429c65ebfc7SToomas Soome     if (!ag) ag = GetAuthGroup(r, &rr->resrec);   // If we don't have a AuthGroup for this name, make one now
430c65ebfc7SToomas Soome     if (ag)
431c65ebfc7SToomas Soome     {
432c65ebfc7SToomas Soome         *(ag->rrauth_tail) = rr;                // Append this record to tail of cache slot list
433c65ebfc7SToomas Soome         ag->rrauth_tail = &(rr->next);          // Advance tail pointer
434c65ebfc7SToomas Soome     }
435c65ebfc7SToomas Soome     return ag;
436c65ebfc7SToomas Soome }
437c65ebfc7SToomas Soome 
RemoveAuthRecord(mDNS * const m,AuthHash * r,AuthRecord * rr)438c65ebfc7SToomas Soome mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
439c65ebfc7SToomas Soome {
440c65ebfc7SToomas Soome     AuthGroup *a;
441c65ebfc7SToomas Soome     AuthRecord **rp;
442c65ebfc7SToomas Soome 
443c65ebfc7SToomas Soome     a = AuthGroupForRecord(r, &rr->resrec);
444c65ebfc7SToomas Soome     if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
445c65ebfc7SToomas Soome     rp = &a->members;
446c65ebfc7SToomas Soome     while (*rp)
447c65ebfc7SToomas Soome     {
448c65ebfc7SToomas Soome         if (*rp != rr)
449c65ebfc7SToomas Soome             rp=&(*rp)->next;
450c65ebfc7SToomas Soome         else
451c65ebfc7SToomas Soome         {
452c65ebfc7SToomas Soome             // We don't break here, so that we can set the tail below without tracking "prev" pointers
453c65ebfc7SToomas Soome 
454c65ebfc7SToomas Soome             LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
455c65ebfc7SToomas Soome             *rp = (*rp)->next;          // Cut record from list
456c65ebfc7SToomas Soome         }
457c65ebfc7SToomas Soome     }
458c65ebfc7SToomas Soome     // TBD: If there are no more members, release authgroup ?
459c65ebfc7SToomas Soome     a->rrauth_tail = rp;
460c65ebfc7SToomas Soome     return a;
461c65ebfc7SToomas Soome }
462c65ebfc7SToomas Soome 
CacheGroupForName(const mDNS * const m,const mDNSu32 namehash,const domainname * const name)463c65ebfc7SToomas Soome mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name)
464c65ebfc7SToomas Soome {
465c65ebfc7SToomas Soome     CacheGroup *cg;
466c65ebfc7SToomas Soome     mDNSu32    slot = HashSlotFromNameHash(namehash);
467c65ebfc7SToomas Soome     for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
468c65ebfc7SToomas Soome         if (cg->namehash == namehash && SameDomainName(cg->name, name))
469c65ebfc7SToomas Soome             break;
470c65ebfc7SToomas Soome     return(cg);
471c65ebfc7SToomas Soome }
472c65ebfc7SToomas Soome 
CacheGroupForRecord(const mDNS * const m,const ResourceRecord * const rr)473c65ebfc7SToomas Soome mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr)
474c65ebfc7SToomas Soome {
475c65ebfc7SToomas Soome     return(CacheGroupForName(m, rr->namehash, rr->name));
476c65ebfc7SToomas Soome }
477c65ebfc7SToomas Soome 
mDNS_AddressIsLocalSubnet(mDNS * const m,const mDNSInterfaceID InterfaceID,const mDNSAddr * addr)478c65ebfc7SToomas Soome mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
479c65ebfc7SToomas Soome {
480c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
481c65ebfc7SToomas Soome 
482c65ebfc7SToomas Soome     if (addr->type == mDNSAddrType_IPv4)
483c65ebfc7SToomas Soome     {
484c65ebfc7SToomas Soome         // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
485c65ebfc7SToomas Soome         if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
486c65ebfc7SToomas Soome         for (intf = m->HostInterfaces; intf; intf = intf->next)
487c65ebfc7SToomas Soome             if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
488c65ebfc7SToomas Soome                 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
489c65ebfc7SToomas Soome                     return(mDNStrue);
490c65ebfc7SToomas Soome     }
491c65ebfc7SToomas Soome 
492c65ebfc7SToomas Soome     if (addr->type == mDNSAddrType_IPv6)
493c65ebfc7SToomas Soome     {
494c65ebfc7SToomas Soome         if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
495c65ebfc7SToomas Soome         for (intf = m->HostInterfaces; intf; intf = intf->next)
496c65ebfc7SToomas Soome             if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
497c65ebfc7SToomas Soome                 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
498c65ebfc7SToomas Soome                     (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
499c65ebfc7SToomas Soome                     (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
500c65ebfc7SToomas Soome                     (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
501c65ebfc7SToomas Soome                         return(mDNStrue);
502c65ebfc7SToomas Soome     }
503c65ebfc7SToomas Soome 
504c65ebfc7SToomas Soome     return(mDNSfalse);
505c65ebfc7SToomas Soome }
506c65ebfc7SToomas Soome 
FirstInterfaceForID(mDNS * const m,const mDNSInterfaceID InterfaceID)507c65ebfc7SToomas Soome mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
508c65ebfc7SToomas Soome {
509c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = m->HostInterfaces;
510c65ebfc7SToomas Soome     while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
511c65ebfc7SToomas Soome     return(intf);
512c65ebfc7SToomas Soome }
513c65ebfc7SToomas Soome 
FirstIPv4LLInterfaceForID(mDNS * const m,const mDNSInterfaceID InterfaceID)514c65ebfc7SToomas Soome mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
515c65ebfc7SToomas Soome {
516c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
517c65ebfc7SToomas Soome 
518c65ebfc7SToomas Soome     if (!InterfaceID)
519c65ebfc7SToomas Soome         return mDNSNULL;
520c65ebfc7SToomas Soome 
521c65ebfc7SToomas Soome     // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
522c65ebfc7SToomas Soome     // we still want to find the first IPv4 Link-Local interface
523c65ebfc7SToomas Soome     for (intf = m->HostInterfaces; intf; intf = intf->next)
524c65ebfc7SToomas Soome     {
525c65ebfc7SToomas Soome         if (intf->InterfaceID == InterfaceID &&
526c65ebfc7SToomas Soome             intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
527c65ebfc7SToomas Soome         {
528c65ebfc7SToomas Soome             debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
529c65ebfc7SToomas Soome             return intf;
530c65ebfc7SToomas Soome         }
531c65ebfc7SToomas Soome     }
532c65ebfc7SToomas Soome     return (mDNSNULL);
533c65ebfc7SToomas Soome }
534c65ebfc7SToomas Soome 
InterfaceNameForID(mDNS * const m,const mDNSInterfaceID InterfaceID)535c65ebfc7SToomas Soome mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
536c65ebfc7SToomas Soome {
537c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
538c65ebfc7SToomas Soome     return(intf ? intf->ifname : mDNSNULL);
539c65ebfc7SToomas Soome }
540c65ebfc7SToomas Soome 
541c65ebfc7SToomas Soome // Caller should hold the lock
GenerateNegativeResponseEx(mDNS * const m,mDNSInterfaceID InterfaceID,QC_result qc,mDNSBool noData)542*472cd20dSToomas Soome mDNSlocal void GenerateNegativeResponseEx(mDNS *const m, mDNSInterfaceID InterfaceID, QC_result qc, mDNSBool noData)
543c65ebfc7SToomas Soome {
544c65ebfc7SToomas Soome     DNSQuestion *q;
545c65ebfc7SToomas Soome     if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
546c65ebfc7SToomas Soome     q = m->CurrentQuestion;
547*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
548*472cd20dSToomas Soome            "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME " (" PUB_S ")",
549*472cd20dSToomas Soome            q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
550c65ebfc7SToomas Soome 
551c65ebfc7SToomas Soome     MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, InterfaceID, mDNSNULL);
552*472cd20dSToomas Soome     m->rec.r.resrec.negativeRecordType = noData ? kNegativeRecordType_NoData : kNegativeRecordType_Unspecified;
553c65ebfc7SToomas Soome 
554c65ebfc7SToomas Soome     // We need to force the response through in the following cases
555c65ebfc7SToomas Soome     //
556c65ebfc7SToomas Soome     //  a) SuppressUnusable questions that are suppressed
557c65ebfc7SToomas Soome     //  b) Append search domains and retry the question
558c65ebfc7SToomas Soome     //
559c65ebfc7SToomas Soome     // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
560c65ebfc7SToomas Soome     // through we use "QC_forceresponse".
561c65ebfc7SToomas Soome     AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
562c65ebfc7SToomas Soome     if (m->CurrentQuestion == q) { q->ThisQInterval = 0; }              // Deactivate this question
563c65ebfc7SToomas Soome     // Don't touch the question after this
564c65ebfc7SToomas Soome     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
565c65ebfc7SToomas Soome }
566*472cd20dSToomas Soome #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
567c65ebfc7SToomas Soome 
AnswerQuestionByFollowingCNAME(mDNS * const m,DNSQuestion * q,ResourceRecord * rr)568c65ebfc7SToomas Soome mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
569c65ebfc7SToomas Soome {
570c65ebfc7SToomas Soome     const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
571c65ebfc7SToomas Soome     if (q->CNAMEReferrals >= 10 || selfref)
572c65ebfc7SToomas Soome     {
573*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
574*472cd20dSToomas Soome                "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ")  NOT following CNAME referral %d" PUB_S " for " PRI_S,
575*472cd20dSToomas Soome                q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype),
576*472cd20dSToomas Soome                q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
577*472cd20dSToomas Soome 
578c65ebfc7SToomas Soome     }
579c65ebfc7SToomas Soome     else
580c65ebfc7SToomas Soome     {
581c65ebfc7SToomas Soome         UDPSocket *sock = q->LocalSocket;
582c65ebfc7SToomas Soome         mDNSOpaque16 id = q->TargetQID;
583*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
584c65ebfc7SToomas Soome         uDNSMetrics metrics;
585c65ebfc7SToomas Soome #endif
586c65ebfc7SToomas Soome 
587c65ebfc7SToomas Soome         q->LocalSocket = mDNSNULL;
588c65ebfc7SToomas Soome 
589c65ebfc7SToomas Soome         // The SameDomainName check above is to ignore bogus CNAME records that point right back at
590c65ebfc7SToomas Soome         // themselves. Without that check we can get into a case where we have two duplicate questions,
591c65ebfc7SToomas Soome         // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
592c65ebfc7SToomas Soome         // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
593c65ebfc7SToomas Soome         // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
594c65ebfc7SToomas Soome         // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
595c65ebfc7SToomas Soome         // for either of them. This is not a problem for CNAME loops of two or more records because in
596c65ebfc7SToomas Soome         // those cases the newly re-appended question A has a different target name and therefore cannot be
597c65ebfc7SToomas Soome         // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
598c65ebfc7SToomas Soome 
599c65ebfc7SToomas Soome         // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
600c65ebfc7SToomas Soome         // and track CNAMEs coming and going, we should really create a subordinate query here,
601c65ebfc7SToomas Soome         // which we would subsequently cancel and retract if the CNAME referral record were removed.
602c65ebfc7SToomas Soome         // In reality this is such a corner case we'll ignore it until someone actually needs it.
603c65ebfc7SToomas Soome 
604*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
605*472cd20dSToomas Soome                "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ") following CNAME referral %d for " PRI_S,
606*472cd20dSToomas Soome                q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype),
607*472cd20dSToomas Soome                q->CNAMEReferrals, RRDisplayString(m, rr));
608c65ebfc7SToomas Soome 
609*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
610*472cd20dSToomas Soome         if (!mDNSOpaque16IsZero(q->TargetQID))
611*472cd20dSToomas Soome         {
612*472cd20dSToomas Soome             // Must be called before zeroing out q->metrics below.
613*472cd20dSToomas Soome             Querier_PrepareQuestionForCNAMERestart(q);
614*472cd20dSToomas Soome         }
615*472cd20dSToomas Soome #endif
616*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
617c65ebfc7SToomas Soome         if ((q->CNAMEReferrals == 0) && !q->metrics.originalQName)
618c65ebfc7SToomas Soome         {
619c65ebfc7SToomas Soome             domainname *    qName;
620c65ebfc7SToomas Soome             mDNSu16         qNameLen;
621c65ebfc7SToomas Soome 
622c65ebfc7SToomas Soome             qNameLen = DomainNameLength(&q->qname);
623c65ebfc7SToomas Soome             if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
624c65ebfc7SToomas Soome             {
625*472cd20dSToomas Soome                 qName = (domainname *) mDNSPlatformMemAllocate(qNameLen);
626c65ebfc7SToomas Soome                 if (qName)
627c65ebfc7SToomas Soome                 {
628c65ebfc7SToomas Soome                     mDNSPlatformMemCopy(qName->c, q->qname.c, qNameLen);
629c65ebfc7SToomas Soome                     q->metrics.originalQName = qName;
630c65ebfc7SToomas Soome                 }
631c65ebfc7SToomas Soome             }
632c65ebfc7SToomas Soome         }
633c65ebfc7SToomas Soome         metrics = q->metrics;
634*472cd20dSToomas Soome         // The metrics will be transplanted to the restarted question, so zero out the old copy instead of using
635*472cd20dSToomas Soome         // uDNSMetricsClear(), which will free any pointers to allocated memory.
636c65ebfc7SToomas Soome         mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics));
637c65ebfc7SToomas Soome #endif
638c65ebfc7SToomas Soome         mDNS_StopQuery_internal(m, q);                              // Stop old query
639c65ebfc7SToomas Soome         AssignDomainName(&q->qname, &rr->rdata->u.name);            // Update qname
640c65ebfc7SToomas Soome         q->qnamehash = DomainNameHashValue(&q->qname);              // and namehash
641c65ebfc7SToomas Soome         // If a unicast query results in a CNAME that points to a .local, we need to re-try
642c65ebfc7SToomas Soome         // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
643c65ebfc7SToomas Soome         // to try this as unicast query even though it is a .local name
644c65ebfc7SToomas Soome         if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
645c65ebfc7SToomas Soome         {
646*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
647*472cd20dSToomas Soome                    "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME " (" PUB_S ") Record " PRI_S,
648*472cd20dSToomas Soome                    q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), RRDisplayString(m, rr));
649*472cd20dSToomas Soome             q->IsUnicastDotLocal = mDNStrue;
650c65ebfc7SToomas Soome         }
651*472cd20dSToomas Soome         q->CNAMEReferrals += 1;                                     // Increment value before calling mDNS_StartQuery_internal
652*472cd20dSToomas Soome         const mDNSu32 c = q->CNAMEReferrals;                        // Stash a copy of the new q->CNAMEReferrals value
653c65ebfc7SToomas Soome         mDNS_StartQuery_internal(m, q);                             // start new query
654c65ebfc7SToomas Soome         // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
655c65ebfc7SToomas Soome         // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
656c65ebfc7SToomas Soome         q->CNAMEReferrals = c;
657*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
6583b436d06SToomas Soome         metrics.expiredAnswerState  = q->metrics.expiredAnswerState; //  We want the newly initialized state for this value
659*472cd20dSToomas Soome         metrics.dnsOverTCPState     = q->metrics.dnsOverTCPState;    //  We want the newly initialized state for this value
660c65ebfc7SToomas Soome         q->metrics = metrics;
661c65ebfc7SToomas Soome #endif
662c65ebfc7SToomas Soome         if (sock)
663c65ebfc7SToomas Soome         {
664c65ebfc7SToomas Soome             // If our new query is a duplicate, then it can't have a socket of its own, so we have to close the one we saved.
665c65ebfc7SToomas Soome             if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
666c65ebfc7SToomas Soome             else
667c65ebfc7SToomas Soome             {
668c65ebfc7SToomas Soome                 // Transplant the old socket into the new question, and copy the query ID across too.
669c65ebfc7SToomas Soome                 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
670c65ebfc7SToomas Soome                 q->LocalSocket = sock;
671c65ebfc7SToomas Soome                 q->TargetQID = id;
672c65ebfc7SToomas Soome             }
673c65ebfc7SToomas Soome         }
674c65ebfc7SToomas Soome     }
675c65ebfc7SToomas Soome }
676c65ebfc7SToomas Soome 
677c65ebfc7SToomas Soome #ifdef USE_LIBIDN
678c65ebfc7SToomas Soome 
679c65ebfc7SToomas Soome #include <unicode/uidna.h>
680c65ebfc7SToomas Soome 
681c65ebfc7SToomas Soome // #define DEBUG_PUNYCODE 1
682c65ebfc7SToomas Soome 
PunycodeConvert(const mDNSu8 * const src,mDNSu8 * const dst,const mDNSu8 * const end)683c65ebfc7SToomas Soome mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end)
684c65ebfc7SToomas Soome {
685c65ebfc7SToomas Soome     UErrorCode errorCode = U_ZERO_ERROR;
686c65ebfc7SToomas Soome     UIDNAInfo info = UIDNA_INFO_INITIALIZER;
687c65ebfc7SToomas Soome     UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode);
688*472cd20dSToomas Soome     int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, (int32_t)(end-(dst+1)), &info, &errorCode);
689c65ebfc7SToomas Soome     uidna_close(uts46);
690c65ebfc7SToomas Soome     #if DEBUG_PUNYCODE
691c65ebfc7SToomas Soome     if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode);
692c65ebfc7SToomas Soome     if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors);
693c65ebfc7SToomas Soome     if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len);
694c65ebfc7SToomas Soome     #endif
695c65ebfc7SToomas Soome     if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL;
696c65ebfc7SToomas Soome     *dst = len;
697c65ebfc7SToomas Soome     return(dst + 1 + len);
698c65ebfc7SToomas Soome }
699c65ebfc7SToomas Soome 
IsHighASCIILabel(const mDNSu8 * d)700c65ebfc7SToomas Soome mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d)
701c65ebfc7SToomas Soome {
702c65ebfc7SToomas Soome     int i;
703c65ebfc7SToomas Soome     for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue;
704c65ebfc7SToomas Soome     return mDNSfalse;
705c65ebfc7SToomas Soome }
706c65ebfc7SToomas Soome 
FindLastHighASCIILabel(const domainname * const d)707c65ebfc7SToomas Soome mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d)
708c65ebfc7SToomas Soome {
709c65ebfc7SToomas Soome     const mDNSu8 *ptr = d->c;
710c65ebfc7SToomas Soome     const mDNSu8 *ans = mDNSNULL;
711c65ebfc7SToomas Soome     while (ptr[0])
712c65ebfc7SToomas Soome     {
713c65ebfc7SToomas Soome         const mDNSu8 *const next = ptr + 1 + ptr[0];
714c65ebfc7SToomas Soome         if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL;
715c65ebfc7SToomas Soome         if (IsHighASCIILabel(ptr)) ans = ptr;
716c65ebfc7SToomas Soome         ptr = next;
717c65ebfc7SToomas Soome     }
718c65ebfc7SToomas Soome     return ans;
719c65ebfc7SToomas Soome }
720c65ebfc7SToomas Soome 
PerformNextPunycodeConversion(const DNSQuestion * const q,domainname * const newname)721c65ebfc7SToomas Soome mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname)
722c65ebfc7SToomas Soome {
723c65ebfc7SToomas Soome     const mDNSu8 *h = FindLastHighASCIILabel(&q->qname);
724c65ebfc7SToomas Soome     #if DEBUG_PUNYCODE
725c65ebfc7SToomas Soome     LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h);
726c65ebfc7SToomas Soome     #endif
727c65ebfc7SToomas Soome     if (!h) return mDNSfalse;  // There are no high-ascii labels to convert
728c65ebfc7SToomas Soome 
729c65ebfc7SToomas Soome     mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME);
730c65ebfc7SToomas Soome     if (!dst)
731c65ebfc7SToomas Soome         return mDNSfalse;  // The label was not convertible to Punycode
732c65ebfc7SToomas Soome     else
733c65ebfc7SToomas Soome     {
734c65ebfc7SToomas Soome         // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
735c65ebfc7SToomas Soome         const mDNSu8 *const src = h + 1 + h[0];
736c65ebfc7SToomas Soome         const mDNSu8 remainder  = DomainNameLength((domainname*)src);
737c65ebfc7SToomas Soome         if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse;  // Name too long -- cannot be converted to Punycode
738c65ebfc7SToomas Soome 
739*472cd20dSToomas Soome         mDNSPlatformMemCopy(newname->c, q->qname.c, (mDNSu32)(h - q->qname.c));  // Fill in the leading part
740c65ebfc7SToomas Soome         mDNSPlatformMemCopy(dst, src, remainder);                     // Fill in the trailing part
741c65ebfc7SToomas Soome         #if DEBUG_PUNYCODE
742c65ebfc7SToomas Soome         LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c);
743c65ebfc7SToomas Soome         #endif
744c65ebfc7SToomas Soome         return mDNStrue;
745c65ebfc7SToomas Soome     }
746c65ebfc7SToomas Soome }
747c65ebfc7SToomas Soome 
748c65ebfc7SToomas Soome #endif // USE_LIBIDN
749c65ebfc7SToomas Soome 
750c65ebfc7SToomas Soome // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
751c65ebfc7SToomas Soome // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
AnswerLocalQuestionWithLocalAuthRecord(mDNS * const m,AuthRecord * rr,QC_result AddRecord)752c65ebfc7SToomas Soome mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
753c65ebfc7SToomas Soome {
754c65ebfc7SToomas Soome     DNSQuestion *q = m->CurrentQuestion;
755c65ebfc7SToomas Soome     mDNSBool followcname;
756c65ebfc7SToomas Soome 
757c65ebfc7SToomas Soome     if (!q)
758c65ebfc7SToomas Soome     {
759c65ebfc7SToomas Soome         LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
760c65ebfc7SToomas Soome         return;
761c65ebfc7SToomas Soome     }
762c65ebfc7SToomas Soome 
763c65ebfc7SToomas Soome     followcname = FollowCNAME(q, &rr->resrec, AddRecord);
764c65ebfc7SToomas Soome 
765c65ebfc7SToomas Soome     // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
766c65ebfc7SToomas Soome     if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
767c65ebfc7SToomas Soome     {
768c65ebfc7SToomas Soome         LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
769c65ebfc7SToomas Soome                AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
770c65ebfc7SToomas Soome         return;
771c65ebfc7SToomas Soome     }
772c65ebfc7SToomas Soome 
773c65ebfc7SToomas Soome     // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
774c65ebfc7SToomas Soome     if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
775c65ebfc7SToomas Soome     mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
776c65ebfc7SToomas Soome     if (q->QuestionCallback && !q->NoAnswer)
777c65ebfc7SToomas Soome     {
778c65ebfc7SToomas Soome         q->CurrentAnswers += AddRecord ? 1 : -1;
779c65ebfc7SToomas Soome         if (UniqueLocalOnlyRecord(rr))
780c65ebfc7SToomas Soome         {
781c65ebfc7SToomas Soome             if (!followcname || q->ReturnIntermed)
782c65ebfc7SToomas Soome             {
783c65ebfc7SToomas Soome                 // Don't send this packet on the wire as we answered from /etc/hosts
784c65ebfc7SToomas Soome                 q->ThisQInterval = 0;
785c65ebfc7SToomas Soome                 q->LOAddressAnswers += AddRecord ? 1 : -1;
786c65ebfc7SToomas Soome                 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
787c65ebfc7SToomas Soome             }
788c65ebfc7SToomas Soome             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
789c65ebfc7SToomas Soome             // The callback above could have caused the question to stop. Detect that
790c65ebfc7SToomas Soome             // using m->CurrentQuestion
791c65ebfc7SToomas Soome             if (followcname && m->CurrentQuestion == q)
792c65ebfc7SToomas Soome                 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
793c65ebfc7SToomas Soome             return;
794c65ebfc7SToomas Soome         }
795c65ebfc7SToomas Soome         else
796c65ebfc7SToomas Soome         {
797c65ebfc7SToomas Soome             q->QuestionCallback(m, q, &rr->resrec, AddRecord);
798c65ebfc7SToomas Soome         }
799c65ebfc7SToomas Soome     }
800c65ebfc7SToomas Soome     mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
801c65ebfc7SToomas Soome }
802c65ebfc7SToomas Soome 
AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS * const m,AuthRecord * ar,QC_result AddRecord)803*472cd20dSToomas Soome mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
804c65ebfc7SToomas Soome {
805c65ebfc7SToomas Soome     if (m->CurrentQuestion)
806c65ebfc7SToomas Soome         LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
807c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
808c65ebfc7SToomas Soome     m->CurrentQuestion = m->Questions;
809c65ebfc7SToomas Soome     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
810c65ebfc7SToomas Soome     {
811c65ebfc7SToomas Soome         mDNSBool answered;
812c65ebfc7SToomas Soome         DNSQuestion *q = m->CurrentQuestion;
813*472cd20dSToomas Soome         if (RRAny(ar))
814*472cd20dSToomas Soome             answered = AuthRecordAnswersQuestion(ar, q);
815c65ebfc7SToomas Soome         else
816*472cd20dSToomas Soome             answered = LocalOnlyRecordAnswersQuestion(ar, q);
817c65ebfc7SToomas Soome         if (answered)
818*472cd20dSToomas Soome             AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord);       // MUST NOT dereference q again
819c65ebfc7SToomas Soome         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
820c65ebfc7SToomas Soome             m->CurrentQuestion = q->next;
821c65ebfc7SToomas Soome     }
822c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
823c65ebfc7SToomas Soome }
824c65ebfc7SToomas Soome 
825c65ebfc7SToomas Soome // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
826c65ebfc7SToomas Soome // delivers the appropriate add/remove events to listening questions:
827c65ebfc7SToomas Soome // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
828c65ebfc7SToomas Soome //    stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
829c65ebfc7SToomas Soome // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
830c65ebfc7SToomas Soome //    our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
831c65ebfc7SToomas Soome //    stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
832c65ebfc7SToomas Soome //
833c65ebfc7SToomas Soome // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
834c65ebfc7SToomas Soome // and by mDNS_Deregister_internal()
835c65ebfc7SToomas Soome 
AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS * const m,AuthRecord * ar,QC_result AddRecord)836*472cd20dSToomas Soome mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
837c65ebfc7SToomas Soome {
838c65ebfc7SToomas Soome     if (m->CurrentQuestion)
839c65ebfc7SToomas Soome         LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
840c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
841c65ebfc7SToomas Soome 
842c65ebfc7SToomas Soome     m->CurrentQuestion = m->LocalOnlyQuestions;
843c65ebfc7SToomas Soome     while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
844c65ebfc7SToomas Soome     {
845c65ebfc7SToomas Soome         mDNSBool answered;
846c65ebfc7SToomas Soome         DNSQuestion *q = m->CurrentQuestion;
847c65ebfc7SToomas Soome         // We are called with both LocalOnly/P2P record or a regular AuthRecord
848*472cd20dSToomas Soome         if (RRAny(ar))
849*472cd20dSToomas Soome             answered = AuthRecordAnswersQuestion(ar, q);
850c65ebfc7SToomas Soome         else
851*472cd20dSToomas Soome             answered = LocalOnlyRecordAnswersQuestion(ar, q);
852c65ebfc7SToomas Soome         if (answered)
853*472cd20dSToomas Soome             AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord);           // MUST NOT dereference q again
854c65ebfc7SToomas Soome         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
855c65ebfc7SToomas Soome             m->CurrentQuestion = q->next;
856c65ebfc7SToomas Soome     }
857c65ebfc7SToomas Soome 
858c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
859c65ebfc7SToomas Soome 
860c65ebfc7SToomas Soome     // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
861*472cd20dSToomas Soome     if (ar->ARType == AuthRecordLocalOnly || ar->ARType == AuthRecordP2P)
862*472cd20dSToomas Soome         AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, ar, AddRecord);
863c65ebfc7SToomas Soome 
864c65ebfc7SToomas Soome }
865c65ebfc7SToomas Soome 
866c65ebfc7SToomas Soome // ***************************************************************************
867c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
868c65ebfc7SToomas Soome #pragma mark -
869c65ebfc7SToomas Soome #pragma mark - Resource Record Utility Functions
870c65ebfc7SToomas Soome #endif
871c65ebfc7SToomas Soome 
872c65ebfc7SToomas Soome #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
873c65ebfc7SToomas Soome 
ResourceRecordIsValidAnswer(const AuthRecord * const rr)874*472cd20dSToomas Soome mDNSlocal mDNSBool ResourceRecordIsValidAnswer(const AuthRecord *const rr)
875*472cd20dSToomas Soome {
876*472cd20dSToomas Soome     if ((rr->resrec.RecordType & kDNSRecordTypeActiveMask) &&
877*472cd20dSToomas Soome         ((rr->Additional1 == mDNSNULL) || (rr->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
878*472cd20dSToomas Soome         ((rr->Additional2 == mDNSNULL) || (rr->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
879*472cd20dSToomas Soome         ((rr->DependentOn == mDNSNULL) || (rr->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)))
880*472cd20dSToomas Soome     {
881*472cd20dSToomas Soome         return mDNStrue;
882*472cd20dSToomas Soome     }
883*472cd20dSToomas Soome     else
884*472cd20dSToomas Soome     {
885*472cd20dSToomas Soome         return mDNSfalse;
886*472cd20dSToomas Soome     }
887*472cd20dSToomas Soome }
888c65ebfc7SToomas Soome 
IsInterfaceValidForAuthRecord(const AuthRecord * const rr,const mDNSInterfaceID InterfaceID)889*472cd20dSToomas Soome mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *const rr, const mDNSInterfaceID InterfaceID)
890*472cd20dSToomas Soome {
891*472cd20dSToomas Soome     if (rr->resrec.InterfaceID == mDNSInterface_Any)
892*472cd20dSToomas Soome     {
893*472cd20dSToomas Soome         return mDNSPlatformValidRecordForInterface(rr, InterfaceID);
894*472cd20dSToomas Soome     }
895*472cd20dSToomas Soome     else
896*472cd20dSToomas Soome     {
897*472cd20dSToomas Soome         return ((rr->resrec.InterfaceID == InterfaceID) ? mDNStrue : mDNSfalse);
898*472cd20dSToomas Soome     }
899*472cd20dSToomas Soome }
900*472cd20dSToomas Soome 
ResourceRecordIsValidInterfaceAnswer(const AuthRecord * const rr,const mDNSInterfaceID interfaceID)901*472cd20dSToomas Soome mDNSlocal mDNSBool ResourceRecordIsValidInterfaceAnswer(const AuthRecord *const rr, const mDNSInterfaceID interfaceID)
902*472cd20dSToomas Soome {
903*472cd20dSToomas Soome     return ((IsInterfaceValidForAuthRecord(rr, interfaceID) && ResourceRecordIsValidAnswer(rr)) ? mDNStrue : mDNSfalse);
904*472cd20dSToomas Soome }
905c65ebfc7SToomas Soome 
906c65ebfc7SToomas Soome #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
907c65ebfc7SToomas Soome #define DefaultProbeCountForRecordType(X)      ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
908c65ebfc7SToomas Soome 
909*472cd20dSToomas Soome // Parameters for handling probing conflicts
910*472cd20dSToomas Soome #define kMaxAllowedMCastProbingConflicts 1                     // Maximum number of conflicts to allow from mcast messages.
911*472cd20dSToomas Soome #define kProbingConflictPauseDuration    mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
912*472cd20dSToomas Soome 
913c65ebfc7SToomas Soome // See RFC 6762: "8.3 Announcing"
914c65ebfc7SToomas Soome // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
915c65ebfc7SToomas Soome // Send 4, which is really 8 since we send on both IPv4 and IPv6.
916c65ebfc7SToomas Soome #define InitialAnnounceCount ((mDNSu8)4)
917c65ebfc7SToomas Soome 
918c65ebfc7SToomas Soome // For goodbye packets we set the count to 3, and for wakeups we set it to 18
919c65ebfc7SToomas Soome // (which will be up to 15 wakeup attempts over the course of 30 seconds,
920c65ebfc7SToomas Soome // and then if the machine fails to wake, 3 goodbye packets).
921c65ebfc7SToomas Soome #define GoodbyeCount ((mDNSu8)3)
922c65ebfc7SToomas Soome #define WakeupCount ((mDNSu8)18)
923c65ebfc7SToomas Soome #define MAX_PROBE_RESTARTS ((mDNSu8)20)
9243b436d06SToomas Soome #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond))  //  One week
925c65ebfc7SToomas Soome 
926c65ebfc7SToomas Soome // Number of wakeups we send if WakeOnResolve is set in the question
927c65ebfc7SToomas Soome #define InitialWakeOnResolveCount ((mDNSu8)3)
928c65ebfc7SToomas Soome 
929c65ebfc7SToomas Soome // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
930c65ebfc7SToomas Soome // This means that because the announce interval is doubled after sending the first packet, the first
931c65ebfc7SToomas Soome // observed on-the-wire inter-packet interval between announcements is actually one second.
932c65ebfc7SToomas Soome // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
933c65ebfc7SToomas Soome #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
934c65ebfc7SToomas Soome #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
935c65ebfc7SToomas Soome #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
936c65ebfc7SToomas Soome 
937c65ebfc7SToomas Soome #define DefaultAPIntervalForRecordType(X)  ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
938c65ebfc7SToomas Soome                                             (X) &kDNSRecordTypeUnique           ? DefaultProbeIntervalForTypeUnique    : \
939c65ebfc7SToomas Soome                                             (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
940c65ebfc7SToomas Soome 
941c65ebfc7SToomas Soome #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
942c65ebfc7SToomas Soome #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
943c65ebfc7SToomas Soome #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
944c65ebfc7SToomas Soome 
945c65ebfc7SToomas Soome // Adjustment factor to avoid race condition (used for unicast cache entries) :
946c65ebfc7SToomas Soome // 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.
947c65ebfc7SToomas Soome // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
948c65ebfc7SToomas Soome // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
949c65ebfc7SToomas Soome // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
950*472cd20dSToomas Soome // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
951c65ebfc7SToomas Soome // the cached copy at our local caching server will already have expired, so the server will be forced
952c65ebfc7SToomas Soome // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
953c65ebfc7SToomas Soome 
954c65ebfc7SToomas Soome #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
955c65ebfc7SToomas Soome #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
956c65ebfc7SToomas Soome 
957c65ebfc7SToomas Soome #define MaxUnansweredQueries 4
958c65ebfc7SToomas Soome 
959c65ebfc7SToomas Soome // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
960c65ebfc7SToomas Soome // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
961c65ebfc7SToomas Soome // TTL and rdata may differ.
962c65ebfc7SToomas Soome // This is used for cache flush management:
963c65ebfc7SToomas Soome // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
964c65ebfc7SToomas Soome // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
965c65ebfc7SToomas Soome 
966c65ebfc7SToomas Soome // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
967c65ebfc7SToomas Soome 
968c65ebfc7SToomas Soome #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
969c65ebfc7SToomas Soome 
SameResourceRecordNameClassInterface(const AuthRecord * const r1,const AuthRecord * const r2)970c65ebfc7SToomas Soome mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
971c65ebfc7SToomas Soome {
972c65ebfc7SToomas Soome     if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
973c65ebfc7SToomas Soome     if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
974c65ebfc7SToomas Soome     if (r1->resrec.InterfaceID &&
975c65ebfc7SToomas Soome         r2->resrec.InterfaceID &&
976c65ebfc7SToomas Soome         r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
977c65ebfc7SToomas Soome     return (mDNSBool)(
978c65ebfc7SToomas Soome                r1->resrec.rrclass  == r2->resrec.rrclass &&
979c65ebfc7SToomas Soome                r1->resrec.namehash == r2->resrec.namehash &&
980c65ebfc7SToomas Soome                SameDomainName(r1->resrec.name, r2->resrec.name));
981c65ebfc7SToomas Soome }
982c65ebfc7SToomas Soome 
983c65ebfc7SToomas Soome // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
984c65ebfc7SToomas Soome // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
985c65ebfc7SToomas Soome // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
986c65ebfc7SToomas Soome // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
987c65ebfc7SToomas Soome // so a response of any type should match, even if it is not actually the type the client plans to use.
988c65ebfc7SToomas Soome 
989c65ebfc7SToomas Soome // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
990c65ebfc7SToomas Soome // and require the rrtypes to match for the rdata to be considered potentially conflicting
PacketRRMatchesSignature(const CacheRecord * const pktrr,const AuthRecord * const authrr)991c65ebfc7SToomas Soome mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
992c65ebfc7SToomas Soome {
993c65ebfc7SToomas Soome     if (!pktrr)  { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
994c65ebfc7SToomas Soome     if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
995c65ebfc7SToomas Soome     if (pktrr->resrec.InterfaceID &&
996c65ebfc7SToomas Soome         authrr->resrec.InterfaceID &&
997c65ebfc7SToomas Soome         pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
998c65ebfc7SToomas Soome     if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
999c65ebfc7SToomas Soome         if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
1000c65ebfc7SToomas Soome     if ((authrr->resrec.InterfaceID == mDNSInterface_Any) &&
1001c65ebfc7SToomas Soome         !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse);
1002c65ebfc7SToomas Soome     return (mDNSBool)(
1003c65ebfc7SToomas Soome                pktrr->resrec.rrclass == authrr->resrec.rrclass &&
1004c65ebfc7SToomas Soome                pktrr->resrec.namehash == authrr->resrec.namehash &&
1005c65ebfc7SToomas Soome                SameDomainName(pktrr->resrec.name, authrr->resrec.name));
1006c65ebfc7SToomas Soome }
1007c65ebfc7SToomas Soome 
1008c65ebfc7SToomas Soome // CacheRecord *ka is the CacheRecord from the known answer list in the query.
1009c65ebfc7SToomas Soome // This is the information that the requester believes to be correct.
1010c65ebfc7SToomas Soome // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
1011c65ebfc7SToomas Soome // This is the information that we believe to be correct.
1012c65ebfc7SToomas Soome // We've already determined that we plan to give this answer on this interface
1013c65ebfc7SToomas Soome // (either the record is non-specific, or it is specific to this interface)
1014c65ebfc7SToomas Soome // so now we just need to check the name, type, class, rdata and TTL.
ShouldSuppressKnownAnswer(const CacheRecord * const ka,const AuthRecord * const rr)1015c65ebfc7SToomas Soome mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
1016c65ebfc7SToomas Soome {
1017c65ebfc7SToomas Soome     // If RR signature is different, or data is different, then don't suppress our answer
1018c65ebfc7SToomas Soome     if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
1019c65ebfc7SToomas Soome 
1020c65ebfc7SToomas Soome     // If the requester's indicated TTL is less than half the real TTL,
1021c65ebfc7SToomas Soome     // we need to give our answer before the requester's copy expires.
1022c65ebfc7SToomas Soome     // If the requester's indicated TTL is at least half the real TTL,
1023c65ebfc7SToomas Soome     // then we can suppress our answer this time.
1024c65ebfc7SToomas Soome     // If the requester's indicated TTL is greater than the TTL we believe,
1025c65ebfc7SToomas Soome     // then that's okay, and we don't need to do anything about it.
1026c65ebfc7SToomas Soome     // (If two responders on the network are offering the same information,
1027c65ebfc7SToomas Soome     // that's okay, and if they are offering the information with different TTLs,
1028c65ebfc7SToomas Soome     // the one offering the lower TTL should defer to the one offering the higher TTL.)
1029c65ebfc7SToomas Soome     return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
1030c65ebfc7SToomas Soome }
1031c65ebfc7SToomas Soome 
SetNextAnnounceProbeTime(mDNS * const m,const AuthRecord * const rr)1032c65ebfc7SToomas Soome mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
1033c65ebfc7SToomas Soome {
1034c65ebfc7SToomas Soome     if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1035c65ebfc7SToomas Soome     {
1036c65ebfc7SToomas Soome         if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
1037c65ebfc7SToomas Soome         {
1038c65ebfc7SToomas Soome             LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
1039c65ebfc7SToomas Soome             LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
1040c65ebfc7SToomas Soome         }
1041c65ebfc7SToomas Soome         if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1042c65ebfc7SToomas Soome             m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
1043c65ebfc7SToomas Soome         // Some defensive code:
1044c65ebfc7SToomas Soome         // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1045c65ebfc7SToomas Soome         // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1046c65ebfc7SToomas Soome         // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1047c65ebfc7SToomas Soome         if (m->NextScheduledProbe - m->timenow < 0)
1048c65ebfc7SToomas Soome             m->NextScheduledProbe = m->timenow;
1049c65ebfc7SToomas Soome     }
1050c65ebfc7SToomas Soome     else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
1051c65ebfc7SToomas Soome     {
1052c65ebfc7SToomas Soome         if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1053c65ebfc7SToomas Soome             m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
1054c65ebfc7SToomas Soome     }
1055c65ebfc7SToomas Soome }
1056c65ebfc7SToomas Soome 
InitializeLastAPTime(mDNS * const m,AuthRecord * const rr)1057c65ebfc7SToomas Soome mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
1058c65ebfc7SToomas Soome {
1059c65ebfc7SToomas Soome     // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1060c65ebfc7SToomas Soome     rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
1061c65ebfc7SToomas Soome 
1062c65ebfc7SToomas Soome     // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1063c65ebfc7SToomas Soome     // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1064c65ebfc7SToomas Soome     //   records that are going to probe, then we delay its first announcement so that it will
1065c65ebfc7SToomas Soome     //   go out synchronized with the first announcement for the other records that *are* probing.
1066c65ebfc7SToomas Soome     //   This is a minor performance tweak that helps keep groups of related records synchronized together.
1067c65ebfc7SToomas Soome     //   The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1068c65ebfc7SToomas Soome     //   delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1069c65ebfc7SToomas Soome     //   When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1070c65ebfc7SToomas Soome     //   because they will meet the criterion of being at least half-way to their scheduled announcement time.
1071c65ebfc7SToomas Soome     // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1072c65ebfc7SToomas Soome 
1073c65ebfc7SToomas Soome     if (rr->ProbeCount)
1074c65ebfc7SToomas Soome     {
1075*472cd20dSToomas Soome         rr->ProbingConflictCount = 0;
1076c65ebfc7SToomas Soome         // If we have no probe suppression time set, or it is in the past, set it now
1077c65ebfc7SToomas Soome         if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
1078c65ebfc7SToomas Soome         {
1079c65ebfc7SToomas Soome             // To allow us to aggregate probes when a group of services are registered together,
1080c65ebfc7SToomas Soome             // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1081c65ebfc7SToomas Soome             // This means the common-case behaviour is:
1082c65ebfc7SToomas Soome             // randomized wait; probe
1083c65ebfc7SToomas Soome             // 1/4 second wait; probe
1084c65ebfc7SToomas Soome             // 1/4 second wait; probe
1085c65ebfc7SToomas Soome             // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1086c65ebfc7SToomas Soome             m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1087c65ebfc7SToomas Soome 
1088c65ebfc7SToomas Soome             // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1089c65ebfc7SToomas Soome             if (m->SuppressProbes - m->NextScheduledProbe >= 0)
1090c65ebfc7SToomas Soome                 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
1091c65ebfc7SToomas Soome             if (m->SuppressProbes - m->timenow < 0)     // Make sure we don't set m->SuppressProbes excessively in the past
1092c65ebfc7SToomas Soome                 m->SuppressProbes = m->timenow;
1093c65ebfc7SToomas Soome 
1094c65ebfc7SToomas Soome             // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1095c65ebfc7SToomas Soome             if (m->SuppressProbes - m->NextScheduledQuery >= 0)
1096c65ebfc7SToomas Soome                 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
1097c65ebfc7SToomas Soome             if (m->SuppressProbes - m->timenow < 0)     // Make sure we don't set m->SuppressProbes excessively in the past
1098c65ebfc7SToomas Soome                 m->SuppressProbes = m->timenow;
1099c65ebfc7SToomas Soome 
1100c65ebfc7SToomas Soome             // except... don't expect to be able to send before the m->SuppressSending timer fires
1101c65ebfc7SToomas Soome             if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
1102c65ebfc7SToomas Soome                 m->SuppressProbes = NonZeroTime(m->SuppressSending);
1103c65ebfc7SToomas Soome 
1104c65ebfc7SToomas Soome             if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
1105c65ebfc7SToomas Soome             {
1106c65ebfc7SToomas Soome                 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1107c65ebfc7SToomas Soome                        m->SuppressProbes     - m->timenow,
1108c65ebfc7SToomas Soome                        m->NextScheduledProbe - m->timenow,
1109c65ebfc7SToomas Soome                        m->NextScheduledQuery - m->timenow,
1110c65ebfc7SToomas Soome                        m->SuppressSending,
1111c65ebfc7SToomas Soome                        m->SuppressSending    - m->timenow);
1112c65ebfc7SToomas Soome                 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1113c65ebfc7SToomas Soome             }
1114c65ebfc7SToomas Soome         }
1115c65ebfc7SToomas Soome         rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
1116c65ebfc7SToomas Soome     }
1117c65ebfc7SToomas Soome     // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1118c65ebfc7SToomas Soome     // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1119c65ebfc7SToomas Soome     else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0))
1120c65ebfc7SToomas Soome         rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
1121c65ebfc7SToomas Soome     else
1122c65ebfc7SToomas Soome         rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1123c65ebfc7SToomas Soome 
1124c65ebfc7SToomas Soome     // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1125c65ebfc7SToomas Soome     // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1126c65ebfc7SToomas Soome     // After three probes one second apart with no answer, we conclude the client is now sleeping
1127c65ebfc7SToomas Soome     // and we can begin broadcasting our announcements to take over ownership of that IP address.
1128c65ebfc7SToomas Soome     // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1129c65ebfc7SToomas Soome     // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1130c65ebfc7SToomas Soome     if (rr->AddressProxy.type)
1131c65ebfc7SToomas Soome         rr->LastAPTime = m->timenow;
1132c65ebfc7SToomas Soome 
1133c65ebfc7SToomas Soome     // Set LastMCTime to now, to inhibit multicast responses
1134c65ebfc7SToomas Soome     // (no need to send additional multicast responses when we're announcing anyway)
1135c65ebfc7SToomas Soome     rr->LastMCTime      = m->timenow;
1136c65ebfc7SToomas Soome     rr->LastMCInterface = mDNSInterfaceMark;
1137c65ebfc7SToomas Soome 
1138c65ebfc7SToomas Soome     SetNextAnnounceProbeTime(m, rr);
1139c65ebfc7SToomas Soome }
1140c65ebfc7SToomas Soome 
SetUnicastTargetToHostName(mDNS * const m,AuthRecord * rr)1141c65ebfc7SToomas Soome mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
1142c65ebfc7SToomas Soome {
1143c65ebfc7SToomas Soome     const domainname *target;
1144c65ebfc7SToomas Soome     if (rr->AutoTarget)
1145c65ebfc7SToomas Soome     {
1146*472cd20dSToomas Soome         rr->AutoTarget = Target_AutoHostAndNATMAP;
1147c65ebfc7SToomas Soome     }
1148c65ebfc7SToomas Soome 
1149c65ebfc7SToomas Soome     target = GetServiceTarget(m, rr);
1150c65ebfc7SToomas Soome     if (!target || target->c[0] == 0)
1151c65ebfc7SToomas Soome     {
1152c65ebfc7SToomas Soome         // defer registration until we've got a target
1153c65ebfc7SToomas Soome         LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
1154c65ebfc7SToomas Soome         rr->state = regState_NoTarget;
1155c65ebfc7SToomas Soome         return mDNSNULL;
1156c65ebfc7SToomas Soome     }
1157c65ebfc7SToomas Soome     else
1158c65ebfc7SToomas Soome     {
1159c65ebfc7SToomas Soome         LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
1160c65ebfc7SToomas Soome         return target;
1161c65ebfc7SToomas Soome     }
1162c65ebfc7SToomas Soome }
1163c65ebfc7SToomas Soome 
1164*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
AuthRecordIncludesOrIsAWDL(const AuthRecord * const ar)1165*472cd20dSToomas Soome mDNSlocal mDNSBool AuthRecordIncludesOrIsAWDL(const AuthRecord *const ar)
1166*472cd20dSToomas Soome {
1167*472cd20dSToomas Soome     return ((AuthRecordIncludesAWDL(ar) || mDNSPlatformInterfaceIsAWDL(ar->resrec.InterfaceID)) ? mDNStrue : mDNSfalse);
1168*472cd20dSToomas Soome }
1169*472cd20dSToomas Soome #endif
1170*472cd20dSToomas Soome 
1171c65ebfc7SToomas Soome // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1172c65ebfc7SToomas Soome // Eventually we should unify this with GetServiceTarget() in uDNS.c
SetTargetToHostName(mDNS * const m,AuthRecord * const rr)1173c65ebfc7SToomas Soome mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
1174c65ebfc7SToomas Soome {
1175c65ebfc7SToomas Soome     domainname *const target = GetRRDomainNameTarget(&rr->resrec);
1176*472cd20dSToomas Soome     const domainname *newname;
1177c65ebfc7SToomas Soome 
1178*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1179*472cd20dSToomas Soome     if (AuthRecordIncludesOrIsAWDL(rr))
1180*472cd20dSToomas Soome     {
1181*472cd20dSToomas Soome         newname = &m->RandomizedHostname;
1182*472cd20dSToomas Soome     }
1183*472cd20dSToomas Soome     else
1184*472cd20dSToomas Soome #endif
1185*472cd20dSToomas Soome     {
1186*472cd20dSToomas Soome         newname = &m->MulticastHostname;
1187*472cd20dSToomas Soome     }
1188c65ebfc7SToomas Soome     if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
1189c65ebfc7SToomas Soome 
1190c65ebfc7SToomas Soome     if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
1191c65ebfc7SToomas Soome     {
1192c65ebfc7SToomas Soome         const domainname *const n = SetUnicastTargetToHostName(m, rr);
1193c65ebfc7SToomas Soome         if (n) newname = n;
1194c65ebfc7SToomas Soome         else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
1195c65ebfc7SToomas Soome     }
1196c65ebfc7SToomas Soome 
1197c65ebfc7SToomas Soome     if (target && SameDomainName(target, newname))
1198c65ebfc7SToomas Soome         debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
1199c65ebfc7SToomas Soome 
1200c65ebfc7SToomas Soome     if (target && !SameDomainName(target, newname))
1201c65ebfc7SToomas Soome     {
1202c65ebfc7SToomas Soome         AssignDomainName(target, newname);
1203c65ebfc7SToomas Soome         SetNewRData(&rr->resrec, mDNSNULL, 0);      // Update rdlength, rdestimate, rdatahash
1204c65ebfc7SToomas Soome 
1205c65ebfc7SToomas Soome         // If we're in the middle of probing this record, we need to start again,
1206c65ebfc7SToomas Soome         // because changing its rdata may change the outcome of the tie-breaker.
1207c65ebfc7SToomas Soome         // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1208c65ebfc7SToomas Soome         rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1209c65ebfc7SToomas Soome 
1210c65ebfc7SToomas Soome         // If we've announced this record, we really should send a goodbye packet for the old rdata before
1211c65ebfc7SToomas Soome         // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1212c65ebfc7SToomas Soome         // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1213c65ebfc7SToomas Soome         if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
1214c65ebfc7SToomas Soome             debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1215c65ebfc7SToomas Soome                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1216c65ebfc7SToomas Soome 
1217c65ebfc7SToomas Soome         rr->AnnounceCount  = InitialAnnounceCount;
1218c65ebfc7SToomas Soome         rr->RequireGoodbye = mDNSfalse;
1219c65ebfc7SToomas Soome         rr->ProbeRestartCount = 0;
1220c65ebfc7SToomas Soome         InitializeLastAPTime(m, rr);
1221c65ebfc7SToomas Soome     }
1222c65ebfc7SToomas Soome }
1223c65ebfc7SToomas Soome 
AcknowledgeRecord(mDNS * const m,AuthRecord * const rr)1224c65ebfc7SToomas Soome mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
1225c65ebfc7SToomas Soome {
1226c65ebfc7SToomas Soome     if (rr->RecordCallback)
1227c65ebfc7SToomas Soome     {
1228c65ebfc7SToomas Soome         // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1229c65ebfc7SToomas Soome         // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1230c65ebfc7SToomas Soome         rr->Acknowledged = mDNStrue;
1231c65ebfc7SToomas Soome         mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
1232c65ebfc7SToomas Soome         rr->RecordCallback(m, rr, mStatus_NoError);
1233c65ebfc7SToomas Soome         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
1234c65ebfc7SToomas Soome     }
1235c65ebfc7SToomas Soome }
1236c65ebfc7SToomas Soome 
ActivateUnicastRegistration(mDNS * const m,AuthRecord * const rr)1237c65ebfc7SToomas Soome mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
1238c65ebfc7SToomas Soome {
1239c65ebfc7SToomas Soome     // Make sure that we don't activate the SRV record and associated service records, if it is in
1240c65ebfc7SToomas Soome     // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1241c65ebfc7SToomas Soome     // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1242c65ebfc7SToomas Soome     // the target becomes available, the records will be reregistered.
1243c65ebfc7SToomas Soome     if (rr->resrec.rrtype != kDNSType_SRV)
1244c65ebfc7SToomas Soome     {
1245c65ebfc7SToomas Soome         AuthRecord *srvRR = mDNSNULL;
1246c65ebfc7SToomas Soome         if (rr->resrec.rrtype == kDNSType_PTR)
1247c65ebfc7SToomas Soome             srvRR = rr->Additional1;
1248c65ebfc7SToomas Soome         else if (rr->resrec.rrtype == kDNSType_TXT)
1249c65ebfc7SToomas Soome             srvRR = rr->DependentOn;
1250c65ebfc7SToomas Soome         if (srvRR)
1251c65ebfc7SToomas Soome         {
1252c65ebfc7SToomas Soome             if (srvRR->resrec.rrtype != kDNSType_SRV)
1253c65ebfc7SToomas Soome             {
1254c65ebfc7SToomas Soome                 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1255c65ebfc7SToomas Soome             }
1256c65ebfc7SToomas Soome             else
1257c65ebfc7SToomas Soome             {
1258c65ebfc7SToomas Soome                 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1259c65ebfc7SToomas Soome                         ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1260c65ebfc7SToomas Soome                 rr->state = srvRR->state;
1261c65ebfc7SToomas Soome             }
1262c65ebfc7SToomas Soome         }
1263c65ebfc7SToomas Soome     }
1264c65ebfc7SToomas Soome 
1265c65ebfc7SToomas Soome     if (rr->state == regState_NoTarget)
1266c65ebfc7SToomas Soome     {
1267c65ebfc7SToomas Soome         LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1268c65ebfc7SToomas Soome         return;
1269c65ebfc7SToomas Soome     }
1270c65ebfc7SToomas Soome     // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1271c65ebfc7SToomas Soome     // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1272c65ebfc7SToomas Soome     // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1273c65ebfc7SToomas Soome     // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1274c65ebfc7SToomas Soome     // 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.
1275c65ebfc7SToomas Soome     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1276c65ebfc7SToomas Soome     {
1277c65ebfc7SToomas Soome         LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1278c65ebfc7SToomas Soome         rr->state = regState_DeregPending;
1279c65ebfc7SToomas Soome     }
1280c65ebfc7SToomas Soome     else
1281c65ebfc7SToomas Soome     {
1282c65ebfc7SToomas Soome         LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1283c65ebfc7SToomas Soome         rr->state = regState_Pending;
1284c65ebfc7SToomas Soome     }
1285*472cd20dSToomas Soome     rr->ProbingConflictCount = 0;
1286*472cd20dSToomas Soome     rr->LastConflictPktNum   = 0;
1287c65ebfc7SToomas Soome     rr->ProbeRestartCount    = 0;
1288*472cd20dSToomas Soome     rr->ProbeCount           = 0;
1289c65ebfc7SToomas Soome     rr->AnnounceCount        = 0;
1290c65ebfc7SToomas Soome     rr->ThisAPInterval       = INIT_RECORD_REG_INTERVAL;
1291c65ebfc7SToomas Soome     rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
1292c65ebfc7SToomas Soome     rr->expire               = 0; // Forget about all the leases, start fresh
1293c65ebfc7SToomas Soome     rr->uselease             = mDNStrue;
1294c65ebfc7SToomas Soome     rr->updateid             = zeroID;
1295c65ebfc7SToomas Soome     rr->SRVChanged           = mDNSfalse;
1296c65ebfc7SToomas Soome     rr->updateError          = mStatus_NoError;
1297c65ebfc7SToomas Soome     // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1298c65ebfc7SToomas Soome     // The records might already be registered with the server and hence could have NAT state.
1299c65ebfc7SToomas Soome     if (rr->NATinfo.clientContext)
1300c65ebfc7SToomas Soome     {
1301c65ebfc7SToomas Soome         mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1302c65ebfc7SToomas Soome         rr->NATinfo.clientContext = mDNSNULL;
1303c65ebfc7SToomas Soome     }
1304c65ebfc7SToomas Soome     if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1305c65ebfc7SToomas Soome     if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
1306c65ebfc7SToomas Soome     if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1307c65ebfc7SToomas Soome         m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1308c65ebfc7SToomas Soome }
1309c65ebfc7SToomas Soome 
1310c65ebfc7SToomas Soome // Two records qualify to be local duplicates if:
1311c65ebfc7SToomas Soome // (a) the RecordTypes are the same, or
1312c65ebfc7SToomas Soome // (b) one is Unique and the other Verified
1313c65ebfc7SToomas Soome // (c) either is in the process of deregistering
1314c65ebfc7SToomas Soome #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1315c65ebfc7SToomas Soome                         ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1316c65ebfc7SToomas Soome                         ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1317c65ebfc7SToomas Soome 
1318c65ebfc7SToomas Soome #define RecordIsLocalDuplicate(A,B) \
1319c65ebfc7SToomas Soome     ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1320c65ebfc7SToomas Soome 
CheckAuthIdenticalRecord(AuthHash * r,AuthRecord * rr)1321c65ebfc7SToomas Soome mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1322c65ebfc7SToomas Soome {
1323c65ebfc7SToomas Soome     const AuthGroup *a;
1324c65ebfc7SToomas Soome     AuthRecord *rp;
1325c65ebfc7SToomas Soome 
1326c65ebfc7SToomas Soome     a = AuthGroupForRecord(r, &rr->resrec);
1327c65ebfc7SToomas Soome     if (!a) return mDNSNULL;
1328c65ebfc7SToomas Soome     rp = a->members;
1329c65ebfc7SToomas Soome     while (rp)
1330c65ebfc7SToomas Soome     {
1331c65ebfc7SToomas Soome         if (!RecordIsLocalDuplicate(rp, rr))
1332c65ebfc7SToomas Soome             rp = rp->next;
1333c65ebfc7SToomas Soome         else
1334c65ebfc7SToomas Soome         {
1335c65ebfc7SToomas Soome             if (rp->resrec.RecordType == kDNSRecordTypeDeregistering)
1336c65ebfc7SToomas Soome             {
1337c65ebfc7SToomas Soome                 rp->AnnounceCount = 0;
1338c65ebfc7SToomas Soome                 rp = rp->next;
1339c65ebfc7SToomas Soome             }
1340c65ebfc7SToomas Soome             else return rp;
1341c65ebfc7SToomas Soome         }
1342c65ebfc7SToomas Soome     }
1343c65ebfc7SToomas Soome     return (mDNSNULL);
1344c65ebfc7SToomas Soome }
1345c65ebfc7SToomas Soome 
CheckAuthRecordConflict(AuthHash * r,AuthRecord * rr)1346c65ebfc7SToomas Soome mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1347c65ebfc7SToomas Soome {
1348c65ebfc7SToomas Soome     const AuthGroup *a;
1349c65ebfc7SToomas Soome     const AuthRecord *rp;
1350c65ebfc7SToomas Soome 
1351c65ebfc7SToomas Soome     a = AuthGroupForRecord(r, &rr->resrec);
1352c65ebfc7SToomas Soome     if (!a) return mDNSfalse;
1353c65ebfc7SToomas Soome     rp = a->members;
1354c65ebfc7SToomas Soome     while (rp)
1355c65ebfc7SToomas Soome     {
1356c65ebfc7SToomas Soome         const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1357c65ebfc7SToomas Soome         const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp;
1358c65ebfc7SToomas Soome         if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec))
1359c65ebfc7SToomas Soome             return mDNStrue;
1360c65ebfc7SToomas Soome         else
1361c65ebfc7SToomas Soome             rp = rp->next;
1362c65ebfc7SToomas Soome     }
1363c65ebfc7SToomas Soome     return (mDNSfalse);
1364c65ebfc7SToomas Soome }
1365c65ebfc7SToomas Soome 
1366c65ebfc7SToomas Soome // checks to see if "rr" is already present
CheckAuthSameRecord(AuthHash * r,AuthRecord * rr)1367c65ebfc7SToomas Soome mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1368c65ebfc7SToomas Soome {
1369c65ebfc7SToomas Soome     const AuthGroup *a;
1370c65ebfc7SToomas Soome     AuthRecord *rp;
1371c65ebfc7SToomas Soome 
1372c65ebfc7SToomas Soome     a = AuthGroupForRecord(r, &rr->resrec);
1373c65ebfc7SToomas Soome     if (!a) return mDNSNULL;
1374c65ebfc7SToomas Soome     rp = a->members;
1375c65ebfc7SToomas Soome     while (rp)
1376c65ebfc7SToomas Soome     {
1377c65ebfc7SToomas Soome         if (rp != rr)
1378c65ebfc7SToomas Soome             rp = rp->next;
1379c65ebfc7SToomas Soome         else
1380c65ebfc7SToomas Soome         {
1381c65ebfc7SToomas Soome             return rp;
1382c65ebfc7SToomas Soome         }
1383c65ebfc7SToomas Soome     }
1384c65ebfc7SToomas Soome     return (mDNSNULL);
1385c65ebfc7SToomas Soome }
1386c65ebfc7SToomas Soome 
DecrementAutoTargetServices(mDNS * const m,AuthRecord * const rr)1387c65ebfc7SToomas Soome mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1388c65ebfc7SToomas Soome {
1389c65ebfc7SToomas Soome     if (RRLocalOnly(rr))
1390c65ebfc7SToomas Soome     {
1391c65ebfc7SToomas Soome         // A sanity check, this should be prevented in calling code.
1392c65ebfc7SToomas Soome         LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1393c65ebfc7SToomas Soome         return;
1394c65ebfc7SToomas Soome     }
1395c65ebfc7SToomas Soome 
1396*472cd20dSToomas Soome     if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1397c65ebfc7SToomas Soome     {
1398*472cd20dSToomas Soome         NetworkInterfaceInfo *intf;
1399*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1400*472cd20dSToomas Soome         DeadvertiseFlags flags     = 0; // DeadvertiseFlags for non-AWDL interfaces.
1401*472cd20dSToomas Soome         DeadvertiseFlags flagsAWDL = 0; // DeadvertiseFlags for AWDL interfaces.
1402*472cd20dSToomas Soome         if (AuthRecordIncludesOrIsAWDL(rr))
1403*472cd20dSToomas Soome         {
1404*472cd20dSToomas Soome             if (AuthRecordIncludesAWDL(rr))
1405*472cd20dSToomas Soome             {
1406*472cd20dSToomas Soome                 m->AutoTargetAWDLIncludedCount--;
1407*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1408*472cd20dSToomas Soome                     "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1409*472cd20dSToomas Soome                     m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1410*472cd20dSToomas Soome                 if (m->AutoTargetAWDLIncludedCount == 0)
1411*472cd20dSToomas Soome                 {
1412*472cd20dSToomas Soome                     flags |= kDeadvertiseFlag_RandHostname;
1413*472cd20dSToomas Soome                     if (m->AutoTargetAWDLOnlyCount == 0) flagsAWDL |= kDeadvertiseFlag_RandHostname;
1414*472cd20dSToomas Soome                 }
1415*472cd20dSToomas Soome             }
1416*472cd20dSToomas Soome             else
1417*472cd20dSToomas Soome             {
1418*472cd20dSToomas Soome                 m->AutoTargetAWDLOnlyCount--;
1419*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1420*472cd20dSToomas Soome                     "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1421*472cd20dSToomas Soome                     m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1422*472cd20dSToomas Soome                 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1423*472cd20dSToomas Soome                 {
1424*472cd20dSToomas Soome                     flagsAWDL |= kDeadvertiseFlag_RandHostname;
1425*472cd20dSToomas Soome                 }
1426*472cd20dSToomas Soome             }
1427*472cd20dSToomas Soome             if (flags || flagsAWDL)
1428*472cd20dSToomas Soome             {
1429*472cd20dSToomas Soome                 for (intf = m->HostInterfaces; intf; intf = intf->next)
1430*472cd20dSToomas Soome                 {
1431*472cd20dSToomas Soome                     if (!intf->Advertise) continue;
1432*472cd20dSToomas Soome                     if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID))
1433*472cd20dSToomas Soome                     {
1434*472cd20dSToomas Soome                         if (flagsAWDL) DeadvertiseInterface(m, intf, flagsAWDL);
1435*472cd20dSToomas Soome                     }
1436*472cd20dSToomas Soome                     else
1437*472cd20dSToomas Soome                     {
1438*472cd20dSToomas Soome                         if (flags) DeadvertiseInterface(m, intf, flags);
1439*472cd20dSToomas Soome                     }
1440*472cd20dSToomas Soome                 }
1441*472cd20dSToomas Soome             }
1442*472cd20dSToomas Soome             if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1443*472cd20dSToomas Soome             {
1444*472cd20dSToomas Soome                 GetRandomUUIDLocalHostname(&m->RandomizedHostname);
1445*472cd20dSToomas Soome             }
1446*472cd20dSToomas Soome         }
1447*472cd20dSToomas Soome         else
1448*472cd20dSToomas Soome #endif
1449*472cd20dSToomas Soome         {
1450c65ebfc7SToomas Soome             m->AutoTargetServices--;
1451*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1452*472cd20dSToomas Soome                 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1453*472cd20dSToomas Soome                 m->AutoTargetServices, ARDisplayString(m, rr));
1454*472cd20dSToomas Soome             if (m->AutoTargetServices == 0)
1455*472cd20dSToomas Soome             {
1456*472cd20dSToomas Soome                 for (intf = m->HostInterfaces; intf; intf = intf->next)
1457*472cd20dSToomas Soome                 {
1458*472cd20dSToomas Soome                     if (intf->Advertise) DeadvertiseInterface(m, intf, kDeadvertiseFlag_NormalHostname);
1459*472cd20dSToomas Soome                 }
1460*472cd20dSToomas Soome             }
1461*472cd20dSToomas Soome         }
1462c65ebfc7SToomas Soome     }
1463c65ebfc7SToomas Soome 
1464*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1465c65ebfc7SToomas Soome     if (!AuthRecord_uDNS(rr))
1466c65ebfc7SToomas Soome     {
1467c65ebfc7SToomas Soome         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1468c65ebfc7SToomas Soome             m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
1469c65ebfc7SToomas Soome         m->NumAllInterfaceRecords--;
1470*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1471*472cd20dSToomas Soome             "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1472c65ebfc7SToomas Soome             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1473c65ebfc7SToomas Soome     }
1474*472cd20dSToomas Soome #endif
1475*472cd20dSToomas Soome }
1476*472cd20dSToomas Soome 
AdvertiseNecessaryInterfaceRecords(mDNS * const m)1477*472cd20dSToomas Soome mDNSlocal void AdvertiseNecessaryInterfaceRecords(mDNS *const m)
1478*472cd20dSToomas Soome {
1479*472cd20dSToomas Soome     NetworkInterfaceInfo *intf;
1480*472cd20dSToomas Soome     for (intf = m->HostInterfaces; intf; intf = intf->next)
1481*472cd20dSToomas Soome     {
1482*472cd20dSToomas Soome         if (intf->Advertise) AdvertiseInterfaceIfNeeded(m, intf);
1483*472cd20dSToomas Soome     }
1484c65ebfc7SToomas Soome }
1485c65ebfc7SToomas Soome 
IncrementAutoTargetServices(mDNS * const m,AuthRecord * const rr)1486c65ebfc7SToomas Soome mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1487c65ebfc7SToomas Soome {
1488*472cd20dSToomas Soome     mDNSBool enablingBonjour = mDNSfalse;
1489c65ebfc7SToomas Soome 
1490c65ebfc7SToomas Soome     if (RRLocalOnly(rr))
1491c65ebfc7SToomas Soome     {
1492c65ebfc7SToomas Soome         // A sanity check, this should be prevented in calling code.
1493c65ebfc7SToomas Soome         LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1494c65ebfc7SToomas Soome         return;
1495c65ebfc7SToomas Soome     }
1496c65ebfc7SToomas Soome 
1497*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1498c65ebfc7SToomas Soome     if (!AuthRecord_uDNS(rr))
1499c65ebfc7SToomas Soome     {
1500c65ebfc7SToomas Soome         m->NumAllInterfaceRecords++;
1501*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1502*472cd20dSToomas Soome             "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1503c65ebfc7SToomas Soome             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1504c65ebfc7SToomas Soome         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1505c65ebfc7SToomas Soome         {
1506c65ebfc7SToomas Soome             m->NextBonjourDisableTime = 0;
1507c65ebfc7SToomas Soome             if (m->BonjourEnabled == 0)
1508c65ebfc7SToomas Soome             {
1509c65ebfc7SToomas Soome                 // Enable Bonjour immediately by scheduling network changed processing where
1510c65ebfc7SToomas Soome                 // we will join the multicast group on each active interface.
1511c65ebfc7SToomas Soome                 m->BonjourEnabled = 1;
1512*472cd20dSToomas Soome                 enablingBonjour = mDNStrue;
1513c65ebfc7SToomas Soome                 m->NetworkChanged = m->timenow;
1514c65ebfc7SToomas Soome             }
1515c65ebfc7SToomas Soome         }
1516c65ebfc7SToomas Soome     }
1517*472cd20dSToomas Soome #endif
1518c65ebfc7SToomas Soome 
1519*472cd20dSToomas Soome     if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1520*472cd20dSToomas Soome     {
1521*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1522*472cd20dSToomas Soome         if (AuthRecordIncludesAWDL(rr))
1523*472cd20dSToomas Soome         {
1524*472cd20dSToomas Soome             m->AutoTargetAWDLIncludedCount++;
1525*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1526*472cd20dSToomas Soome                 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1527*472cd20dSToomas Soome                 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1528*472cd20dSToomas Soome         }
1529*472cd20dSToomas Soome         else if (mDNSPlatformInterfaceIsAWDL(rr->resrec.InterfaceID))
1530*472cd20dSToomas Soome         {
1531*472cd20dSToomas Soome             m->AutoTargetAWDLOnlyCount++;
1532*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1533*472cd20dSToomas Soome                 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1534*472cd20dSToomas Soome                 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1535*472cd20dSToomas Soome         }
1536*472cd20dSToomas Soome         else
1537*472cd20dSToomas Soome #endif
1538c65ebfc7SToomas Soome         {
1539c65ebfc7SToomas Soome             m->AutoTargetServices++;
1540*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1541*472cd20dSToomas Soome                 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1542*472cd20dSToomas Soome                 m->AutoTargetServices, ARDisplayString(m, rr));
1543*472cd20dSToomas Soome         }
1544c65ebfc7SToomas Soome         // If this is the first advertised service and we did not just enable Bonjour above, then
1545c65ebfc7SToomas Soome         // advertise all the interface records.  If we did enable Bonjour above, the interface records will
1546c65ebfc7SToomas Soome         // be advertised during the network changed processing scheduled above, so no need
1547c65ebfc7SToomas Soome         // to do it here.
1548*472cd20dSToomas Soome         if (!enablingBonjour) AdvertiseNecessaryInterfaceRecords(m);
1549c65ebfc7SToomas Soome     }
1550c65ebfc7SToomas Soome }
1551c65ebfc7SToomas Soome 
getKeepaliveRaddr(mDNS * const m,AuthRecord * rr,mDNSAddr * raddr)1552c65ebfc7SToomas Soome mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1553c65ebfc7SToomas Soome {
1554c65ebfc7SToomas Soome     mDNSAddr     laddr = zeroAddr;
1555c65ebfc7SToomas Soome     mDNSEthAddr  eth = zeroEthAddr;
1556c65ebfc7SToomas Soome     mDNSIPPort   lport = zeroIPPort;
1557c65ebfc7SToomas Soome     mDNSIPPort   rport = zeroIPPort;
1558c65ebfc7SToomas Soome     mDNSu32      timeout = 0;
1559c65ebfc7SToomas Soome     mDNSu32      seq = 0;
1560c65ebfc7SToomas Soome     mDNSu32      ack = 0;
1561c65ebfc7SToomas Soome     mDNSu16      win = 0;
1562c65ebfc7SToomas Soome 
1563c65ebfc7SToomas Soome     if (mDNS_KeepaliveRecord(&rr->resrec))
1564c65ebfc7SToomas Soome     {
1565c65ebfc7SToomas Soome         mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1566c65ebfc7SToomas Soome         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1567c65ebfc7SToomas Soome         {
1568c65ebfc7SToomas Soome             LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1569c65ebfc7SToomas Soome             return;
1570c65ebfc7SToomas Soome         }
1571c65ebfc7SToomas Soome     }
1572c65ebfc7SToomas Soome }
1573c65ebfc7SToomas Soome 
1574c65ebfc7SToomas Soome // Exported so uDNS.c can call this
mDNS_Register_internal(mDNS * const m,AuthRecord * const rr)1575c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1576c65ebfc7SToomas Soome {
1577c65ebfc7SToomas Soome     domainname *target = GetRRDomainNameTarget(&rr->resrec);
1578c65ebfc7SToomas Soome     AuthRecord *r;
1579c65ebfc7SToomas Soome     AuthRecord **p = &m->ResourceRecords;
1580c65ebfc7SToomas Soome     AuthRecord **d = &m->DuplicateRecords;
1581c65ebfc7SToomas Soome 
1582c65ebfc7SToomas Soome     if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1583c65ebfc7SToomas Soome     { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1584c65ebfc7SToomas Soome 
1585c65ebfc7SToomas Soome     if (!rr->resrec.RecordType)
1586c65ebfc7SToomas Soome     { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1587c65ebfc7SToomas Soome 
1588c65ebfc7SToomas Soome     if (m->ShutdownTime)
1589c65ebfc7SToomas Soome     { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1590c65ebfc7SToomas Soome 
1591c65ebfc7SToomas Soome     if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1592c65ebfc7SToomas Soome     {
1593c65ebfc7SToomas Soome         mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1594c65ebfc7SToomas Soome         if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1595c65ebfc7SToomas Soome         {
1596c65ebfc7SToomas Soome             rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1597c65ebfc7SToomas Soome             rr->ARType = AuthRecordLocalOnly;
1598c65ebfc7SToomas Soome         }
1599c65ebfc7SToomas Soome         if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1600c65ebfc7SToomas Soome         {
1601c65ebfc7SToomas Soome             NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1602c65ebfc7SToomas Soome             if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1603c65ebfc7SToomas Soome         }
1604c65ebfc7SToomas Soome         if (rr->resrec.InterfaceID != previousID)
1605c65ebfc7SToomas Soome             LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1606c65ebfc7SToomas Soome     }
1607c65ebfc7SToomas Soome 
1608c65ebfc7SToomas Soome     if (RRLocalOnly(rr))
1609c65ebfc7SToomas Soome     {
1610c65ebfc7SToomas Soome         if (CheckAuthSameRecord(&m->rrauth, rr))
1611c65ebfc7SToomas Soome         {
1612c65ebfc7SToomas Soome             LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1613c65ebfc7SToomas Soome                    rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1614c65ebfc7SToomas Soome             return(mStatus_AlreadyRegistered);
1615c65ebfc7SToomas Soome         }
1616c65ebfc7SToomas Soome     }
1617c65ebfc7SToomas Soome     else
1618c65ebfc7SToomas Soome     {
1619c65ebfc7SToomas Soome         while (*p && *p != rr) p=&(*p)->next;
1620c65ebfc7SToomas Soome         if (*p)
1621c65ebfc7SToomas Soome         {
1622c65ebfc7SToomas Soome             LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1623c65ebfc7SToomas Soome                    rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1624c65ebfc7SToomas Soome             return(mStatus_AlreadyRegistered);
1625c65ebfc7SToomas Soome         }
1626c65ebfc7SToomas Soome     }
1627c65ebfc7SToomas Soome 
1628c65ebfc7SToomas Soome     while (*d && *d != rr) d=&(*d)->next;
1629c65ebfc7SToomas Soome     if (*d)
1630c65ebfc7SToomas Soome     {
1631c65ebfc7SToomas Soome         LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1632c65ebfc7SToomas Soome                rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1633c65ebfc7SToomas Soome         return(mStatus_AlreadyRegistered);
1634c65ebfc7SToomas Soome     }
1635c65ebfc7SToomas Soome 
1636c65ebfc7SToomas Soome     if (rr->DependentOn)
1637c65ebfc7SToomas Soome     {
1638c65ebfc7SToomas Soome         if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1639c65ebfc7SToomas Soome             rr->resrec.RecordType =  kDNSRecordTypeVerified;
1640c65ebfc7SToomas Soome         else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique)
1641c65ebfc7SToomas Soome         {
1642c65ebfc7SToomas Soome             LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1643c65ebfc7SToomas Soome                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1644c65ebfc7SToomas Soome             return(mStatus_Invalid);
1645c65ebfc7SToomas Soome         }
1646c65ebfc7SToomas Soome         if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1647c65ebfc7SToomas Soome         {
1648c65ebfc7SToomas Soome             LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1649c65ebfc7SToomas Soome                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1650c65ebfc7SToomas Soome             return(mStatus_Invalid);
1651c65ebfc7SToomas Soome         }
1652c65ebfc7SToomas Soome     }
1653c65ebfc7SToomas Soome 
1654c65ebfc7SToomas Soome     rr->next = mDNSNULL;
1655c65ebfc7SToomas Soome 
1656c65ebfc7SToomas Soome     // Field Group 1: The actual information pertaining to this resource record
1657c65ebfc7SToomas Soome     // Set up by client prior to call
1658c65ebfc7SToomas Soome 
1659c65ebfc7SToomas Soome     // Field Group 2: Persistent metadata for Authoritative Records
1660c65ebfc7SToomas Soome //  rr->Additional1       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1661c65ebfc7SToomas Soome //  rr->Additional2       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1662c65ebfc7SToomas Soome //  rr->DependentOn       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1663c65ebfc7SToomas Soome //  rr->RRSet             = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1664c65ebfc7SToomas Soome //  rr->Callback          = already set      in mDNS_SetupResourceRecord
1665c65ebfc7SToomas Soome //  rr->Context           = already set      in mDNS_SetupResourceRecord
1666c65ebfc7SToomas Soome //  rr->RecordType        = already set      in mDNS_SetupResourceRecord
1667c65ebfc7SToomas Soome //  rr->HostTarget        = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1668c65ebfc7SToomas Soome //  rr->AllowRemoteQuery  = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1669c65ebfc7SToomas Soome     // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1670c65ebfc7SToomas Soome     if (rr->AutoTarget && target) target->c[0] = 0;
1671c65ebfc7SToomas Soome 
1672c65ebfc7SToomas Soome     // Field Group 3: Transient state for Authoritative Records
1673c65ebfc7SToomas Soome     rr->Acknowledged      = mDNSfalse;
1674c65ebfc7SToomas Soome     rr->ProbeCount        = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1675c65ebfc7SToomas Soome     rr->ProbeRestartCount = 0;
1676c65ebfc7SToomas Soome     rr->AnnounceCount     = InitialAnnounceCount;
1677c65ebfc7SToomas Soome     rr->RequireGoodbye    = mDNSfalse;
1678c65ebfc7SToomas Soome     rr->AnsweredLocalQ    = mDNSfalse;
1679c65ebfc7SToomas Soome     rr->IncludeInProbe    = mDNSfalse;
1680c65ebfc7SToomas Soome     rr->ImmedUnicast      = mDNSfalse;
1681c65ebfc7SToomas Soome     rr->SendNSECNow       = mDNSNULL;
1682c65ebfc7SToomas Soome     rr->ImmedAnswer       = mDNSNULL;
1683c65ebfc7SToomas Soome     rr->ImmedAdditional   = mDNSNULL;
1684c65ebfc7SToomas Soome     rr->SendRNow          = mDNSNULL;
1685c65ebfc7SToomas Soome     rr->v4Requester       = zerov4Addr;
1686c65ebfc7SToomas Soome     rr->v6Requester       = zerov6Addr;
1687c65ebfc7SToomas Soome     rr->NextResponse      = mDNSNULL;
1688c65ebfc7SToomas Soome     rr->NR_AnswerTo       = mDNSNULL;
1689c65ebfc7SToomas Soome     rr->NR_AdditionalTo   = mDNSNULL;
1690c65ebfc7SToomas Soome     if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1691c65ebfc7SToomas Soome //  rr->LastAPTime        = Set for us in InitializeLastAPTime()
1692c65ebfc7SToomas Soome //  rr->LastMCTime        = Set for us in InitializeLastAPTime()
1693c65ebfc7SToomas Soome //  rr->LastMCInterface   = Set for us in InitializeLastAPTime()
1694c65ebfc7SToomas Soome     rr->NewRData          = mDNSNULL;
1695c65ebfc7SToomas Soome     rr->newrdlength       = 0;
1696c65ebfc7SToomas Soome     rr->UpdateCallback    = mDNSNULL;
1697c65ebfc7SToomas Soome     rr->UpdateCredits     = kMaxUpdateCredits;
1698c65ebfc7SToomas Soome     rr->NextUpdateCredit  = 0;
1699c65ebfc7SToomas Soome     rr->UpdateBlocked     = 0;
1700c65ebfc7SToomas Soome 
1701c65ebfc7SToomas Soome     // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1702c65ebfc7SToomas Soome     if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1703c65ebfc7SToomas Soome 
1704c65ebfc7SToomas Soome     // Field Group 4: Transient uDNS state for Authoritative Records
1705c65ebfc7SToomas Soome     rr->state             = regState_Zero;
1706c65ebfc7SToomas Soome     rr->uselease          = 0;
1707c65ebfc7SToomas Soome     rr->expire            = 0;
1708c65ebfc7SToomas Soome     rr->Private           = 0;
1709c65ebfc7SToomas Soome     rr->updateid          = zeroID;
1710c65ebfc7SToomas Soome     rr->updateIntID       = zeroOpaque64;
1711c65ebfc7SToomas Soome     rr->zone              = rr->resrec.name;
1712c65ebfc7SToomas Soome     rr->nta               = mDNSNULL;
1713c65ebfc7SToomas Soome     rr->tcp               = mDNSNULL;
1714c65ebfc7SToomas Soome     rr->OrigRData         = 0;
1715c65ebfc7SToomas Soome     rr->OrigRDLen         = 0;
1716c65ebfc7SToomas Soome     rr->InFlightRData     = 0;
1717c65ebfc7SToomas Soome     rr->InFlightRDLen     = 0;
1718c65ebfc7SToomas Soome     rr->QueuedRData       = 0;
1719c65ebfc7SToomas Soome     rr->QueuedRDLen       = 0;
1720c65ebfc7SToomas Soome     //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1721c65ebfc7SToomas Soome     // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1722c65ebfc7SToomas Soome     // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1723c65ebfc7SToomas Soome     // times with different values if the external NAT port changes during the lifetime of the service registration.
1724c65ebfc7SToomas Soome     //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1725c65ebfc7SToomas Soome 
1726c65ebfc7SToomas Soome //  rr->resrec.interface         = already set in mDNS_SetupResourceRecord
1727c65ebfc7SToomas Soome //  rr->resrec.name->c           = MUST be set by client
1728c65ebfc7SToomas Soome //  rr->resrec.rrtype            = already set in mDNS_SetupResourceRecord
1729c65ebfc7SToomas Soome //  rr->resrec.rrclass           = already set in mDNS_SetupResourceRecord
1730c65ebfc7SToomas Soome //  rr->resrec.rroriginalttl     = already set in mDNS_SetupResourceRecord
1731c65ebfc7SToomas Soome //  rr->resrec.rdata             = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1732c65ebfc7SToomas Soome 
1733c65ebfc7SToomas Soome     // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1734c65ebfc7SToomas Soome     // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1735c65ebfc7SToomas Soome     // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1736c65ebfc7SToomas Soome     if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1737c65ebfc7SToomas Soome 
1738c65ebfc7SToomas Soome     if (rr->AutoTarget)
1739c65ebfc7SToomas Soome     {
1740c65ebfc7SToomas Soome         SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1741c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
1742c65ebfc7SToomas Soome         // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1743c65ebfc7SToomas Soome         // 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.
1744c65ebfc7SToomas Soome         if (rr->state == regState_NoTarget)
1745c65ebfc7SToomas Soome         {
1746c65ebfc7SToomas Soome             // Initialize the target so that we don't crash while logging etc.
1747c65ebfc7SToomas Soome             domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1748c65ebfc7SToomas Soome             if (tar) tar->c[0] = 0;
1749c65ebfc7SToomas Soome             LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1750c65ebfc7SToomas Soome         }
1751c65ebfc7SToomas Soome #endif
1752c65ebfc7SToomas Soome     }
1753c65ebfc7SToomas Soome     else
1754c65ebfc7SToomas Soome     {
1755c65ebfc7SToomas Soome         rr->resrec.rdlength   = GetRDLength(&rr->resrec, mDNSfalse);
1756c65ebfc7SToomas Soome         rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1757c65ebfc7SToomas Soome     }
1758c65ebfc7SToomas Soome 
1759c65ebfc7SToomas Soome     if (!ValidateDomainName(rr->resrec.name))
1760c65ebfc7SToomas Soome     { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1761c65ebfc7SToomas Soome 
1762c65ebfc7SToomas Soome     // Don't do this until *after* we've set rr->resrec.rdlength
1763c65ebfc7SToomas Soome     if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1764c65ebfc7SToomas Soome     { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1765c65ebfc7SToomas Soome 
1766c65ebfc7SToomas Soome     rr->resrec.namehash   = DomainNameHashValue(rr->resrec.name);
1767c65ebfc7SToomas Soome     rr->resrec.rdatahash  = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1768c65ebfc7SToomas Soome 
1769c65ebfc7SToomas Soome     if (RRLocalOnly(rr))
1770c65ebfc7SToomas Soome     {
1771c65ebfc7SToomas Soome         // If this is supposed to be unique, make sure we don't have any name conflicts.
1772c65ebfc7SToomas Soome         // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1773c65ebfc7SToomas Soome         // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1774c65ebfc7SToomas Soome         // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1775c65ebfc7SToomas Soome         // Hence, just bail out.
1776c65ebfc7SToomas Soome         // This comment is doesn’t make any sense. -- SC
1777c65ebfc7SToomas Soome         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1778c65ebfc7SToomas Soome         {
1779c65ebfc7SToomas Soome             if (CheckAuthRecordConflict(&m->rrauth, rr))
1780c65ebfc7SToomas Soome             {
1781c65ebfc7SToomas Soome                 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1782c65ebfc7SToomas Soome                 return mStatus_NameConflict;
1783c65ebfc7SToomas Soome             }
1784c65ebfc7SToomas Soome         }
1785c65ebfc7SToomas Soome     }
1786c65ebfc7SToomas Soome 
1787c65ebfc7SToomas Soome     // For uDNS records, we don't support duplicate checks at this time.
1788c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
1789c65ebfc7SToomas Soome     if (AuthRecord_uDNS(rr))
1790c65ebfc7SToomas Soome     {
1791c65ebfc7SToomas Soome         if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1792c65ebfc7SToomas Soome         // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1793c65ebfc7SToomas Soome         // 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.
1794c65ebfc7SToomas Soome         while (*p) p=&(*p)->next;
1795c65ebfc7SToomas Soome         *p = rr;
1796c65ebfc7SToomas Soome         if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1797c65ebfc7SToomas Soome         rr->ProbeCount    = 0;
1798c65ebfc7SToomas Soome         rr->ProbeRestartCount = 0;
1799c65ebfc7SToomas Soome         rr->AnnounceCount = 0;
1800c65ebfc7SToomas Soome         if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1801c65ebfc7SToomas Soome         return(mStatus_NoError);            // <--- Note: For unicast records, code currently bails out at this point
1802c65ebfc7SToomas Soome     }
1803c65ebfc7SToomas Soome #endif
1804c65ebfc7SToomas Soome 
1805c65ebfc7SToomas Soome     // Now that we've finished building our new record, make sure it's not identical to one we already have
1806c65ebfc7SToomas Soome     if (RRLocalOnly(rr))
1807c65ebfc7SToomas Soome     {
1808c65ebfc7SToomas Soome         rr->ProbeCount    = 0;
1809c65ebfc7SToomas Soome         rr->ProbeRestartCount = 0;
1810c65ebfc7SToomas Soome         rr->AnnounceCount = 0;
1811c65ebfc7SToomas Soome         r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1812c65ebfc7SToomas Soome     }
1813c65ebfc7SToomas Soome     else
1814c65ebfc7SToomas Soome     {
1815c65ebfc7SToomas Soome         for (r = m->ResourceRecords; r; r=r->next)
1816c65ebfc7SToomas Soome             if (RecordIsLocalDuplicate(r, rr))
1817c65ebfc7SToomas Soome             {
1818c65ebfc7SToomas Soome                 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1819c65ebfc7SToomas Soome                 else break;
1820c65ebfc7SToomas Soome             }
1821c65ebfc7SToomas Soome     }
1822c65ebfc7SToomas Soome 
1823c65ebfc7SToomas Soome     if (r)
1824c65ebfc7SToomas Soome     {
1825c65ebfc7SToomas Soome         LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr));
1826c65ebfc7SToomas Soome         *d = rr;
1827c65ebfc7SToomas Soome         // If the previous copy of this record is already verified unique,
1828c65ebfc7SToomas Soome         // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1829c65ebfc7SToomas Soome         // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1830c65ebfc7SToomas Soome         // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1831c65ebfc7SToomas Soome         if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1832c65ebfc7SToomas Soome             rr->ProbeCount = 0;
1833c65ebfc7SToomas Soome     }
1834c65ebfc7SToomas Soome     else
1835c65ebfc7SToomas Soome     {
1836c65ebfc7SToomas Soome         LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1837c65ebfc7SToomas Soome         if (RRLocalOnly(rr))
1838c65ebfc7SToomas Soome         {
1839c65ebfc7SToomas Soome             AuthGroup *ag;
1840c65ebfc7SToomas Soome             ag = InsertAuthRecord(m, &m->rrauth, rr);
1841c65ebfc7SToomas Soome             if (ag && !ag->NewLocalOnlyRecords)
1842c65ebfc7SToomas Soome             {
1843c65ebfc7SToomas Soome                 m->NewLocalOnlyRecords = mDNStrue;
1844c65ebfc7SToomas Soome                 ag->NewLocalOnlyRecords = rr;
1845c65ebfc7SToomas Soome             }
1846c65ebfc7SToomas Soome             // No probing for LocalOnly records; acknowledge them right away
1847c65ebfc7SToomas Soome             if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1848c65ebfc7SToomas Soome             AcknowledgeRecord(m, rr);
1849c65ebfc7SToomas Soome             return(mStatus_NoError);
1850c65ebfc7SToomas Soome         }
1851c65ebfc7SToomas Soome         else
1852c65ebfc7SToomas Soome         {
1853c65ebfc7SToomas Soome             if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1854c65ebfc7SToomas Soome             *p = rr;
1855c65ebfc7SToomas Soome         }
1856c65ebfc7SToomas Soome     }
1857c65ebfc7SToomas Soome 
1858c65ebfc7SToomas Soome     if (!AuthRecord_uDNS(rr))   // This check is superfluous, given that for unicast records we (currently) bail out above
1859c65ebfc7SToomas Soome     {
1860c65ebfc7SToomas Soome         // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1861c65ebfc7SToomas Soome         IncrementAutoTargetServices(m, rr);
1862c65ebfc7SToomas Soome 
1863c65ebfc7SToomas Soome         // For records that are not going to probe, acknowledge them right away
1864c65ebfc7SToomas Soome         if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1865c65ebfc7SToomas Soome             AcknowledgeRecord(m, rr);
1866c65ebfc7SToomas Soome 
1867c65ebfc7SToomas Soome         // Adding a record may affect whether or not we should sleep
1868c65ebfc7SToomas Soome         mDNS_UpdateAllowSleep(m);
1869c65ebfc7SToomas Soome     }
1870c65ebfc7SToomas Soome 
1871c65ebfc7SToomas Soome     // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1872c65ebfc7SToomas Soome     // This is used by the in-NIC proxy to send the keepalive packets.
1873c65ebfc7SToomas Soome     if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1874c65ebfc7SToomas Soome     {
1875c65ebfc7SToomas Soome         mDNSAddr raddr;
1876c65ebfc7SToomas Soome         // Set the record type to known unique to prevent probing keep alive records.
1877c65ebfc7SToomas Soome         // Also make sure we do not announce the keepalive records.
1878c65ebfc7SToomas Soome        rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1879c65ebfc7SToomas Soome        rr->AnnounceCount     = 0;
1880c65ebfc7SToomas Soome        getKeepaliveRaddr(m, rr, &raddr);
1881c65ebfc7SToomas Soome        // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1882c65ebfc7SToomas Soome        // asynchronous task to update the resource record
1883c65ebfc7SToomas Soome        mDNSPlatformGetRemoteMacAddr(&raddr);
1884c65ebfc7SToomas Soome     }
1885c65ebfc7SToomas Soome 
1886c65ebfc7SToomas Soome     return(mStatus_NoError);
1887c65ebfc7SToomas Soome }
1888c65ebfc7SToomas Soome 
RecordProbeFailure(mDNS * const m,const AuthRecord * const rr)1889c65ebfc7SToomas Soome mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1890c65ebfc7SToomas Soome {
1891c65ebfc7SToomas Soome     m->ProbeFailTime = m->timenow;
1892c65ebfc7SToomas Soome     m->NumFailedProbes++;
1893c65ebfc7SToomas Soome     // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1894c65ebfc7SToomas Soome     // If a bunch of hosts have all been configured with the same name, then they'll all
1895c65ebfc7SToomas Soome     // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1896c65ebfc7SToomas Soome     // up to name-10. After that they'll start adding random increments in the range 1-100,
1897c65ebfc7SToomas Soome     // so they're more likely to branch out in the available namespace and settle on a set of
1898c65ebfc7SToomas Soome     // unique names quickly. If after five more tries the host is still conflicting, then we
1899c65ebfc7SToomas Soome     // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1900c65ebfc7SToomas Soome     if (m->NumFailedProbes >= 15)
1901c65ebfc7SToomas Soome     {
1902c65ebfc7SToomas Soome         m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1903c65ebfc7SToomas Soome         LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1904c65ebfc7SToomas Soome                m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1905c65ebfc7SToomas Soome     }
1906c65ebfc7SToomas Soome }
1907c65ebfc7SToomas Soome 
CompleteRDataUpdate(mDNS * const m,AuthRecord * const rr)1908c65ebfc7SToomas Soome mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1909c65ebfc7SToomas Soome {
1910c65ebfc7SToomas Soome     RData *OldRData = rr->resrec.rdata;
1911c65ebfc7SToomas Soome     mDNSu16 OldRDLen = rr->resrec.rdlength;
1912c65ebfc7SToomas Soome     SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);    // Update our rdata
1913c65ebfc7SToomas Soome     rr->NewRData = mDNSNULL;                                    // Clear the NewRData pointer ...
1914c65ebfc7SToomas Soome     if (rr->UpdateCallback)
1915c65ebfc7SToomas Soome         rr->UpdateCallback(m, rr, OldRData, OldRDLen);          // ... and let the client know
1916c65ebfc7SToomas Soome }
1917c65ebfc7SToomas Soome 
1918c65ebfc7SToomas Soome // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1919c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1920c65ebfc7SToomas Soome // Exported so uDNS.c can call this
mDNS_Deregister_internal(mDNS * const m,AuthRecord * const rr,mDNS_Dereg_type drt)1921c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1922c65ebfc7SToomas Soome {
1923c65ebfc7SToomas Soome     AuthRecord *r2;
1924c65ebfc7SToomas Soome     mDNSu8 RecordType = rr->resrec.RecordType;
1925c65ebfc7SToomas Soome     AuthRecord **p = &m->ResourceRecords;   // Find this record in our list of active records
1926c65ebfc7SToomas Soome     mDNSBool dupList = mDNSfalse;
1927c65ebfc7SToomas Soome 
1928c65ebfc7SToomas Soome     if (RRLocalOnly(rr))
1929c65ebfc7SToomas Soome     {
1930c65ebfc7SToomas Soome         AuthGroup *a;
1931c65ebfc7SToomas Soome         AuthRecord **rp;
1932c65ebfc7SToomas Soome 
1933c65ebfc7SToomas Soome         a = AuthGroupForRecord(&m->rrauth, &rr->resrec);
1934c65ebfc7SToomas Soome         if (!a) return mDNSfalse;
1935c65ebfc7SToomas Soome         rp = &a->members;
1936c65ebfc7SToomas Soome         while (*rp && *rp != rr) rp=&(*rp)->next;
1937c65ebfc7SToomas Soome         p = rp;
1938c65ebfc7SToomas Soome     }
1939c65ebfc7SToomas Soome     else
1940c65ebfc7SToomas Soome     {
1941c65ebfc7SToomas Soome         while (*p && *p != rr) p=&(*p)->next;
1942c65ebfc7SToomas Soome     }
1943c65ebfc7SToomas Soome 
1944c65ebfc7SToomas Soome     if (*p)
1945c65ebfc7SToomas Soome     {
1946c65ebfc7SToomas Soome         // We found our record on the main list. See if there are any duplicates that need special handling.
1947c65ebfc7SToomas Soome         if (drt == mDNS_Dereg_conflict)     // If this was a conflict, see that all duplicates get the same treatment
1948c65ebfc7SToomas Soome         {
1949c65ebfc7SToomas Soome             // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1950c65ebfc7SToomas Soome             // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1951c65ebfc7SToomas Soome             for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1952c65ebfc7SToomas Soome         }
1953c65ebfc7SToomas Soome         else
1954c65ebfc7SToomas Soome         {
1955c65ebfc7SToomas Soome             // Before we delete the record (and potentially send a goodbye packet)
1956c65ebfc7SToomas Soome             // first see if we have a record on the duplicate list ready to take over from it.
1957c65ebfc7SToomas Soome             AuthRecord **d = &m->DuplicateRecords;
1958c65ebfc7SToomas Soome             while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1959c65ebfc7SToomas Soome             if (*d)
1960c65ebfc7SToomas Soome             {
1961c65ebfc7SToomas Soome                 AuthRecord *dup = *d;
1962c65ebfc7SToomas Soome                 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1963c65ebfc7SToomas Soome                        dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1964c65ebfc7SToomas Soome                 *d        = dup->next;      // Cut replacement record from DuplicateRecords list
1965c65ebfc7SToomas Soome                 if (RRLocalOnly(rr))
1966c65ebfc7SToomas Soome                 {
1967c65ebfc7SToomas Soome                     dup->next = mDNSNULL;
1968c65ebfc7SToomas Soome                     if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1969c65ebfc7SToomas Soome                 }
1970c65ebfc7SToomas Soome                 else
1971c65ebfc7SToomas Soome                 {
1972c65ebfc7SToomas Soome                     dup->next = rr->next;       // And then...
1973c65ebfc7SToomas Soome                     rr->next  = dup;            // ... splice it in right after the record we're about to delete
1974c65ebfc7SToomas Soome                 }
1975c65ebfc7SToomas Soome                 dup->resrec.RecordType        = rr->resrec.RecordType;
1976c65ebfc7SToomas Soome                 dup->ProbeCount      = rr->ProbeCount;
1977c65ebfc7SToomas Soome                 dup->ProbeRestartCount = rr->ProbeRestartCount;
1978c65ebfc7SToomas Soome                 dup->AnnounceCount   = rr->AnnounceCount;
1979c65ebfc7SToomas Soome                 dup->RequireGoodbye  = rr->RequireGoodbye;
1980c65ebfc7SToomas Soome                 dup->AnsweredLocalQ  = rr->AnsweredLocalQ;
1981c65ebfc7SToomas Soome                 dup->ImmedAnswer     = rr->ImmedAnswer;
1982c65ebfc7SToomas Soome                 dup->ImmedUnicast    = rr->ImmedUnicast;
1983c65ebfc7SToomas Soome                 dup->ImmedAdditional = rr->ImmedAdditional;
1984c65ebfc7SToomas Soome                 dup->v4Requester     = rr->v4Requester;
1985c65ebfc7SToomas Soome                 dup->v6Requester     = rr->v6Requester;
1986c65ebfc7SToomas Soome                 dup->ThisAPInterval  = rr->ThisAPInterval;
1987c65ebfc7SToomas Soome                 dup->LastAPTime      = rr->LastAPTime;
1988c65ebfc7SToomas Soome                 dup->LastMCTime      = rr->LastMCTime;
1989c65ebfc7SToomas Soome                 dup->LastMCInterface = rr->LastMCInterface;
1990c65ebfc7SToomas Soome                 dup->Private         = rr->Private;
1991c65ebfc7SToomas Soome                 dup->state           = rr->state;
1992c65ebfc7SToomas Soome                 rr->RequireGoodbye = mDNSfalse;
1993c65ebfc7SToomas Soome                 rr->AnsweredLocalQ = mDNSfalse;
1994c65ebfc7SToomas Soome             }
1995c65ebfc7SToomas Soome         }
1996c65ebfc7SToomas Soome     }
1997c65ebfc7SToomas Soome     else
1998c65ebfc7SToomas Soome     {
1999c65ebfc7SToomas Soome         // We didn't find our record on the main list; try the DuplicateRecords list instead.
2000c65ebfc7SToomas Soome         p = &m->DuplicateRecords;
2001c65ebfc7SToomas Soome         while (*p && *p != rr) p=&(*p)->next;
2002c65ebfc7SToomas Soome         // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2003c65ebfc7SToomas Soome         if (*p)
2004c65ebfc7SToomas Soome         {
2005c65ebfc7SToomas Soome             // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
2006c65ebfc7SToomas Soome             // immediately. When there is a conflict, we deregister all the conflicting duplicate records
2007c65ebfc7SToomas Soome             // also that have been marked above in this function. In that case, we come here and if we don't
2008c65ebfc7SToomas Soome             // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
2009c65ebfc7SToomas Soome             // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
2010c65ebfc7SToomas Soome             // details.
2011c65ebfc7SToomas Soome             rr->WakeUp.HMAC    = zeroEthAddr;
2012c65ebfc7SToomas Soome             rr->RequireGoodbye = mDNSfalse;
2013c65ebfc7SToomas Soome             rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2014c65ebfc7SToomas Soome             dupList = mDNStrue;
2015c65ebfc7SToomas Soome         }
2016c65ebfc7SToomas Soome         if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
2017c65ebfc7SToomas Soome                        rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2018c65ebfc7SToomas Soome     }
2019c65ebfc7SToomas Soome 
2020c65ebfc7SToomas Soome     if (!*p)
2021c65ebfc7SToomas Soome     {
2022c65ebfc7SToomas Soome         // No need to log an error message if we already know this is a potentially repeated deregistration
2023c65ebfc7SToomas Soome         if (drt != mDNS_Dereg_repeat)
2024c65ebfc7SToomas Soome             LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
2025c65ebfc7SToomas Soome         return(mStatus_BadReferenceErr);
2026c65ebfc7SToomas Soome     }
2027c65ebfc7SToomas Soome 
2028c65ebfc7SToomas Soome     // If this is a shared record and we've announced it at least once,
2029c65ebfc7SToomas Soome     // we need to retract that announcement before we delete the record
2030c65ebfc7SToomas Soome 
2031c65ebfc7SToomas Soome     // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2032*472cd20dSToomas Soome     // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2033c65ebfc7SToomas Soome     // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2034c65ebfc7SToomas Soome     // mechanism to cope with the client callback modifying the question list while that's happening.
2035c65ebfc7SToomas Soome     // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2036c65ebfc7SToomas Soome     // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2037c65ebfc7SToomas Soome     // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2038c65ebfc7SToomas Soome     // records, thereby invoking yet more callbacks, without limit.
2039c65ebfc7SToomas Soome     // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2040c65ebfc7SToomas Soome     // actual goodbye packets.
2041c65ebfc7SToomas Soome 
2042c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
2043c65ebfc7SToomas Soome     if (AuthRecord_uDNS(rr))
2044c65ebfc7SToomas Soome     {
2045c65ebfc7SToomas Soome         if (rr->RequireGoodbye)
2046c65ebfc7SToomas Soome         {
2047c65ebfc7SToomas Soome             if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2048c65ebfc7SToomas Soome             rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
2049c65ebfc7SToomas Soome             m->LocalRemoveEvents     = mDNStrue;
2050c65ebfc7SToomas Soome             uDNS_DeregisterRecord(m, rr);
2051c65ebfc7SToomas Soome             // At this point unconditionally we bail out
2052c65ebfc7SToomas Soome             // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2053c65ebfc7SToomas Soome             // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2054c65ebfc7SToomas Soome             // process and will complete asynchronously. Either way we don't need to do anything more here.
2055c65ebfc7SToomas Soome             return(mStatus_NoError);
2056c65ebfc7SToomas Soome         }
2057c65ebfc7SToomas Soome         // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2058c65ebfc7SToomas Soome         // from the server. In that case, if the records have been part of a group update, clear the
2059*472cd20dSToomas Soome         // state here.
2060c65ebfc7SToomas Soome         rr->updateid = zeroID;
2061c65ebfc7SToomas Soome 
2062c65ebfc7SToomas Soome         // We defer cleaning up NAT state only after sending goodbyes. This is important because
2063c65ebfc7SToomas Soome         // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2064c65ebfc7SToomas Soome         // This happens today when we turn on/off interface where we get multiple network transitions
2065c65ebfc7SToomas Soome         // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2066c65ebfc7SToomas Soome         // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2067c65ebfc7SToomas Soome         // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2068c65ebfc7SToomas Soome         // NAT state here takes care of the case where we did not send goodbyes at all.
2069c65ebfc7SToomas Soome         if (rr->NATinfo.clientContext)
2070c65ebfc7SToomas Soome         {
2071c65ebfc7SToomas Soome             mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2072c65ebfc7SToomas Soome             rr->NATinfo.clientContext = mDNSNULL;
2073c65ebfc7SToomas Soome         }
2074c65ebfc7SToomas Soome         if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
2075c65ebfc7SToomas Soome         if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
2076c65ebfc7SToomas Soome     }
2077c65ebfc7SToomas Soome #endif // UNICAST_DISABLED
2078c65ebfc7SToomas Soome 
2079c65ebfc7SToomas Soome     if      (RecordType == kDNSRecordTypeUnregistered)
2080c65ebfc7SToomas Soome         LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
2081c65ebfc7SToomas Soome     else if (RecordType == kDNSRecordTypeDeregistering)
2082c65ebfc7SToomas Soome     {
2083c65ebfc7SToomas Soome         LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
2084c65ebfc7SToomas Soome         return(mStatus_BadReferenceErr);
2085c65ebfc7SToomas Soome     }
2086c65ebfc7SToomas Soome 
2087c65ebfc7SToomas Soome     if (rr->WakeUp.HMAC.l[0] ||
2088*472cd20dSToomas Soome         (((RecordType == kDNSRecordTypeShared) || (rr->ARType == AuthRecordLocalOnly)) &&
2089*472cd20dSToomas Soome         (rr->RequireGoodbye || rr->AnsweredLocalQ)))
2090c65ebfc7SToomas Soome     {
2091c65ebfc7SToomas Soome         verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
2092c65ebfc7SToomas Soome         rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
2093c65ebfc7SToomas Soome         rr->resrec.rroriginalttl = 0;
2094c65ebfc7SToomas Soome         rr->AnnounceCount        = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
2095c65ebfc7SToomas Soome         rr->ThisAPInterval       = mDNSPlatformOneSecond * 2;
2096c65ebfc7SToomas Soome         rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
2097c65ebfc7SToomas Soome         m->LocalRemoveEvents     = mDNStrue;
2098c65ebfc7SToomas Soome         if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
2099c65ebfc7SToomas Soome             m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
2100c65ebfc7SToomas Soome     }
2101c65ebfc7SToomas Soome     else
2102c65ebfc7SToomas Soome     {
2103c65ebfc7SToomas Soome         if (!dupList && RRLocalOnly(rr))
2104c65ebfc7SToomas Soome         {
2105c65ebfc7SToomas Soome             AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
2106c65ebfc7SToomas Soome             if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
2107c65ebfc7SToomas Soome         }
2108c65ebfc7SToomas Soome         else
2109c65ebfc7SToomas Soome         {
2110c65ebfc7SToomas Soome             *p = rr->next;                  // Cut this record from the list
2111c65ebfc7SToomas Soome             if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
2112c65ebfc7SToomas Soome             DecrementAutoTargetServices(m, rr);
2113c65ebfc7SToomas Soome         }
2114c65ebfc7SToomas Soome         // If someone is about to look at this, bump the pointer forward
2115c65ebfc7SToomas Soome         if (m->CurrentRecord   == rr) m->CurrentRecord   = rr->next;
2116c65ebfc7SToomas Soome         rr->next = mDNSNULL;
2117c65ebfc7SToomas Soome 
2118c65ebfc7SToomas Soome         verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
2119c65ebfc7SToomas Soome         rr->resrec.RecordType = kDNSRecordTypeUnregistered;
2120c65ebfc7SToomas Soome 
2121c65ebfc7SToomas Soome         if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
2122c65ebfc7SToomas Soome             debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2123c65ebfc7SToomas Soome                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2124c65ebfc7SToomas Soome 
2125c65ebfc7SToomas Soome         // If we have an update queued up which never executed, give the client a chance to free that memory
2126c65ebfc7SToomas Soome         if (rr->NewRData) CompleteRDataUpdate(m, rr);   // Update our rdata, clear the NewRData pointer, and return memory to the client
2127c65ebfc7SToomas Soome 
2128c65ebfc7SToomas Soome 
2129c65ebfc7SToomas Soome         // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2130c65ebfc7SToomas Soome         // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2131c65ebfc7SToomas Soome         // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2132c65ebfc7SToomas Soome         // so any attempt to touch rr after this is likely to lead to a crash.
2133c65ebfc7SToomas Soome         if (drt != mDNS_Dereg_conflict)
2134c65ebfc7SToomas Soome         {
2135c65ebfc7SToomas Soome             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
2136c65ebfc7SToomas Soome             LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr));
2137c65ebfc7SToomas Soome             if (rr->RecordCallback)
2138c65ebfc7SToomas Soome                 rr->RecordCallback(m, rr, mStatus_MemFree);         // MUST NOT touch rr after this
2139c65ebfc7SToomas Soome             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
2140c65ebfc7SToomas Soome         }
2141c65ebfc7SToomas Soome         else
2142c65ebfc7SToomas Soome         {
2143c65ebfc7SToomas Soome             RecordProbeFailure(m, rr);
2144c65ebfc7SToomas Soome             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
2145c65ebfc7SToomas Soome             if (rr->RecordCallback)
2146c65ebfc7SToomas Soome                 rr->RecordCallback(m, rr, mStatus_NameConflict);    // MUST NOT touch rr after this
2147c65ebfc7SToomas Soome             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
2148c65ebfc7SToomas Soome             // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2149c65ebfc7SToomas Soome             // Note that with all the client callbacks going on, by the time we get here all the
2150c65ebfc7SToomas Soome             // records we marked may have been explicitly deregistered by the client anyway.
2151c65ebfc7SToomas Soome             r2 = m->DuplicateRecords;
2152c65ebfc7SToomas Soome             while (r2)
2153c65ebfc7SToomas Soome             {
2154c65ebfc7SToomas Soome                 if (r2->ProbeCount != 0xFF)
2155c65ebfc7SToomas Soome                 {
2156c65ebfc7SToomas Soome                     r2 = r2->next;
2157c65ebfc7SToomas Soome                 }
2158c65ebfc7SToomas Soome                 else
2159c65ebfc7SToomas Soome                 {
2160*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2161c65ebfc7SToomas Soome                     // See if this record was also registered with any D2D plugins.
2162c65ebfc7SToomas Soome                     D2D_stop_advertising_record(r2);
2163c65ebfc7SToomas Soome #endif
2164c65ebfc7SToomas Soome                     mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
2165c65ebfc7SToomas Soome                     // As this is a duplicate record, it will be unlinked from the list
2166c65ebfc7SToomas Soome                     // immediately
2167c65ebfc7SToomas Soome                     r2 = m->DuplicateRecords;
2168c65ebfc7SToomas Soome                 }
2169c65ebfc7SToomas Soome             }
2170c65ebfc7SToomas Soome         }
2171c65ebfc7SToomas Soome     }
2172c65ebfc7SToomas Soome     mDNS_UpdateAllowSleep(m);
2173c65ebfc7SToomas Soome     return(mStatus_NoError);
2174c65ebfc7SToomas Soome }
2175c65ebfc7SToomas Soome 
2176c65ebfc7SToomas Soome // ***************************************************************************
2177c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
2178c65ebfc7SToomas Soome #pragma mark -
2179c65ebfc7SToomas Soome #pragma mark - Packet Sending Functions
2180c65ebfc7SToomas Soome #endif
2181c65ebfc7SToomas Soome 
AddRecordToResponseList(AuthRecord *** nrpp,AuthRecord * rr,AuthRecord * add)2182c65ebfc7SToomas Soome mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
2183c65ebfc7SToomas Soome {
2184c65ebfc7SToomas Soome     if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
2185c65ebfc7SToomas Soome     {
2186c65ebfc7SToomas Soome         **nrpp = rr;
2187c65ebfc7SToomas Soome         // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2188c65ebfc7SToomas Soome         // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2189c65ebfc7SToomas Soome         // The referenced record will definitely be acceptable (by recursive application of this rule)
2190c65ebfc7SToomas Soome         if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
2191c65ebfc7SToomas Soome         rr->NR_AdditionalTo = add;
2192c65ebfc7SToomas Soome         *nrpp = &rr->NextResponse;
2193c65ebfc7SToomas Soome     }
2194c65ebfc7SToomas Soome     debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2195c65ebfc7SToomas Soome }
2196c65ebfc7SToomas Soome 
AddRRSetAdditionalsToResponseList(mDNS * const m,AuthRecord *** nrpp,AuthRecord * rr,AuthRecord * additional,const mDNSInterfaceID InterfaceID)2197c65ebfc7SToomas Soome mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID)
2198c65ebfc7SToomas Soome {
2199c65ebfc7SToomas Soome     AuthRecord *rr2;
2200c65ebfc7SToomas Soome     if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask)
2201c65ebfc7SToomas Soome     {
2202c65ebfc7SToomas Soome         for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next)
2203c65ebfc7SToomas Soome         {
2204c65ebfc7SToomas Soome             if ((rr2->resrec.namehash == additional->resrec.namehash) &&
2205c65ebfc7SToomas Soome                 (rr2->resrec.rrtype   == additional->resrec.rrtype) &&
2206c65ebfc7SToomas Soome                 (rr2 != additional) &&
2207c65ebfc7SToomas Soome                 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) &&
2208c65ebfc7SToomas Soome                 (rr2->resrec.rrclass  == additional->resrec.rrclass) &&
2209c65ebfc7SToomas Soome                 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&
2210c65ebfc7SToomas Soome                 SameDomainName(rr2->resrec.name, additional->resrec.name))
2211c65ebfc7SToomas Soome             {
2212c65ebfc7SToomas Soome                 AddRecordToResponseList(nrpp, rr2, rr);
2213c65ebfc7SToomas Soome             }
2214c65ebfc7SToomas Soome         }
2215c65ebfc7SToomas Soome     }
2216c65ebfc7SToomas Soome }
2217c65ebfc7SToomas Soome 
AddAdditionalsToResponseList(mDNS * const m,AuthRecord * ResponseRecords,AuthRecord *** nrpp,const mDNSInterfaceID InterfaceID)2218c65ebfc7SToomas Soome mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
2219c65ebfc7SToomas Soome {
2220c65ebfc7SToomas Soome     AuthRecord  *rr, *rr2;
2221c65ebfc7SToomas Soome     for (rr=ResponseRecords; rr; rr=rr->NextResponse)           // For each record we plan to put
2222c65ebfc7SToomas Soome     {
2223c65ebfc7SToomas Soome         // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2224c65ebfc7SToomas Soome         // later in the "for" loop, and we will follow further "additional" links then.)
2225c65ebfc7SToomas Soome         if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
2226c65ebfc7SToomas Soome         {
2227c65ebfc7SToomas Soome             AddRecordToResponseList(nrpp, rr->Additional1, rr);
2228c65ebfc7SToomas Soome             AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID);
2229c65ebfc7SToomas Soome         }
2230c65ebfc7SToomas Soome 
2231c65ebfc7SToomas Soome         if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
2232c65ebfc7SToomas Soome         {
2233c65ebfc7SToomas Soome             AddRecordToResponseList(nrpp, rr->Additional2, rr);
2234c65ebfc7SToomas Soome             AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID);
2235c65ebfc7SToomas Soome         }
2236c65ebfc7SToomas Soome 
2237c65ebfc7SToomas Soome         // For SRV records, automatically add the Address record(s) for the target host
2238c65ebfc7SToomas Soome         if (rr->resrec.rrtype == kDNSType_SRV)
2239c65ebfc7SToomas Soome         {
2240c65ebfc7SToomas Soome             for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                    // Scan list of resource records
2241c65ebfc7SToomas Soome                 if (RRTypeIsAddressType(rr2->resrec.rrtype) &&                  // For all address records (A/AAAA) ...
2242c65ebfc7SToomas Soome                     ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&   // ... which are valid for answer ...
2243c65ebfc7SToomas Soome                     rr->resrec.rdatahash == rr2->resrec.namehash &&         // ... whose name is the name of the SRV target
2244c65ebfc7SToomas Soome                     SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
2245c65ebfc7SToomas Soome                     AddRecordToResponseList(nrpp, rr2, rr);
2246c65ebfc7SToomas Soome         }
2247c65ebfc7SToomas Soome         else if (RRTypeIsAddressType(rr->resrec.rrtype))    // For A or AAAA, put counterpart as additional
2248c65ebfc7SToomas Soome         {
2249c65ebfc7SToomas Soome             for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                    // Scan list of resource records
2250c65ebfc7SToomas Soome                 if (RRTypeIsAddressType(rr2->resrec.rrtype) &&                  // For all address records (A/AAAA) ...
2251c65ebfc7SToomas Soome                     ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&   // ... which are valid for answer ...
2252c65ebfc7SToomas Soome                     rr->resrec.namehash == rr2->resrec.namehash &&              // ... and have the same name
2253c65ebfc7SToomas Soome                     SameDomainName(rr->resrec.name, rr2->resrec.name))
2254c65ebfc7SToomas Soome                     AddRecordToResponseList(nrpp, rr2, rr);
2255c65ebfc7SToomas Soome         }
2256c65ebfc7SToomas Soome         else if (rr->resrec.rrtype == kDNSType_PTR)         // For service PTR, see if we want to add DeviceInfo record
2257c65ebfc7SToomas Soome         {
2258c65ebfc7SToomas Soome             if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
2259c65ebfc7SToomas Soome                 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2260c65ebfc7SToomas Soome                 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
2261c65ebfc7SToomas Soome         }
2262c65ebfc7SToomas Soome     }
2263c65ebfc7SToomas Soome }
2264c65ebfc7SToomas Soome 
SendDelayedUnicastResponse(mDNS * const m,const mDNSAddr * const dest,const mDNSInterfaceID InterfaceID)2265c65ebfc7SToomas Soome mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
2266c65ebfc7SToomas Soome {
2267c65ebfc7SToomas Soome     AuthRecord *rr;
2268c65ebfc7SToomas Soome     AuthRecord  *ResponseRecords = mDNSNULL;
2269c65ebfc7SToomas Soome     AuthRecord **nrp             = &ResponseRecords;
2270c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2271c65ebfc7SToomas Soome 
2272c65ebfc7SToomas Soome     // Make a list of all our records that need to be unicast to this destination
2273c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2274c65ebfc7SToomas Soome     {
2275c65ebfc7SToomas Soome         // If we find we can no longer unicast this answer, clear ImmedUnicast
2276c65ebfc7SToomas Soome         if (rr->ImmedAnswer == mDNSInterfaceMark               ||
2277c65ebfc7SToomas Soome             mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
2278c65ebfc7SToomas Soome             mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr)  )
2279c65ebfc7SToomas Soome             rr->ImmedUnicast = mDNSfalse;
2280c65ebfc7SToomas Soome 
2281c65ebfc7SToomas Soome         if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
2282c65ebfc7SToomas Soome         {
2283c65ebfc7SToomas Soome             if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
2284c65ebfc7SToomas Soome                 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
2285c65ebfc7SToomas Soome             {
2286c65ebfc7SToomas Soome                 rr->ImmedAnswer  = mDNSNULL;                // Clear the state fields
2287c65ebfc7SToomas Soome                 rr->ImmedUnicast = mDNSfalse;
2288c65ebfc7SToomas Soome                 rr->v4Requester  = zerov4Addr;
2289c65ebfc7SToomas Soome                 rr->v6Requester  = zerov6Addr;
2290c65ebfc7SToomas Soome 
2291c65ebfc7SToomas Soome                 // Only sent records registered for P2P over P2P interfaces
2292c65ebfc7SToomas Soome                 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))
2293c65ebfc7SToomas Soome                 {
2294c65ebfc7SToomas Soome                     continue;
2295c65ebfc7SToomas Soome                 }
2296c65ebfc7SToomas Soome 
2297c65ebfc7SToomas Soome                 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse)   // rr->NR_AnswerTo
2298c65ebfc7SToomas Soome                 {
2299c65ebfc7SToomas Soome                     rr->NR_AnswerTo = NR_AnswerMulticast;
2300c65ebfc7SToomas Soome                     *nrp = rr;
2301c65ebfc7SToomas Soome                     nrp = &rr->NextResponse;
2302c65ebfc7SToomas Soome                 }
2303c65ebfc7SToomas Soome             }
2304c65ebfc7SToomas Soome         }
2305c65ebfc7SToomas Soome     }
2306c65ebfc7SToomas Soome 
2307c65ebfc7SToomas Soome     AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
2308c65ebfc7SToomas Soome 
2309c65ebfc7SToomas Soome     while (ResponseRecords)
2310c65ebfc7SToomas Soome     {
2311c65ebfc7SToomas Soome         mDNSu8 *responseptr = m->omsg.data;
2312c65ebfc7SToomas Soome         mDNSu8 *newptr;
2313c65ebfc7SToomas Soome         InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2314c65ebfc7SToomas Soome 
2315c65ebfc7SToomas Soome         // Put answers in the packet
2316c65ebfc7SToomas Soome         while (ResponseRecords && ResponseRecords->NR_AnswerTo)
2317c65ebfc7SToomas Soome         {
2318c65ebfc7SToomas Soome             rr = ResponseRecords;
2319c65ebfc7SToomas Soome             if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2320c65ebfc7SToomas Soome                 rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2321c65ebfc7SToomas Soome 
2322*472cd20dSToomas Soome             newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
2323c65ebfc7SToomas Soome 
2324c65ebfc7SToomas Soome             rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2325c65ebfc7SToomas Soome             if (!newptr && m->omsg.h.numAnswers)
2326c65ebfc7SToomas Soome             {
2327c65ebfc7SToomas Soome                 break; // If packet full, send it now
2328c65ebfc7SToomas Soome             }
2329c65ebfc7SToomas Soome             if (newptr) responseptr = newptr;
2330c65ebfc7SToomas Soome             ResponseRecords = rr->NextResponse;
2331c65ebfc7SToomas Soome             rr->NextResponse    = mDNSNULL;
2332c65ebfc7SToomas Soome             rr->NR_AnswerTo     = mDNSNULL;
2333c65ebfc7SToomas Soome             rr->NR_AdditionalTo = mDNSNULL;
2334c65ebfc7SToomas Soome             rr->RequireGoodbye  = mDNStrue;
2335c65ebfc7SToomas Soome         }
2336c65ebfc7SToomas Soome 
2337c65ebfc7SToomas Soome         // Add additionals, if there's space
2338c65ebfc7SToomas Soome         while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2339c65ebfc7SToomas Soome         {
2340c65ebfc7SToomas Soome             rr = ResponseRecords;
2341c65ebfc7SToomas Soome             if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2342c65ebfc7SToomas Soome                 rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2343c65ebfc7SToomas Soome             newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2344c65ebfc7SToomas Soome             rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2345c65ebfc7SToomas Soome 
2346c65ebfc7SToomas Soome             if (newptr) responseptr = newptr;
2347c65ebfc7SToomas Soome             if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2348c65ebfc7SToomas Soome             else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2349c65ebfc7SToomas Soome             ResponseRecords = rr->NextResponse;
2350c65ebfc7SToomas Soome             rr->NextResponse    = mDNSNULL;
2351c65ebfc7SToomas Soome             rr->NR_AnswerTo     = mDNSNULL;
2352c65ebfc7SToomas Soome             rr->NR_AdditionalTo = mDNSNULL;
2353c65ebfc7SToomas Soome         }
2354c65ebfc7SToomas Soome 
2355c65ebfc7SToomas Soome         if (m->omsg.h.numAnswers)
2356*472cd20dSToomas Soome             mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSfalse);
2357c65ebfc7SToomas Soome     }
2358c65ebfc7SToomas Soome }
2359c65ebfc7SToomas Soome 
2360c65ebfc7SToomas Soome // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2361c65ebfc7SToomas Soome // and the client's mStatus_MemFree callback will have been invoked
CompleteDeregistration(mDNS * const m,AuthRecord * rr)2362c65ebfc7SToomas Soome mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2363c65ebfc7SToomas Soome {
2364c65ebfc7SToomas Soome     LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2365c65ebfc7SToomas Soome     // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2366c65ebfc7SToomas Soome     // it should go ahead and immediately dispose of this registration
2367c65ebfc7SToomas Soome     rr->resrec.RecordType = kDNSRecordTypeShared;
2368c65ebfc7SToomas Soome     rr->RequireGoodbye    = mDNSfalse;
2369c65ebfc7SToomas Soome     rr->WakeUp.HMAC       = zeroEthAddr;
23703b436d06SToomas Soome     if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; }
2371c65ebfc7SToomas Soome     mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);     // Don't touch rr after this
2372c65ebfc7SToomas Soome }
2373c65ebfc7SToomas Soome 
2374c65ebfc7SToomas Soome // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2375c65ebfc7SToomas Soome // any deregistering records that remain in the m->ResourceRecords list.
2376c65ebfc7SToomas Soome // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2377c65ebfc7SToomas Soome // which may change the record list and/or question list.
2378c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
DiscardDeregistrations(mDNS * const m)2379c65ebfc7SToomas Soome mDNSlocal void DiscardDeregistrations(mDNS *const m)
2380c65ebfc7SToomas Soome {
2381c65ebfc7SToomas Soome     if (m->CurrentRecord)
2382c65ebfc7SToomas Soome         LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2383c65ebfc7SToomas Soome     m->CurrentRecord = m->ResourceRecords;
2384c65ebfc7SToomas Soome 
2385c65ebfc7SToomas Soome     while (m->CurrentRecord)
2386c65ebfc7SToomas Soome     {
2387c65ebfc7SToomas Soome         AuthRecord *rr = m->CurrentRecord;
2388c65ebfc7SToomas Soome         if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2389c65ebfc7SToomas Soome             CompleteDeregistration(m, rr);      // Don't touch rr after this
2390c65ebfc7SToomas Soome         else
2391c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
2392c65ebfc7SToomas Soome     }
2393c65ebfc7SToomas Soome }
2394c65ebfc7SToomas Soome 
GetLabelDecimalValue(const mDNSu8 * const src,mDNSu8 * dst)2395c65ebfc7SToomas Soome mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2396c65ebfc7SToomas Soome {
2397c65ebfc7SToomas Soome     int i, val = 0;
2398c65ebfc7SToomas Soome     if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2399c65ebfc7SToomas Soome     for (i=1; i<=src[0]; i++)
2400c65ebfc7SToomas Soome     {
2401c65ebfc7SToomas Soome         if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2402c65ebfc7SToomas Soome         val = val * 10 + src[i] - '0';
2403c65ebfc7SToomas Soome     }
2404c65ebfc7SToomas Soome     if (val > 255) return(mStatus_Invalid);
2405c65ebfc7SToomas Soome     *dst = (mDNSu8)val;
2406c65ebfc7SToomas Soome     return(mStatus_NoError);
2407c65ebfc7SToomas Soome }
2408c65ebfc7SToomas Soome 
GetIPv4FromName(mDNSAddr * const a,const domainname * const name)2409c65ebfc7SToomas Soome mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2410c65ebfc7SToomas Soome {
2411c65ebfc7SToomas Soome     int skip = CountLabels(name) - 6;
2412c65ebfc7SToomas Soome     if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2413c65ebfc7SToomas Soome     if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2414c65ebfc7SToomas Soome         GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2415c65ebfc7SToomas Soome         GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2416c65ebfc7SToomas Soome         GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2417c65ebfc7SToomas Soome     a->type = mDNSAddrType_IPv4;
2418c65ebfc7SToomas Soome     return(mStatus_NoError);
2419c65ebfc7SToomas Soome }
2420c65ebfc7SToomas Soome 
2421c65ebfc7SToomas Soome #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :   \
2422c65ebfc7SToomas Soome                     ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :   \
2423c65ebfc7SToomas Soome                     ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2424c65ebfc7SToomas Soome 
GetIPv6FromName(mDNSAddr * const a,const domainname * const name)2425c65ebfc7SToomas Soome mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2426c65ebfc7SToomas Soome {
2427c65ebfc7SToomas Soome     int i, h, l;
2428c65ebfc7SToomas Soome     const domainname *n;
2429c65ebfc7SToomas Soome 
2430c65ebfc7SToomas Soome     int skip = CountLabels(name) - 34;
2431c65ebfc7SToomas Soome     if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2432c65ebfc7SToomas Soome 
2433c65ebfc7SToomas Soome     n = SkipLeadingLabels(name, skip);
2434c65ebfc7SToomas Soome     for (i=0; i<16; i++)
2435c65ebfc7SToomas Soome     {
2436c65ebfc7SToomas Soome         if (n->c[0] != 1) return mStatus_Invalid;
2437c65ebfc7SToomas Soome         l = HexVal(n->c[1]);
2438c65ebfc7SToomas Soome         n = (const domainname *)(n->c + 2);
2439c65ebfc7SToomas Soome 
2440c65ebfc7SToomas Soome         if (n->c[0] != 1) return mStatus_Invalid;
2441c65ebfc7SToomas Soome         h = HexVal(n->c[1]);
2442c65ebfc7SToomas Soome         n = (const domainname *)(n->c + 2);
2443c65ebfc7SToomas Soome 
2444c65ebfc7SToomas Soome         if (l<0 || h<0) return mStatus_Invalid;
2445c65ebfc7SToomas Soome         a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2446c65ebfc7SToomas Soome     }
2447c65ebfc7SToomas Soome 
2448c65ebfc7SToomas Soome     a->type = mDNSAddrType_IPv6;
2449c65ebfc7SToomas Soome     return(mStatus_NoError);
2450c65ebfc7SToomas Soome }
2451c65ebfc7SToomas Soome 
ReverseMapDomainType(const domainname * const name)2452c65ebfc7SToomas Soome mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2453c65ebfc7SToomas Soome {
2454c65ebfc7SToomas Soome     int skip = CountLabels(name) - 2;
2455c65ebfc7SToomas Soome     if (skip >= 0)
2456c65ebfc7SToomas Soome     {
2457c65ebfc7SToomas Soome         const domainname *suffix = SkipLeadingLabels(name, skip);
2458c65ebfc7SToomas Soome         if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2459c65ebfc7SToomas Soome         if (SameDomainName(suffix, (const domainname*)"\x3" "ip6"     "\x4" "arpa")) return mDNSAddrType_IPv6;
2460c65ebfc7SToomas Soome     }
2461c65ebfc7SToomas Soome     return(mDNSAddrType_None);
2462c65ebfc7SToomas Soome }
2463c65ebfc7SToomas Soome 
SendARP(mDNS * const m,const mDNSu8 op,const AuthRecord * const rr,const mDNSv4Addr * const spa,const mDNSEthAddr * const tha,const mDNSv4Addr * const tpa,const mDNSEthAddr * const dst)2464c65ebfc7SToomas Soome mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2465c65ebfc7SToomas Soome                        const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2466c65ebfc7SToomas Soome {
2467c65ebfc7SToomas Soome     int i;
2468c65ebfc7SToomas Soome     mDNSu8 *ptr = m->omsg.data;
2469c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2470c65ebfc7SToomas Soome     if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2471c65ebfc7SToomas Soome 
2472c65ebfc7SToomas Soome     // 0x00 Destination address
2473c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = dst->b[i];
2474c65ebfc7SToomas Soome 
2475c65ebfc7SToomas Soome     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2476c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2477c65ebfc7SToomas Soome 
2478c65ebfc7SToomas Soome     // 0x0C ARP Ethertype (0x0806)
2479c65ebfc7SToomas Soome     *ptr++ = 0x08; *ptr++ = 0x06;
2480c65ebfc7SToomas Soome 
2481c65ebfc7SToomas Soome     // 0x0E ARP header
2482c65ebfc7SToomas Soome     *ptr++ = 0x00; *ptr++ = 0x01;   // Hardware address space; Ethernet = 1
2483c65ebfc7SToomas Soome     *ptr++ = 0x08; *ptr++ = 0x00;   // Protocol address space; IP = 0x0800
2484c65ebfc7SToomas Soome     *ptr++ = 6;                     // Hardware address length
2485c65ebfc7SToomas Soome     *ptr++ = 4;                     // Protocol address length
2486c65ebfc7SToomas Soome     *ptr++ = 0x00; *ptr++ = op;     // opcode; Request = 1, Response = 2
2487c65ebfc7SToomas Soome 
2488c65ebfc7SToomas Soome     // 0x16 Sender hardware address (our MAC address)
2489c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2490c65ebfc7SToomas Soome 
2491c65ebfc7SToomas Soome     // 0x1C Sender protocol address
2492c65ebfc7SToomas Soome     for (i=0; i<4; i++) *ptr++ = spa->b[i];
2493c65ebfc7SToomas Soome 
2494c65ebfc7SToomas Soome     // 0x20 Target hardware address
2495c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = tha->b[i];
2496c65ebfc7SToomas Soome 
2497c65ebfc7SToomas Soome     // 0x26 Target protocol address
2498c65ebfc7SToomas Soome     for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2499c65ebfc7SToomas Soome 
2500c65ebfc7SToomas Soome     // 0x2A Total ARP Packet length 42 bytes
2501c65ebfc7SToomas Soome     mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2502c65ebfc7SToomas Soome }
2503c65ebfc7SToomas Soome 
CheckSum(const void * const data,mDNSs32 length,mDNSu32 sum)2504c65ebfc7SToomas Soome mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2505c65ebfc7SToomas Soome {
2506c65ebfc7SToomas Soome     const mDNSu16 *ptr = data;
2507c65ebfc7SToomas Soome     while (length > 0) { length -= 2; sum += *ptr++; }
2508c65ebfc7SToomas Soome     sum = (sum & 0xFFFF) + (sum >> 16);
2509c65ebfc7SToomas Soome     sum = (sum & 0xFFFF) + (sum >> 16);
2510c65ebfc7SToomas Soome     return(sum != 0xFFFF ? sum : 0);
2511c65ebfc7SToomas Soome }
2512c65ebfc7SToomas Soome 
IPv6CheckSum(const mDNSv6Addr * const src,const mDNSv6Addr * const dst,const mDNSu8 protocol,const void * const data,const mDNSu32 length)2513c65ebfc7SToomas Soome mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2514c65ebfc7SToomas Soome {
2515c65ebfc7SToomas Soome     IPv6PseudoHeader ph;
2516c65ebfc7SToomas Soome     ph.src = *src;
2517c65ebfc7SToomas Soome     ph.dst = *dst;
2518c65ebfc7SToomas Soome     ph.len.b[0] = length >> 24;
2519c65ebfc7SToomas Soome     ph.len.b[1] = length >> 16;
2520c65ebfc7SToomas Soome     ph.len.b[2] = length >> 8;
2521c65ebfc7SToomas Soome     ph.len.b[3] = length;
2522c65ebfc7SToomas Soome     ph.pro.b[0] = 0;
2523c65ebfc7SToomas Soome     ph.pro.b[1] = 0;
2524c65ebfc7SToomas Soome     ph.pro.b[2] = 0;
2525c65ebfc7SToomas Soome     ph.pro.b[3] = protocol;
2526c65ebfc7SToomas Soome     return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2527c65ebfc7SToomas Soome }
2528c65ebfc7SToomas Soome 
SendNDP(mDNS * const m,const mDNSu8 op,const mDNSu8 flags,const AuthRecord * const rr,const mDNSv6Addr * const spa,const mDNSEthAddr * const tha,const mDNSv6Addr * const tpa,const mDNSEthAddr * const dst)2529c65ebfc7SToomas Soome mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2530c65ebfc7SToomas Soome                        const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2531c65ebfc7SToomas Soome {
2532c65ebfc7SToomas Soome     int i;
2533c65ebfc7SToomas Soome     mDNSOpaque16 checksum;
2534c65ebfc7SToomas Soome     mDNSu8 *ptr = m->omsg.data;
2535c65ebfc7SToomas Soome     // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2536c65ebfc7SToomas Soome     // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2537c65ebfc7SToomas Soome     // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2538c65ebfc7SToomas Soome     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] } };
2539c65ebfc7SToomas Soome     const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2540c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2541c65ebfc7SToomas Soome     if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2542c65ebfc7SToomas Soome 
2543c65ebfc7SToomas Soome     // 0x00 Destination address
2544c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = dst->b[i];
2545c65ebfc7SToomas Soome     // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2546c65ebfc7SToomas Soome     // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2547c65ebfc7SToomas Soome     // link with a pointless link-layer multicast.
2548c65ebfc7SToomas Soome     // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2549c65ebfc7SToomas Soome     // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2550c65ebfc7SToomas Soome     // *ptr++ = 0x33;
2551c65ebfc7SToomas Soome     // *ptr++ = 0x33;
2552c65ebfc7SToomas Soome     // *ptr++ = 0xFF;
2553c65ebfc7SToomas Soome     // *ptr++ = tpa->b[0xD];
2554c65ebfc7SToomas Soome     // *ptr++ = tpa->b[0xE];
2555c65ebfc7SToomas Soome     // *ptr++ = tpa->b[0xF];
2556c65ebfc7SToomas Soome 
2557c65ebfc7SToomas Soome     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
25583b436d06SToomas Soome     for (i=0; i<6; i++)
25593b436d06SToomas Soome 	if (tha)
25603b436d06SToomas Soome 	    *ptr++ = tha->b[i];
25613b436d06SToomas Soome 	else
25623b436d06SToomas Soome 	    *ptr++ = intf->MAC.b[i];
2563c65ebfc7SToomas Soome 
2564c65ebfc7SToomas Soome     // 0x0C IPv6 Ethertype (0x86DD)
2565c65ebfc7SToomas Soome     *ptr++ = 0x86; *ptr++ = 0xDD;
2566c65ebfc7SToomas Soome 
2567c65ebfc7SToomas Soome     // 0x0E IPv6 header
2568c65ebfc7SToomas Soome     *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;     // Version, Traffic Class, Flow Label
2569c65ebfc7SToomas Soome     *ptr++ = 0x00; *ptr++ = 0x20;                                   // Length
2570c65ebfc7SToomas Soome     *ptr++ = 0x3A;                                                  // Protocol == ICMPv6
2571c65ebfc7SToomas Soome     *ptr++ = 0xFF;                                                  // Hop Limit
2572c65ebfc7SToomas Soome 
2573c65ebfc7SToomas Soome     // 0x16 Sender IPv6 address
2574c65ebfc7SToomas Soome     for (i=0; i<16; i++) *ptr++ = spa->b[i];
2575c65ebfc7SToomas Soome 
2576c65ebfc7SToomas Soome     // 0x26 Destination IPv6 address
2577c65ebfc7SToomas Soome     for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2578c65ebfc7SToomas Soome 
2579c65ebfc7SToomas Soome     // 0x36 NDP header
2580c65ebfc7SToomas Soome     *ptr++ = op;                    // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2581c65ebfc7SToomas Soome     *ptr++ = 0x00;                  // Code
2582c65ebfc7SToomas Soome     *ptr++ = 0x00; *ptr++ = 0x00;   // Checksum placeholder (0x38, 0x39)
2583c65ebfc7SToomas Soome     *ptr++ = flags;
2584c65ebfc7SToomas Soome     *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2585c65ebfc7SToomas Soome 
2586c65ebfc7SToomas Soome     if (op == NDP_Sol)  // Neighbor Solicitation. The NDP "target" is the address we seek.
2587c65ebfc7SToomas Soome     {
2588c65ebfc7SToomas Soome         // 0x3E NDP target.
2589c65ebfc7SToomas Soome         for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2590c65ebfc7SToomas Soome         // 0x4E Source Link-layer Address
2591c65ebfc7SToomas Soome         // <http://www.ietf.org/rfc/rfc2461.txt>
2592c65ebfc7SToomas Soome         // MUST NOT be included when the source IP address is the unspecified address.
2593c65ebfc7SToomas Soome         // Otherwise, on link layers that have addresses this option MUST be included
2594c65ebfc7SToomas Soome         // in multicast solicitations and SHOULD be included in unicast solicitations.
2595c65ebfc7SToomas Soome         if (!mDNSIPv6AddressIsZero(*spa))
2596c65ebfc7SToomas Soome         {
2597c65ebfc7SToomas Soome             *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2598c65ebfc7SToomas Soome             *ptr++ = 0x01;      // Option length 1 (in units of 8 octets)
25993b436d06SToomas Soome             for (i=0; i<6; i++)
26003b436d06SToomas Soome 		if (tha)
26013b436d06SToomas Soome 		    *ptr++ = tha->b[i];
26023b436d06SToomas Soome 		else
26033b436d06SToomas Soome 		    *ptr++ = intf->MAC.b[i];
2604c65ebfc7SToomas Soome         }
2605c65ebfc7SToomas Soome     }
2606c65ebfc7SToomas Soome     else            // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2607c65ebfc7SToomas Soome     {
2608c65ebfc7SToomas Soome         // 0x3E NDP target.
2609c65ebfc7SToomas Soome         for (i=0; i<16; i++) *ptr++ = spa->b[i];
2610c65ebfc7SToomas Soome         // 0x4E Target Link-layer Address
2611c65ebfc7SToomas Soome         *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2612c65ebfc7SToomas Soome         *ptr++ = 0x01;      // Option length 1 (in units of 8 octets)
26133b436d06SToomas Soome         for (i=0; i<6; i++)
26143b436d06SToomas Soome 	    if (tha)
26153b436d06SToomas Soome 		*ptr++ = tha->b[i];
26163b436d06SToomas Soome 	    else
26173b436d06SToomas Soome 		*ptr++ = intf->MAC.b[i];
2618c65ebfc7SToomas Soome     }
2619c65ebfc7SToomas Soome 
2620c65ebfc7SToomas Soome     // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2621c65ebfc7SToomas Soome     m->omsg.data[0x13] = ptr - &m->omsg.data[0x36];     // Compute actual length
2622c65ebfc7SToomas Soome     checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2623c65ebfc7SToomas Soome     m->omsg.data[0x38] = checksum.b[0];
2624c65ebfc7SToomas Soome     m->omsg.data[0x39] = checksum.b[1];
2625c65ebfc7SToomas Soome 
2626c65ebfc7SToomas Soome     mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2627c65ebfc7SToomas Soome }
2628c65ebfc7SToomas Soome 
SetupTracerOpt(const mDNS * const m,rdataOPT * const Trace)2629c65ebfc7SToomas Soome mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2630c65ebfc7SToomas Soome {
2631c65ebfc7SToomas Soome     mDNSu32 DNS_VERS = _DNS_SD_H;
2632c65ebfc7SToomas Soome     Trace->u.tracer.platf    = m->mDNS_plat;
2633c65ebfc7SToomas Soome     Trace->u.tracer.mDNSv    = DNS_VERS;
2634c65ebfc7SToomas Soome 
2635c65ebfc7SToomas Soome     Trace->opt              = kDNSOpt_Trace;
2636c65ebfc7SToomas Soome     Trace->optlen           = DNSOpt_TraceData_Space - 4;
2637c65ebfc7SToomas Soome }
2638c65ebfc7SToomas Soome 
SetupOwnerOpt(const mDNS * const m,const NetworkInterfaceInfo * const intf,rdataOPT * const owner)2639c65ebfc7SToomas Soome mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2640c65ebfc7SToomas Soome {
2641c65ebfc7SToomas Soome     owner->u.owner.vers     = 0;
2642c65ebfc7SToomas Soome     owner->u.owner.seq      = m->SleepSeqNum;
2643c65ebfc7SToomas Soome     owner->u.owner.HMAC     = m->PrimaryMAC;
2644c65ebfc7SToomas Soome     owner->u.owner.IMAC     = intf->MAC;
2645c65ebfc7SToomas Soome     owner->u.owner.password = zeroEthAddr;
2646c65ebfc7SToomas Soome 
2647c65ebfc7SToomas Soome     // Don't try to compute the optlen until *after* we've set up the data fields
2648c65ebfc7SToomas Soome     // 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
2649c65ebfc7SToomas Soome     owner->opt              = kDNSOpt_Owner;
2650c65ebfc7SToomas Soome     owner->optlen           = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2651c65ebfc7SToomas Soome }
2652c65ebfc7SToomas Soome 
GrantUpdateCredit(AuthRecord * rr)2653c65ebfc7SToomas Soome mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2654c65ebfc7SToomas Soome {
2655c65ebfc7SToomas Soome     if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2656c65ebfc7SToomas Soome     else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2657c65ebfc7SToomas Soome }
2658c65ebfc7SToomas Soome 
ShouldSendGoodbyesBeforeSleep(mDNS * const m,const NetworkInterfaceInfo * intf,AuthRecord * rr)2659c65ebfc7SToomas Soome mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2660c65ebfc7SToomas Soome {
2661c65ebfc7SToomas Soome     // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2662c65ebfc7SToomas Soome     // and hence there is no need to check for Transfering state. But if we have sleep
2663c65ebfc7SToomas Soome     // proxies and partially sending goodbyes for some records, we will be in Transfering
2664c65ebfc7SToomas Soome     // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2665c65ebfc7SToomas Soome     // we are not awake handles both cases.
2666c65ebfc7SToomas Soome     if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2667c65ebfc7SToomas Soome     {
2668c65ebfc7SToomas Soome         debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2669c65ebfc7SToomas Soome         return mDNStrue;
2670c65ebfc7SToomas Soome     }
2671c65ebfc7SToomas Soome 
2672c65ebfc7SToomas Soome     if (m->SleepState != SleepState_Sleeping)
2673c65ebfc7SToomas Soome         return mDNSfalse;
2674c65ebfc7SToomas Soome 
2675c65ebfc7SToomas Soome     // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2676c65ebfc7SToomas Soome     // whether you can send goodbyes or not.
2677c65ebfc7SToomas Soome     if (!intf->SendGoodbyes)
2678c65ebfc7SToomas Soome     {
2679c65ebfc7SToomas Soome         debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2680c65ebfc7SToomas Soome         return mDNSfalse;
2681c65ebfc7SToomas Soome     }
2682c65ebfc7SToomas Soome     else
2683c65ebfc7SToomas Soome     {
2684c65ebfc7SToomas Soome         debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2685c65ebfc7SToomas Soome         return mDNStrue;
2686c65ebfc7SToomas Soome     }
2687c65ebfc7SToomas Soome }
2688c65ebfc7SToomas Soome 
2689c65ebfc7SToomas Soome // Note about acceleration of announcements to facilitate automatic coalescing of
2690c65ebfc7SToomas Soome // multiple independent threads of announcements into a single synchronized thread:
2691c65ebfc7SToomas Soome // The announcements in the packet may be at different stages of maturity;
2692c65ebfc7SToomas Soome // One-second interval, two-second interval, four-second interval, and so on.
2693c65ebfc7SToomas Soome // After we've put in all the announcements that are due, we then consider
2694c65ebfc7SToomas Soome // whether there are other nearly-due announcements that are worth accelerating.
2695c65ebfc7SToomas Soome // To be eligible for acceleration, a record MUST NOT be older (further along
2696c65ebfc7SToomas Soome // its timeline) than the most mature record we've already put in the packet.
2697c65ebfc7SToomas Soome // In other words, younger records can have their timelines accelerated to catch up
2698c65ebfc7SToomas Soome // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2699c65ebfc7SToomas Soome // Older records cannot have their timelines accelerated; this would just widen
2700c65ebfc7SToomas Soome // the gap between them and their younger bretheren and get them even more out of sync.
2701c65ebfc7SToomas Soome 
2702c65ebfc7SToomas Soome // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2703c65ebfc7SToomas Soome // the record list and/or question list.
2704c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
SendResponses(mDNS * const m)2705c65ebfc7SToomas Soome mDNSlocal void SendResponses(mDNS *const m)
2706c65ebfc7SToomas Soome {
2707c65ebfc7SToomas Soome     int pktcount = 0;
2708c65ebfc7SToomas Soome     AuthRecord *rr, *r2;
2709c65ebfc7SToomas Soome     mDNSs32 maxExistingAnnounceInterval = 0;
2710c65ebfc7SToomas Soome     const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2711c65ebfc7SToomas Soome 
2712c65ebfc7SToomas Soome     m->NextScheduledResponse = m->timenow + FutureTime;
2713c65ebfc7SToomas Soome 
2714c65ebfc7SToomas Soome     if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2715c65ebfc7SToomas Soome 
2716c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2717c65ebfc7SToomas Soome         if (rr->ImmedUnicast)
2718c65ebfc7SToomas Soome         {
2719c65ebfc7SToomas Soome             mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2720c65ebfc7SToomas Soome             mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2721c65ebfc7SToomas Soome             v4.ip.v4 = rr->v4Requester;
2722c65ebfc7SToomas Soome             v6.ip.v6 = rr->v6Requester;
2723c65ebfc7SToomas Soome             if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2724c65ebfc7SToomas Soome             if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2725c65ebfc7SToomas Soome             if (rr->ImmedUnicast)
2726c65ebfc7SToomas Soome             {
2727c65ebfc7SToomas Soome                 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2728c65ebfc7SToomas Soome                 rr->ImmedUnicast = mDNSfalse;
2729c65ebfc7SToomas Soome             }
2730c65ebfc7SToomas Soome         }
2731c65ebfc7SToomas Soome 
2732c65ebfc7SToomas Soome     // ***
2733c65ebfc7SToomas Soome     // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2734c65ebfc7SToomas Soome     // ***
2735c65ebfc7SToomas Soome 
2736c65ebfc7SToomas Soome     // Run through our list of records, and decide which ones we're going to announce on all interfaces
2737c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2738c65ebfc7SToomas Soome     {
2739c65ebfc7SToomas Soome         while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2740c65ebfc7SToomas Soome         if (TimeToAnnounceThisRecord(rr, m->timenow))
2741c65ebfc7SToomas Soome         {
2742c65ebfc7SToomas Soome             if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2743c65ebfc7SToomas Soome             {
2744c65ebfc7SToomas Soome                 if (!rr->WakeUp.HMAC.l[0])
2745c65ebfc7SToomas Soome                 {
2746c65ebfc7SToomas Soome                     if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark;     // Send goodbye packet on all interfaces
2747c65ebfc7SToomas Soome                 }
2748c65ebfc7SToomas Soome                 else
2749c65ebfc7SToomas Soome                 {
2750c65ebfc7SToomas Soome                     mDNSBool unicastOnly;
2751c65ebfc7SToomas Soome                     LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2752c65ebfc7SToomas Soome                     unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse;
2753c65ebfc7SToomas Soome                     SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly);
2754c65ebfc7SToomas Soome                     for (r2 = rr; r2; r2=r2->next)
2755c65ebfc7SToomas Soome                         if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2756c65ebfc7SToomas Soome                             mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2757c65ebfc7SToomas Soome                         {
2758c65ebfc7SToomas Soome                             // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2759c65ebfc7SToomas Soome                             // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2760c65ebfc7SToomas Soome                             if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2761c65ebfc7SToomas Soome                             {
2762c65ebfc7SToomas Soome                                 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2763c65ebfc7SToomas Soome                                        r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2764c65ebfc7SToomas Soome                                 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2765c65ebfc7SToomas Soome                             }
2766c65ebfc7SToomas Soome                             r2->LastAPTime = m->timenow;
2767c65ebfc7SToomas Soome                             // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2768c65ebfc7SToomas Soome                             if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2769c65ebfc7SToomas Soome                         }
2770c65ebfc7SToomas Soome                 }
2771c65ebfc7SToomas Soome             }
2772c65ebfc7SToomas Soome             else if (ResourceRecordIsValidAnswer(rr))
2773c65ebfc7SToomas Soome             {
2774c65ebfc7SToomas Soome                 if (rr->AddressProxy.type)
2775c65ebfc7SToomas Soome                 {
2776c65ebfc7SToomas Soome                     if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2777c65ebfc7SToomas Soome                     {
2778c65ebfc7SToomas Soome                         rr->AnnounceCount--;
2779c65ebfc7SToomas Soome                         rr->ThisAPInterval *= 2;
2780c65ebfc7SToomas Soome                         rr->LastAPTime = m->timenow;
2781c65ebfc7SToomas Soome                         if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2782c65ebfc7SToomas Soome                         {
2783c65ebfc7SToomas Soome                             LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2784c65ebfc7SToomas Soome                                     rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2785c65ebfc7SToomas Soome                             SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2786c65ebfc7SToomas Soome                         }
2787c65ebfc7SToomas Soome                         else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2788c65ebfc7SToomas Soome                         {
2789c65ebfc7SToomas Soome                             LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2790c65ebfc7SToomas Soome                                     rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2791c65ebfc7SToomas Soome                             SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2792c65ebfc7SToomas Soome                         }
2793c65ebfc7SToomas Soome                     }
2794c65ebfc7SToomas Soome                 }
2795c65ebfc7SToomas Soome                 else
2796c65ebfc7SToomas Soome                 {
2797c65ebfc7SToomas Soome                     rr->ImmedAnswer = mDNSInterfaceMark;        // Send on all interfaces
2798c65ebfc7SToomas Soome                     if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2799c65ebfc7SToomas Soome                         maxExistingAnnounceInterval = rr->ThisAPInterval;
2800c65ebfc7SToomas Soome                     if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2801c65ebfc7SToomas Soome                 }
2802c65ebfc7SToomas Soome             }
2803c65ebfc7SToomas Soome         }
2804c65ebfc7SToomas Soome     }
2805c65ebfc7SToomas Soome 
2806c65ebfc7SToomas Soome     // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2807c65ebfc7SToomas Soome     // Eligible records that are more than half-way to their announcement time are accelerated
2808c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2809c65ebfc7SToomas Soome         if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2810c65ebfc7SToomas Soome             (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2811c65ebfc7SToomas Soome              TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2812c65ebfc7SToomas Soome              !rr->AddressProxy.type &&                  // Don't include ARP Annoucements when considering which records to accelerate
2813c65ebfc7SToomas Soome              ResourceRecordIsValidAnswer(rr)))
2814c65ebfc7SToomas Soome             rr->ImmedAnswer = mDNSInterfaceMark;        // Send on all interfaces
2815c65ebfc7SToomas Soome 
2816c65ebfc7SToomas Soome     // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2817c65ebfc7SToomas Soome     // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2818c65ebfc7SToomas Soome     // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2819c65ebfc7SToomas Soome     // then all that means is that it won't get sent -- which would not be the end of the world.
2820c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2821c65ebfc7SToomas Soome     {
2822c65ebfc7SToomas Soome         if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2823c65ebfc7SToomas Soome             for (r2=m->ResourceRecords; r2; r2=r2->next)                // Scan list of resource records
2824c65ebfc7SToomas Soome                 if (RRTypeIsAddressType(r2->resrec.rrtype) &&           // For all address records (A/AAAA) ...
2825c65ebfc7SToomas Soome                     ResourceRecordIsValidAnswer(r2) &&                  // ... which are valid for answer ...
2826c65ebfc7SToomas Soome                     rr->LastMCTime - r2->LastMCTime >= 0 &&             // ... which we have not sent recently ...
2827c65ebfc7SToomas Soome                     rr->resrec.rdatahash == r2->resrec.namehash &&      // ... whose name is the name of the SRV target
2828c65ebfc7SToomas Soome                     SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2829c65ebfc7SToomas Soome                     (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2830c65ebfc7SToomas Soome                     r2->ImmedAdditional = r2->resrec.InterfaceID;       // ... then mark this address record for sending too
2831c65ebfc7SToomas Soome         // We also make sure we send the DeviceInfo TXT record too, if necessary
2832c65ebfc7SToomas Soome         // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2833c65ebfc7SToomas Soome         // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2834c65ebfc7SToomas Soome         if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2835c65ebfc7SToomas Soome             if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2836c65ebfc7SToomas Soome             {
2837c65ebfc7SToomas Soome                 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2838c65ebfc7SToomas Soome                 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2839c65ebfc7SToomas Soome             }
2840c65ebfc7SToomas Soome     }
2841c65ebfc7SToomas Soome 
2842c65ebfc7SToomas Soome     // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2843c65ebfc7SToomas Soome     // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2844c65ebfc7SToomas Soome     // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2845c65ebfc7SToomas Soome     // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2846c65ebfc7SToomas Soome     // -- 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
2847c65ebfc7SToomas Soome     // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2848c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2849c65ebfc7SToomas Soome         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2850c65ebfc7SToomas Soome         {
2851c65ebfc7SToomas Soome             if (rr->ImmedAnswer)            // If we're sending this as answer, see that its whole RRSet is similarly marked
2852c65ebfc7SToomas Soome             {
2853c65ebfc7SToomas Soome                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2854c65ebfc7SToomas Soome                 {
2855c65ebfc7SToomas Soome                     if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2856c65ebfc7SToomas Soome                         (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) &&
2857c65ebfc7SToomas Soome                         SameResourceRecordSignature(r2, rr) &&
2858c65ebfc7SToomas Soome                         ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer)))
2859c65ebfc7SToomas Soome                     {
2860c65ebfc7SToomas Soome                         r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2861c65ebfc7SToomas Soome                     }
2862c65ebfc7SToomas Soome                 }
2863c65ebfc7SToomas Soome             }
2864c65ebfc7SToomas Soome             else if (rr->ImmedAdditional)   // If we're sending this as additional, see that its whole RRSet is similarly marked
2865c65ebfc7SToomas Soome             {
2866c65ebfc7SToomas Soome                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2867c65ebfc7SToomas Soome                 {
2868c65ebfc7SToomas Soome                     if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2869c65ebfc7SToomas Soome                         (r2->ImmedAdditional != rr->ImmedAdditional) &&
2870c65ebfc7SToomas Soome                         SameResourceRecordSignature(r2, rr) &&
2871c65ebfc7SToomas Soome                         IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional))
2872c65ebfc7SToomas Soome                     {
2873c65ebfc7SToomas Soome                         r2->ImmedAdditional = rr->ImmedAdditional;
2874c65ebfc7SToomas Soome                     }
2875c65ebfc7SToomas Soome                 }
2876c65ebfc7SToomas Soome             }
2877c65ebfc7SToomas Soome         }
2878c65ebfc7SToomas Soome 
2879c65ebfc7SToomas Soome     // Now set SendRNow state appropriately
2880c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
2881c65ebfc7SToomas Soome     {
2882c65ebfc7SToomas Soome         if (rr->ImmedAnswer == mDNSInterfaceMark)       // Sending this record on all appropriate interfaces
2883c65ebfc7SToomas Soome         {
2884c65ebfc7SToomas Soome             rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2885c65ebfc7SToomas Soome             rr->ImmedAdditional = mDNSNULL;             // No need to send as additional if sending as answer
2886c65ebfc7SToomas Soome             rr->LastMCTime      = m->timenow;
2887c65ebfc7SToomas Soome             rr->LastMCInterface = rr->ImmedAnswer;
2888c65ebfc7SToomas Soome             rr->ProbeRestartCount = 0;                  // Reset the probe restart count
2889c65ebfc7SToomas Soome             // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2890c65ebfc7SToomas Soome             if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2891c65ebfc7SToomas Soome             {
2892c65ebfc7SToomas Soome                 rr->AnnounceCount--;
2893c65ebfc7SToomas Soome                 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2894c65ebfc7SToomas Soome                     rr->ThisAPInterval *= 2;
2895c65ebfc7SToomas Soome                 rr->LastAPTime = m->timenow;
2896c65ebfc7SToomas Soome                 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2897c65ebfc7SToomas Soome             }
2898c65ebfc7SToomas Soome         }
2899c65ebfc7SToomas Soome         else if (rr->ImmedAnswer)                       // Else, just respond to a single query on single interface:
2900c65ebfc7SToomas Soome         {
2901c65ebfc7SToomas Soome             rr->SendRNow        = rr->ImmedAnswer;      // Just respond on that interface
2902c65ebfc7SToomas Soome             rr->ImmedAdditional = mDNSNULL;             // No need to send as additional too
2903c65ebfc7SToomas Soome             rr->LastMCTime      = m->timenow;
2904c65ebfc7SToomas Soome             rr->LastMCInterface = rr->ImmedAnswer;
2905c65ebfc7SToomas Soome         }
2906c65ebfc7SToomas Soome         SetNextAnnounceProbeTime(m, rr);
2907c65ebfc7SToomas Soome         //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2908c65ebfc7SToomas Soome     }
2909c65ebfc7SToomas Soome 
2910c65ebfc7SToomas Soome     // ***
2911c65ebfc7SToomas Soome     // *** 2. Loop through interface list, sending records as appropriate
2912c65ebfc7SToomas Soome     // ***
2913c65ebfc7SToomas Soome 
2914c65ebfc7SToomas Soome     while (intf)
2915c65ebfc7SToomas Soome     {
2916c65ebfc7SToomas Soome         int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2917c65ebfc7SToomas Soome         int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2918c65ebfc7SToomas Soome         int numDereg    = 0;
2919c65ebfc7SToomas Soome         int numAnnounce = 0;
2920c65ebfc7SToomas Soome         int numAnswer   = 0;
2921c65ebfc7SToomas Soome         mDNSu8 *responseptr = m->omsg.data;
2922c65ebfc7SToomas Soome         mDNSu8 *newptr;
2923c65ebfc7SToomas Soome         InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2924c65ebfc7SToomas Soome 
2925c65ebfc7SToomas Soome         // First Pass. Look for:
2926c65ebfc7SToomas Soome         // 1. Deregistering records that need to send their goodbye packet
2927c65ebfc7SToomas Soome         // 2. Updated records that need to retract their old data
2928c65ebfc7SToomas Soome         // 3. Answers and announcements we need to send
2929c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
2930c65ebfc7SToomas Soome         {
2931c65ebfc7SToomas Soome 
2932c65ebfc7SToomas Soome             // Skip this interface if the record InterfaceID is *Any and the record is not
2933c65ebfc7SToomas Soome             // appropriate for the interface type.
2934c65ebfc7SToomas Soome             if ((rr->SendRNow == intf->InterfaceID) &&
2935c65ebfc7SToomas Soome                 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)))
2936c65ebfc7SToomas Soome             {
2937c65ebfc7SToomas Soome                 rr->SendRNow = GetNextActiveInterfaceID(intf);
2938c65ebfc7SToomas Soome             }
2939c65ebfc7SToomas Soome             else if (rr->SendRNow == intf->InterfaceID)
2940c65ebfc7SToomas Soome             {
2941c65ebfc7SToomas Soome                 RData  *OldRData    = rr->resrec.rdata;
2942c65ebfc7SToomas Soome                 mDNSu16 oldrdlength = rr->resrec.rdlength;
2943c65ebfc7SToomas Soome                 mDNSu8 active = (mDNSu8)
2944c65ebfc7SToomas Soome                                 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2945c65ebfc7SToomas Soome                 newptr = mDNSNULL;
2946c65ebfc7SToomas Soome                 if (rr->NewRData && active)
2947c65ebfc7SToomas Soome                 {
2948c65ebfc7SToomas Soome                     // See if we should send a courtesy "goodbye" for the old data before we replace it.
2949c65ebfc7SToomas Soome                     if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2950c65ebfc7SToomas Soome                     {
2951c65ebfc7SToomas Soome                         newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2952c65ebfc7SToomas Soome                         if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2953c65ebfc7SToomas Soome                         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
2954c65ebfc7SToomas Soome                     }
2955c65ebfc7SToomas Soome                     SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2956c65ebfc7SToomas Soome                 }
2957c65ebfc7SToomas Soome 
2958c65ebfc7SToomas Soome                 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2959c65ebfc7SToomas Soome                     rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2960c65ebfc7SToomas Soome                 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2961c65ebfc7SToomas Soome                 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2962c65ebfc7SToomas Soome                 if (newptr)
2963c65ebfc7SToomas Soome                 {
2964c65ebfc7SToomas Soome                     responseptr = newptr;
2965c65ebfc7SToomas Soome                     rr->RequireGoodbye = active;
2966c65ebfc7SToomas Soome                     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2967c65ebfc7SToomas Soome                     else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2968c65ebfc7SToomas Soome                 }
2969c65ebfc7SToomas Soome 
2970c65ebfc7SToomas Soome                 if (rr->NewRData && active)
2971c65ebfc7SToomas Soome                     SetNewRData(&rr->resrec, OldRData, oldrdlength);
2972c65ebfc7SToomas Soome 
2973c65ebfc7SToomas Soome                 // The first time through (pktcount==0), if this record is verified unique
2974c65ebfc7SToomas Soome                 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2975c65ebfc7SToomas Soome                 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2976c65ebfc7SToomas Soome                     rr->SendNSECNow = mDNSInterfaceMark;
2977c65ebfc7SToomas Soome 
2978c65ebfc7SToomas Soome                 if (newptr)     // If succeeded in sending, advance to next interface
2979c65ebfc7SToomas Soome                 {
2980c65ebfc7SToomas Soome                     // If sending on all interfaces, go to next interface; else we're finished now
2981c65ebfc7SToomas Soome                     if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2982c65ebfc7SToomas Soome                         rr->SendRNow = GetNextActiveInterfaceID(intf);
2983c65ebfc7SToomas Soome                     else
2984c65ebfc7SToomas Soome                         rr->SendRNow = mDNSNULL;
2985c65ebfc7SToomas Soome                 }
2986c65ebfc7SToomas Soome             }
2987c65ebfc7SToomas Soome         }
2988c65ebfc7SToomas Soome 
2989c65ebfc7SToomas Soome         // Second Pass. Add additional records, if there's space.
2990c65ebfc7SToomas Soome         newptr = responseptr;
2991c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
2992c65ebfc7SToomas Soome             if (rr->ImmedAdditional == intf->InterfaceID)
2993c65ebfc7SToomas Soome                 if (ResourceRecordIsValidAnswer(rr))
2994c65ebfc7SToomas Soome                 {
2995c65ebfc7SToomas Soome                     // If we have at least one answer already in the packet, then plan to add additionals too
2996c65ebfc7SToomas Soome                     mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2997c65ebfc7SToomas Soome 
2998c65ebfc7SToomas Soome                     // If we're not planning to send any additionals, but this record is a unique one, then
2999c65ebfc7SToomas Soome                     // make sure we haven't already sent any other members of its RRSet -- if we have, then they
3000c65ebfc7SToomas Soome                     // will have had the cache flush bit set, so now we need to finish the job and send the rest.
3001c65ebfc7SToomas Soome                     if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
3002c65ebfc7SToomas Soome                     {
3003c65ebfc7SToomas Soome                         const AuthRecord *a;
3004c65ebfc7SToomas Soome                         for (a = m->ResourceRecords; a; a=a->next)
3005c65ebfc7SToomas Soome                             if (a->LastMCTime      == m->timenow &&
3006c65ebfc7SToomas Soome                                 a->LastMCInterface == intf->InterfaceID &&
3007c65ebfc7SToomas Soome                                 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
3008c65ebfc7SToomas Soome                     }
3009c65ebfc7SToomas Soome                     if (!SendAdditional)                    // If we don't want to send this after all,
3010c65ebfc7SToomas Soome                         rr->ImmedAdditional = mDNSNULL;     // then cancel its ImmedAdditional field
3011c65ebfc7SToomas Soome                     else if (newptr)                        // Else, try to add it if we can
3012c65ebfc7SToomas Soome                     {
3013c65ebfc7SToomas Soome                         // The first time through (pktcount==0), if this record is verified unique
3014c65ebfc7SToomas Soome                         // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
3015c65ebfc7SToomas Soome                         if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
3016c65ebfc7SToomas Soome                             rr->SendNSECNow = mDNSInterfaceMark;
3017c65ebfc7SToomas Soome 
3018c65ebfc7SToomas Soome                         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
3019c65ebfc7SToomas Soome                             rr->resrec.rrclass |= kDNSClass_UniqueRRSet;    // Temporarily set the cache flush bit so PutResourceRecord will set it
3020c65ebfc7SToomas Soome                         newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
3021c65ebfc7SToomas Soome                         rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;       // Make sure to clear cache flush bit back to normal state
3022c65ebfc7SToomas Soome                         if (newptr)
3023c65ebfc7SToomas Soome                         {
3024c65ebfc7SToomas Soome                             responseptr = newptr;
3025c65ebfc7SToomas Soome                             rr->ImmedAdditional = mDNSNULL;
3026c65ebfc7SToomas Soome                             rr->RequireGoodbye = mDNStrue;
3027c65ebfc7SToomas Soome                             // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
3028c65ebfc7SToomas Soome                             // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
3029c65ebfc7SToomas Soome                             // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3030c65ebfc7SToomas Soome                             // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3031c65ebfc7SToomas Soome                             rr->LastMCTime      = m->timenow;
3032c65ebfc7SToomas Soome                             rr->LastMCInterface = intf->InterfaceID;
3033c65ebfc7SToomas Soome                         }
3034c65ebfc7SToomas Soome                     }
3035c65ebfc7SToomas Soome                 }
3036c65ebfc7SToomas Soome 
3037c65ebfc7SToomas Soome         // Third Pass. Add NSEC records, if there's space.
3038c65ebfc7SToomas Soome         // When we're generating an NSEC record in response to a specify query for that type
3039c65ebfc7SToomas Soome         // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3040c65ebfc7SToomas Soome         // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3041c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
3042c65ebfc7SToomas Soome             if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
3043c65ebfc7SToomas Soome             {
3044c65ebfc7SToomas Soome                 AuthRecord nsec;
3045c65ebfc7SToomas Soome                 mDNSu8 *ptr;
3046c65ebfc7SToomas Soome                 int len;
3047c65ebfc7SToomas Soome                 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3048c65ebfc7SToomas Soome                 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
3049c65ebfc7SToomas Soome                 AssignDomainName(&nsec.namestorage, rr->resrec.name);
3050c65ebfc7SToomas Soome                 ptr = nsec.rdatastorage.u.data;
3051c65ebfc7SToomas Soome                 len = DomainNameLength(rr->resrec.name);
3052c65ebfc7SToomas Soome                 // We have a nxt name followed by window number, window length and a window bitmap
3053c65ebfc7SToomas Soome                 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
3054c65ebfc7SToomas Soome                 if (nsec.resrec.rdlength <= StandardAuthRDSize)
3055c65ebfc7SToomas Soome                 {
3056c65ebfc7SToomas Soome                     mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
3057c65ebfc7SToomas Soome                     AssignDomainName((domainname *)ptr, rr->resrec.name);
3058c65ebfc7SToomas Soome                     ptr += len;
3059c65ebfc7SToomas Soome                     *ptr++ = 0; // window number
3060c65ebfc7SToomas Soome                     *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
3061c65ebfc7SToomas Soome                     for (r2 = m->ResourceRecords; r2; r2=r2->next)
3062c65ebfc7SToomas Soome                         if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
3063c65ebfc7SToomas Soome                         {
3064c65ebfc7SToomas Soome                             if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
3065c65ebfc7SToomas Soome                             else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
3066c65ebfc7SToomas Soome                         }
3067c65ebfc7SToomas Soome                     newptr = responseptr;
3068c65ebfc7SToomas Soome                     if (!r2)    // If we successfully built our NSEC record, add it to the packet now
3069c65ebfc7SToomas Soome                     {
3070c65ebfc7SToomas Soome                         newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
3071c65ebfc7SToomas Soome                         if (newptr) responseptr = newptr;
3072c65ebfc7SToomas Soome                     }
3073c65ebfc7SToomas Soome                 }
3074c65ebfc7SToomas Soome                 else LogMsg("SendResponses: not enough space (%d)  in authrecord for nsec", nsec.resrec.rdlength);
3075c65ebfc7SToomas Soome 
3076c65ebfc7SToomas Soome                 // If we successfully put the NSEC record, clear the SendNSECNow flag
3077c65ebfc7SToomas Soome                 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3078c65ebfc7SToomas Soome                 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
3079c65ebfc7SToomas Soome                 {
3080c65ebfc7SToomas Soome                     rr->SendNSECNow = mDNSNULL;
3081c65ebfc7SToomas Soome                     // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3082c65ebfc7SToomas Soome                     for (r2 = rr->next; r2; r2=r2->next)
3083c65ebfc7SToomas Soome                         if (SameResourceRecordNameClassInterface(r2, rr))
3084c65ebfc7SToomas Soome                             if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
3085c65ebfc7SToomas Soome                                 r2->SendNSECNow = mDNSNULL;
3086c65ebfc7SToomas Soome                 }
3087c65ebfc7SToomas Soome             }
3088c65ebfc7SToomas Soome 
3089c65ebfc7SToomas Soome         if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
3090c65ebfc7SToomas Soome         {
3091c65ebfc7SToomas Soome             // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3092c65ebfc7SToomas Soome             if (OwnerRecordSpace || TraceRecordSpace)
3093c65ebfc7SToomas Soome             {
3094c65ebfc7SToomas Soome                 AuthRecord opt;
3095c65ebfc7SToomas Soome                 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3096c65ebfc7SToomas Soome                 opt.resrec.rrclass    = NormalMaxDNSMessageData;
3097c65ebfc7SToomas Soome                 opt.resrec.rdlength   = sizeof(rdataOPT);
3098c65ebfc7SToomas Soome                 opt.resrec.rdestimate = sizeof(rdataOPT);
3099c65ebfc7SToomas Soome                 if (OwnerRecordSpace && TraceRecordSpace)
3100c65ebfc7SToomas Soome                 {
3101c65ebfc7SToomas Soome                     opt.resrec.rdlength   += sizeof(rdataOPT); // Two options in this OPT record
3102c65ebfc7SToomas Soome                     opt.resrec.rdestimate += sizeof(rdataOPT);
3103c65ebfc7SToomas Soome                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3104c65ebfc7SToomas Soome                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3105c65ebfc7SToomas Soome                 }
3106c65ebfc7SToomas Soome                 else if (OwnerRecordSpace)
3107c65ebfc7SToomas Soome                 {
3108c65ebfc7SToomas Soome                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3109c65ebfc7SToomas Soome                 }
3110c65ebfc7SToomas Soome                 else if (TraceRecordSpace)
3111c65ebfc7SToomas Soome                 {
3112c65ebfc7SToomas Soome                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3113c65ebfc7SToomas Soome                 }
3114c65ebfc7SToomas Soome                 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
3115c65ebfc7SToomas Soome                 if (newptr)
3116c65ebfc7SToomas Soome                 {
3117c65ebfc7SToomas Soome                     responseptr = newptr;
3118c65ebfc7SToomas Soome                 }
3119c65ebfc7SToomas Soome                 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
3120c65ebfc7SToomas Soome                 {
3121c65ebfc7SToomas Soome                     LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3122c65ebfc7SToomas Soome                             m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3123c65ebfc7SToomas Soome                 }
3124c65ebfc7SToomas Soome                 else
3125c65ebfc7SToomas Soome                 {
3126c65ebfc7SToomas Soome                     LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3127c65ebfc7SToomas Soome                            m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3128c65ebfc7SToomas Soome                 }
3129c65ebfc7SToomas Soome             }
3130c65ebfc7SToomas Soome 
3131c65ebfc7SToomas Soome             debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3132c65ebfc7SToomas Soome                    numDereg,                 numDereg                 == 1 ? "" : "s",
3133c65ebfc7SToomas Soome                    numAnnounce,              numAnnounce              == 1 ? "" : "s",
3134c65ebfc7SToomas Soome                    numAnswer,                numAnswer                == 1 ? "" : "s",
3135c65ebfc7SToomas Soome                    m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
3136c65ebfc7SToomas Soome 
3137*472cd20dSToomas Soome             if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSfalse);
3138*472cd20dSToomas Soome             if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSfalse);
3139c65ebfc7SToomas Soome             if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3140c65ebfc7SToomas Soome             if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
3141c65ebfc7SToomas Soome             // There might be more things to send on this interface, so go around one more time and try again.
3142c65ebfc7SToomas Soome         }
3143c65ebfc7SToomas Soome         else    // Nothing more to send on this interface; go to next
3144c65ebfc7SToomas Soome         {
3145c65ebfc7SToomas Soome             const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3146c65ebfc7SToomas Soome             #if MDNS_DEBUGMSGS && 0
3147c65ebfc7SToomas Soome             const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3148c65ebfc7SToomas Soome             debugf(msg, intf, next);
3149c65ebfc7SToomas Soome             #endif
3150c65ebfc7SToomas Soome             intf = next;
3151c65ebfc7SToomas Soome             pktcount = 0;       // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3152c65ebfc7SToomas Soome         }
3153c65ebfc7SToomas Soome     }
3154c65ebfc7SToomas Soome 
3155c65ebfc7SToomas Soome     // ***
3156c65ebfc7SToomas Soome     // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3157c65ebfc7SToomas Soome     // ***
3158c65ebfc7SToomas Soome 
3159c65ebfc7SToomas Soome     if (m->CurrentRecord)
3160c65ebfc7SToomas Soome         LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3161c65ebfc7SToomas Soome     m->CurrentRecord = m->ResourceRecords;
3162c65ebfc7SToomas Soome     while (m->CurrentRecord)
3163c65ebfc7SToomas Soome     {
3164c65ebfc7SToomas Soome         rr = m->CurrentRecord;
3165c65ebfc7SToomas Soome         m->CurrentRecord = rr->next;
3166c65ebfc7SToomas Soome 
3167c65ebfc7SToomas Soome         if (rr->SendRNow)
3168c65ebfc7SToomas Soome         {
3169c65ebfc7SToomas Soome             if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
3170c65ebfc7SToomas Soome                 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3171*472cd20dSToomas Soome                 IIDPrintable(rr->SendRNow), IIDPrintable(rr->resrec.InterfaceID), rr->resrec.RecordType, ARDisplayString(m, rr));
3172c65ebfc7SToomas Soome             rr->SendRNow = mDNSNULL;
3173c65ebfc7SToomas Soome         }
3174c65ebfc7SToomas Soome 
3175c65ebfc7SToomas Soome         if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3176c65ebfc7SToomas Soome         {
3177c65ebfc7SToomas Soome             if (rr->NewRData) CompleteRDataUpdate(m, rr);   // Update our rdata, clear the NewRData pointer, and return memory to the client
3178c65ebfc7SToomas Soome 
3179c65ebfc7SToomas Soome             if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
3180c65ebfc7SToomas Soome             {
3181c65ebfc7SToomas Soome                 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3182c65ebfc7SToomas Soome                 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr);        // Don't touch rr after this
3183c65ebfc7SToomas Soome             }
3184c65ebfc7SToomas Soome             else
3185c65ebfc7SToomas Soome             {
3186c65ebfc7SToomas Soome                 rr->ImmedAnswer  = mDNSNULL;
3187c65ebfc7SToomas Soome                 rr->ImmedUnicast = mDNSfalse;
3188c65ebfc7SToomas Soome                 rr->v4Requester  = zerov4Addr;
3189c65ebfc7SToomas Soome                 rr->v6Requester  = zerov6Addr;
3190c65ebfc7SToomas Soome             }
3191c65ebfc7SToomas Soome         }
3192c65ebfc7SToomas Soome     }
3193c65ebfc7SToomas Soome     verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
3194c65ebfc7SToomas Soome }
3195c65ebfc7SToomas Soome 
3196c65ebfc7SToomas Soome // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3197c65ebfc7SToomas Soome // so we want to be lazy about how frequently we do it.
3198c65ebfc7SToomas Soome // 1. If a cache record is currently referenced by *no* active questions,
3199c65ebfc7SToomas Soome //    then we don't mind expiring it up to a minute late (who will know?)
3200c65ebfc7SToomas Soome // 2. Else, if a cache record is due for some of its final expiration queries,
3201c65ebfc7SToomas Soome //    we'll allow them to be late by up to 2% of the TTL
3202c65ebfc7SToomas Soome // 3. Else, if a cache record has completed all its final expiration queries without success,
3203c65ebfc7SToomas Soome //    and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3204c65ebfc7SToomas Soome // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3205c65ebfc7SToomas Soome //    so allow at most 1/10 second lateness
3206c65ebfc7SToomas Soome // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3207c65ebfc7SToomas Soome //    (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3208*472cd20dSToomas Soome #define CacheCheckGracePeriod(CR) (                                                   \
3209*472cd20dSToomas Soome         ((CR)->CRActiveQuestion == mDNSNULL            ) ? (60 * mDNSPlatformOneSecond) : \
3210*472cd20dSToomas Soome         ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50)            : \
3211*472cd20dSToomas Soome         ((CR)->resrec.rroriginalttl > 10               ) ? (mDNSPlatformOneSecond)      : \
3212*472cd20dSToomas Soome         ((CR)->resrec.rroriginalttl > 0                ) ? (mDNSPlatformOneSecond/10)   : 0)
3213c65ebfc7SToomas Soome 
3214*472cd20dSToomas Soome #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3215c65ebfc7SToomas Soome 
ScheduleNextCacheCheckTime(mDNS * const m,const mDNSu32 slot,const mDNSs32 event)3216c65ebfc7SToomas Soome mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
3217c65ebfc7SToomas Soome {
3218c65ebfc7SToomas Soome     if (m->rrcache_nextcheck[slot] - event > 0)
3219c65ebfc7SToomas Soome         m->rrcache_nextcheck[slot] = event;
3220c65ebfc7SToomas Soome     if (m->NextCacheCheck          - event > 0)
3221c65ebfc7SToomas Soome         m->NextCacheCheck          = event;
3222c65ebfc7SToomas Soome }
3223c65ebfc7SToomas Soome 
3224c65ebfc7SToomas Soome // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3225c65ebfc7SToomas Soome // rr->TimeRcvd
3226c65ebfc7SToomas Soome // rr->resrec.rroriginalttl
3227c65ebfc7SToomas Soome // rr->UnansweredQueries
3228c65ebfc7SToomas Soome // rr->CRActiveQuestion
SetNextCacheCheckTimeForRecord(mDNS * const m,CacheRecord * const rr)3229c65ebfc7SToomas Soome mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
3230c65ebfc7SToomas Soome {
3231c65ebfc7SToomas Soome     rr->NextRequiredQuery = RRExpireTime(rr);
3232c65ebfc7SToomas Soome 
3233c65ebfc7SToomas Soome     // If we have an active question, then see if we want to schedule a refresher query for this record.
3234c65ebfc7SToomas Soome     // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3235c65ebfc7SToomas Soome     if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3236c65ebfc7SToomas Soome     {
3237c65ebfc7SToomas Soome         rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3238c65ebfc7SToomas Soome         rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3239c65ebfc7SToomas Soome         verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3240c65ebfc7SToomas Soome                       (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
3241c65ebfc7SToomas Soome     }
3242c65ebfc7SToomas Soome     ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr));
3243c65ebfc7SToomas Soome }
3244c65ebfc7SToomas Soome 
3245c65ebfc7SToomas Soome #define kMinimumReconfirmTime                     ((mDNSu32)mDNSPlatformOneSecond *  5)
3246c65ebfc7SToomas Soome #define kDefaultReconfirmTimeForWake              ((mDNSu32)mDNSPlatformOneSecond *  5)
3247c65ebfc7SToomas Soome #define kDefaultReconfirmTimeForNoAnswer          ((mDNSu32)mDNSPlatformOneSecond *  5)
3248c65ebfc7SToomas Soome 
3249c65ebfc7SToomas Soome // Delay before restarting questions on a flapping interface.
3250c65ebfc7SToomas Soome #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond *  3)
3251c65ebfc7SToomas Soome // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3252c65ebfc7SToomas Soome // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3253c65ebfc7SToomas Soome #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond *  7))
3254c65ebfc7SToomas Soome 
mDNS_Reconfirm_internal(mDNS * const m,CacheRecord * const rr,mDNSu32 interval)3255c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3256c65ebfc7SToomas Soome {
3257c65ebfc7SToomas Soome     if (interval < kMinimumReconfirmTime)
3258c65ebfc7SToomas Soome         interval = kMinimumReconfirmTime;
3259c65ebfc7SToomas Soome     if (interval > 0x10000000)  // Make sure interval doesn't overflow when we multiply by four below
3260c65ebfc7SToomas Soome         interval = 0x10000000;
3261c65ebfc7SToomas Soome 
3262c65ebfc7SToomas Soome     // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3263c65ebfc7SToomas Soome     if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3264c65ebfc7SToomas Soome     {
3265c65ebfc7SToomas Soome         // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3266c65ebfc7SToomas Soome         // For all the reconfirmations in a given batch, we want to use the same random value
3267c65ebfc7SToomas Soome         // so that the reconfirmation questions can be grouped into a single query packet
3268c65ebfc7SToomas Soome         if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime);
3269c65ebfc7SToomas Soome         interval += m->RandomReconfirmDelay % ((interval/3) + 1);
3270c65ebfc7SToomas Soome         rr->TimeRcvd          = m->timenow - (mDNSs32)interval * 3;
3271c65ebfc7SToomas Soome         rr->resrec.rroriginalttl     = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
3272c65ebfc7SToomas Soome         SetNextCacheCheckTimeForRecord(m, rr);
3273c65ebfc7SToomas Soome     }
3274c65ebfc7SToomas Soome     debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3275c65ebfc7SToomas Soome            RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
3276c65ebfc7SToomas Soome     return(mStatus_NoError);
3277c65ebfc7SToomas Soome }
3278c65ebfc7SToomas Soome 
3279c65ebfc7SToomas Soome // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3280c65ebfc7SToomas Soome // It also appends to the list of known answer records that need to be included,
3281c65ebfc7SToomas Soome // and updates the forcast for the size of the known answer section.
BuildQuestion(mDNS * const m,const NetworkInterfaceInfo * intf,DNSMessage * query,mDNSu8 ** queryptr,DNSQuestion * q,CacheRecord *** kalistptrptr,mDNSu32 * answerforecast)3282c65ebfc7SToomas Soome mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
3283c65ebfc7SToomas Soome                                  DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3284c65ebfc7SToomas Soome {
3285c65ebfc7SToomas Soome     mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3286c65ebfc7SToomas Soome     mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3287c65ebfc7SToomas Soome     const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3288*472cd20dSToomas Soome     mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3289c65ebfc7SToomas Soome     if (!newptr)
3290c65ebfc7SToomas Soome     {
3291c65ebfc7SToomas Soome         debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3292c65ebfc7SToomas Soome         return(mDNSfalse);
3293c65ebfc7SToomas Soome     }
3294c65ebfc7SToomas Soome     else
3295c65ebfc7SToomas Soome     {
3296*472cd20dSToomas Soome         mDNSu32 forecast = *answerforecast;
3297c65ebfc7SToomas Soome         const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3298*472cd20dSToomas Soome         CacheRecord *cr;
3299c65ebfc7SToomas Soome         CacheRecord **ka = *kalistptrptr;   // Make a working copy of the pointer we're going to update
3300c65ebfc7SToomas Soome 
3301*472cd20dSToomas Soome         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)             // If we have a resource record in our cache,
3302*472cd20dSToomas Soome             if (cr->resrec.InterfaceID == q->SendQNow &&                    // received on this interface
3303*472cd20dSToomas Soome                 !(cr->resrec.RecordType & kDNSRecordTypeUniqueMask) &&      // which is a shared (i.e. not unique) record type
3304*472cd20dSToomas Soome                 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList &&  // which is not already in the known answer list
3305*472cd20dSToomas Soome                 cr->resrec.rdlength <= SmallRecordLimit &&                  // which is small enough to sensibly fit in the packet
3306*472cd20dSToomas Soome                 SameNameCacheRecordAnswersQuestion(cr, q) &&                // which answers our question
3307*472cd20dSToomas Soome                 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >                // and its half-way-to-expiry time is at least 1 second away
3308c65ebfc7SToomas Soome                 mDNSPlatformOneSecond)                                      // (also ensures we never include goodbye records with TTL=1)
3309c65ebfc7SToomas Soome             {
3310c65ebfc7SToomas Soome                 // We don't want to include unique records in the Known Answer section. The Known Answer section
3311c65ebfc7SToomas Soome                 // is intended to suppress floods of shared-record replies from many other devices on the network.
3312c65ebfc7SToomas Soome                 // That concept really does not apply to unique records, and indeed if we do send a query for
3313c65ebfc7SToomas Soome                 // which we have a unique record already in our cache, then including that unique record as a
3314c65ebfc7SToomas Soome                 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3315c65ebfc7SToomas Soome 
3316*472cd20dSToomas Soome                 *ka = cr;   // Link this record into our known answer chain
3317*472cd20dSToomas Soome                 ka = &cr->NextInKAList;
3318c65ebfc7SToomas Soome                 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3319*472cd20dSToomas Soome                 forecast += 12 + cr->resrec.rdestimate;
3320c65ebfc7SToomas Soome                 // If we're trying to put more than one question in this packet, and it doesn't fit
3321c65ebfc7SToomas Soome                 // then undo that last question and try again next time
3322c65ebfc7SToomas Soome                 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3323c65ebfc7SToomas Soome                 {
3324c65ebfc7SToomas Soome                     query->h.numQuestions--;
3325c65ebfc7SToomas Soome                     debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3326c65ebfc7SToomas Soome                            q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3327c65ebfc7SToomas Soome                     ka = *kalistptrptr;     // Go back to where we started and retract these answer records
3328c65ebfc7SToomas Soome                     while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3329c65ebfc7SToomas Soome                     return(mDNSfalse);      // Return false, so we'll try again in the next packet
3330c65ebfc7SToomas Soome                 }
3331c65ebfc7SToomas Soome             }
3332c65ebfc7SToomas Soome 
3333c65ebfc7SToomas Soome         // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3334c65ebfc7SToomas Soome         *queryptr        = newptr;              // Update the packet pointer
3335c65ebfc7SToomas Soome         *answerforecast  = forecast;            // Update the forecast
3336c65ebfc7SToomas Soome         *kalistptrptr    = ka;                  // Update the known answer list pointer
3337c65ebfc7SToomas Soome         if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3338c65ebfc7SToomas Soome 
3339*472cd20dSToomas Soome         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)             // For every resource record in our cache,
3340*472cd20dSToomas Soome             if (cr->resrec.InterfaceID == q->SendQNow &&                    // received on this interface
3341*472cd20dSToomas Soome                 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList &&  // which is not in the known answer list
3342*472cd20dSToomas Soome                 SameNameCacheRecordAnswersQuestion(cr, q))                  // which answers our question
3343c65ebfc7SToomas Soome             {
3344*472cd20dSToomas Soome                 cr->UnansweredQueries++;                                    // indicate that we're expecting a response
3345*472cd20dSToomas Soome                 cr->LastUnansweredTime = m->timenow;
3346*472cd20dSToomas Soome                 SetNextCacheCheckTimeForRecord(m, cr);
3347c65ebfc7SToomas Soome             }
3348c65ebfc7SToomas Soome 
3349c65ebfc7SToomas Soome         return(mDNStrue);
3350c65ebfc7SToomas Soome     }
3351c65ebfc7SToomas Soome }
3352c65ebfc7SToomas Soome 
3353c65ebfc7SToomas Soome // When we have a query looking for a specified name, but there appear to be no answers with
3354c65ebfc7SToomas Soome // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3355c65ebfc7SToomas Soome // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3356c65ebfc7SToomas Soome // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3357c65ebfc7SToomas Soome // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3358c65ebfc7SToomas Soome // A typical reconfirmation scenario might go like this:
3359c65ebfc7SToomas Soome // Depth 0: Name "myhost.local" has no address records
3360c65ebfc7SToomas Soome // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3361c65ebfc7SToomas Soome // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3362c65ebfc7SToomas Soome // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3363c65ebfc7SToomas Soome // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3364c65ebfc7SToomas Soome // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
ReconfirmAntecedents(mDNS * const m,const domainname * const name,const mDNSu32 namehash,const mDNSInterfaceID InterfaceID,const int depth)33653b436d06SToomas Soome mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth)
3366c65ebfc7SToomas Soome {
3367c65ebfc7SToomas Soome     mDNSu32 slot;
33683b436d06SToomas Soome     const CacheGroup *cg;
3369c65ebfc7SToomas Soome     CacheRecord *cr;
3370c65ebfc7SToomas Soome     debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
33713b436d06SToomas Soome     if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3372c65ebfc7SToomas Soome     FORALL_CACHERECORDS(slot, cg, cr)
3373c65ebfc7SToomas Soome     {
33743b436d06SToomas Soome         const domainname *crtarget;
33753b436d06SToomas Soome         if (cr->resrec.InterfaceID != InterfaceID) continue; // Skip non-mDNS records and mDNS records from other interfaces.
33763b436d06SToomas Soome         if (cr->resrec.rdatahash != namehash)      continue; // Skip records whose rdata hash doesn't match the name hash.
33773b436d06SToomas Soome         crtarget = GetRRDomainNameTarget(&cr->resrec);
33783b436d06SToomas Soome         if (crtarget && SameDomainName(crtarget, name))
3379c65ebfc7SToomas Soome         {
33803b436d06SToomas Soome             LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth, InterfaceID, CRDisplayString(m, cr));
3381c65ebfc7SToomas Soome             mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3382c65ebfc7SToomas Soome             if (depth < 5)
33833b436d06SToomas Soome                 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1);
3384c65ebfc7SToomas Soome         }
3385c65ebfc7SToomas Soome     }
3386c65ebfc7SToomas Soome }
3387c65ebfc7SToomas Soome 
3388c65ebfc7SToomas Soome // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3389c65ebfc7SToomas Soome // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3390c65ebfc7SToomas Soome // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3391c65ebfc7SToomas Soome // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
CacheHasAddressTypeForName(mDNS * const m,const domainname * const name,const mDNSu32 namehash)3392c65ebfc7SToomas Soome mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3393c65ebfc7SToomas Soome {
3394c65ebfc7SToomas Soome     CacheGroup *const cg = CacheGroupForName(m, namehash, name);
3395c65ebfc7SToomas Soome     const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3396c65ebfc7SToomas Soome     while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3397c65ebfc7SToomas Soome     return(cr);
3398c65ebfc7SToomas Soome }
3399c65ebfc7SToomas Soome 
3400c65ebfc7SToomas Soome 
FindSPSInCache1(mDNS * const m,const DNSQuestion * const q,const CacheRecord * const c0,const CacheRecord * const c1)3401c65ebfc7SToomas Soome mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3402c65ebfc7SToomas Soome {
3403c65ebfc7SToomas Soome #ifndef SPC_DISABLED
3404c65ebfc7SToomas Soome     CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3405c65ebfc7SToomas Soome     const CacheRecord *cr, *bestcr = mDNSNULL;
3406c65ebfc7SToomas Soome     mDNSu32 bestmetric = 1000000;
3407c65ebfc7SToomas Soome     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3408c65ebfc7SToomas Soome         if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6)                      // If record is PTR type, with long enough name,
3409c65ebfc7SToomas Soome             if (cr != c0 && cr != c1)                                                           // that's not one we've seen before,
3410*472cd20dSToomas Soome                 if (SameNameCacheRecordAnswersQuestion(cr, q))                                  // and answers our browse query,
3411c65ebfc7SToomas Soome                     if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec))    // and is not our own advertised service...
3412c65ebfc7SToomas Soome                     {
3413c65ebfc7SToomas Soome                         mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3414c65ebfc7SToomas Soome                         if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3415c65ebfc7SToomas Soome                     }
3416c65ebfc7SToomas Soome     return(bestcr);
3417c65ebfc7SToomas Soome #else // SPC_DISABLED
3418c65ebfc7SToomas Soome     (void) m;
3419c65ebfc7SToomas Soome     (void) q;
3420c65ebfc7SToomas Soome     (void) c0;
3421c65ebfc7SToomas Soome     (void) c1;
3422c65ebfc7SToomas Soome     (void) c1;
3423c65ebfc7SToomas Soome     return mDNSNULL;
3424c65ebfc7SToomas Soome #endif // SPC_DISABLED
3425c65ebfc7SToomas Soome }
3426c65ebfc7SToomas Soome 
CheckAndSwapSPS(const CacheRecord ** sps1,const CacheRecord ** sps2)3427c65ebfc7SToomas Soome mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3428c65ebfc7SToomas Soome {
3429c65ebfc7SToomas Soome     const CacheRecord *swap_sps;
3430c65ebfc7SToomas Soome     mDNSu32 metric1, metric2;
3431c65ebfc7SToomas Soome 
3432c65ebfc7SToomas Soome     if (!(*sps1) || !(*sps2)) return;
3433c65ebfc7SToomas Soome     metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3434c65ebfc7SToomas Soome     metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3435c65ebfc7SToomas Soome     if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3436c65ebfc7SToomas Soome     {
3437c65ebfc7SToomas Soome         swap_sps = *sps1;
3438c65ebfc7SToomas Soome         *sps1    = *sps2;
3439c65ebfc7SToomas Soome         *sps2    = swap_sps;
3440c65ebfc7SToomas Soome     }
3441c65ebfc7SToomas Soome }
3442c65ebfc7SToomas Soome 
ReorderSPSByFeature(const CacheRecord * sps[3])3443c65ebfc7SToomas Soome mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3444c65ebfc7SToomas Soome {
3445c65ebfc7SToomas Soome     CheckAndSwapSPS(&sps[0], &sps[1]);
3446c65ebfc7SToomas Soome     CheckAndSwapSPS(&sps[0], &sps[2]);
3447c65ebfc7SToomas Soome     CheckAndSwapSPS(&sps[1], &sps[2]);
3448c65ebfc7SToomas Soome }
3449c65ebfc7SToomas Soome 
3450c65ebfc7SToomas Soome 
3451c65ebfc7SToomas Soome // Finds the three best Sleep Proxies we currently have in our cache
FindSPSInCache(mDNS * const m,const DNSQuestion * const q,const CacheRecord * sps[3])3452c65ebfc7SToomas Soome mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3453c65ebfc7SToomas Soome {
3454c65ebfc7SToomas Soome     sps[0] =                      FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3455c65ebfc7SToomas Soome     sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   mDNSNULL);
3456c65ebfc7SToomas Soome     sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   sps[1]);
3457c65ebfc7SToomas Soome 
3458c65ebfc7SToomas Soome     // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3459c65ebfc7SToomas Soome     // only if they have equally good metric and support features.
3460c65ebfc7SToomas Soome     ReorderSPSByFeature(sps);
3461c65ebfc7SToomas Soome }
3462c65ebfc7SToomas Soome 
3463c65ebfc7SToomas Soome // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize],mDNSs32 time)3464c65ebfc7SToomas Soome mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3465c65ebfc7SToomas Soome {
3466c65ebfc7SToomas Soome     int i;
3467c65ebfc7SToomas Soome     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3468c65ebfc7SToomas Soome }
3469c65ebfc7SToomas Soome 
ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize],mDNSs32 time,mDNSInterfaceID InterfaceID)3470c65ebfc7SToomas Soome mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3471c65ebfc7SToomas Soome {
3472c65ebfc7SToomas Soome     int i;
3473c65ebfc7SToomas Soome     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3474c65ebfc7SToomas Soome }
3475c65ebfc7SToomas Soome 
SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize],const NetworkInterfaceInfo * const intf)3476c65ebfc7SToomas Soome mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3477c65ebfc7SToomas Soome {
3478c65ebfc7SToomas Soome     int i;
3479c65ebfc7SToomas Soome     mDNSBool v4 = !intf->IPv4Available;     // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3480c65ebfc7SToomas Soome     mDNSBool v6 = !intf->IPv6Available;     // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3481c65ebfc7SToomas Soome     for (i=0; i<DupSuppressInfoSize; i++)
3482c65ebfc7SToomas Soome         if (ds[i].InterfaceID == intf->InterfaceID)
3483c65ebfc7SToomas Soome         {
3484c65ebfc7SToomas Soome             if      (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3485c65ebfc7SToomas Soome             else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3486c65ebfc7SToomas Soome             if (v4 && v6) return(mDNStrue);
3487c65ebfc7SToomas Soome         }
3488c65ebfc7SToomas Soome     return(mDNSfalse);
3489c65ebfc7SToomas Soome }
3490c65ebfc7SToomas Soome 
RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize],mDNSs32 Time,mDNSInterfaceID InterfaceID,mDNSs32 Type)3491c65ebfc7SToomas Soome mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3492c65ebfc7SToomas Soome {
3493c65ebfc7SToomas Soome     int i, j;
3494c65ebfc7SToomas Soome 
3495c65ebfc7SToomas Soome     // See if we have this one in our list somewhere already
3496c65ebfc7SToomas Soome     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3497c65ebfc7SToomas Soome 
3498c65ebfc7SToomas Soome     // If not, find a slot we can re-use
3499c65ebfc7SToomas Soome     if (i >= DupSuppressInfoSize)
3500c65ebfc7SToomas Soome     {
3501c65ebfc7SToomas Soome         i = 0;
3502c65ebfc7SToomas Soome         for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3503c65ebfc7SToomas Soome             if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3504c65ebfc7SToomas Soome                 i = j;
3505c65ebfc7SToomas Soome     }
3506c65ebfc7SToomas Soome 
3507c65ebfc7SToomas Soome     // Record the info about this query we saw
3508c65ebfc7SToomas Soome     ds[i].Time        = Time;
3509c65ebfc7SToomas Soome     ds[i].InterfaceID = InterfaceID;
3510c65ebfc7SToomas Soome     ds[i].Type        = Type;
3511c65ebfc7SToomas Soome }
3512c65ebfc7SToomas Soome 
mDNSSendWakeOnResolve(mDNS * const m,DNSQuestion * q)3513c65ebfc7SToomas Soome mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3514c65ebfc7SToomas Soome {
3515c65ebfc7SToomas Soome     int len, i, cnt;
3516c65ebfc7SToomas Soome     mDNSInterfaceID InterfaceID = q->InterfaceID;
3517c65ebfc7SToomas Soome     domainname *d = &q->qname;
3518c65ebfc7SToomas Soome 
3519c65ebfc7SToomas Soome     // We can't send magic packets without knowing which interface to send it on.
3520c65ebfc7SToomas Soome     if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID))
3521c65ebfc7SToomas Soome     {
3522c65ebfc7SToomas Soome         LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3523c65ebfc7SToomas Soome         return;
3524c65ebfc7SToomas Soome     }
3525c65ebfc7SToomas Soome 
3526c65ebfc7SToomas Soome     // Split MAC@IPAddress and pass them separately
3527c65ebfc7SToomas Soome     len = d->c[0];
3528c65ebfc7SToomas Soome     cnt = 0;
3529c65ebfc7SToomas Soome     for (i = 1; i < len; i++)
3530c65ebfc7SToomas Soome     {
3531c65ebfc7SToomas Soome         if (d->c[i] == '@')
3532c65ebfc7SToomas Soome         {
3533c65ebfc7SToomas Soome             char EthAddr[18];   // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3534c65ebfc7SToomas Soome             char IPAddr[47];    // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3535c65ebfc7SToomas Soome             if (cnt != 5)
3536c65ebfc7SToomas Soome             {
3537c65ebfc7SToomas Soome                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3538c65ebfc7SToomas Soome                 return;
3539c65ebfc7SToomas Soome             }
3540c65ebfc7SToomas Soome             if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3541c65ebfc7SToomas Soome             {
3542c65ebfc7SToomas Soome                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3543c65ebfc7SToomas Soome                 return;
3544c65ebfc7SToomas Soome             }
3545c65ebfc7SToomas Soome             if ((len - i) > (int)(sizeof(IPAddr) - 1))
3546c65ebfc7SToomas Soome             {
3547c65ebfc7SToomas Soome                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3548c65ebfc7SToomas Soome                 return;
3549c65ebfc7SToomas Soome             }
3550c65ebfc7SToomas Soome             mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3551c65ebfc7SToomas Soome             EthAddr[i - 1] = 0;
3552c65ebfc7SToomas Soome             mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3553c65ebfc7SToomas Soome             IPAddr[len - i] = 0;
3554c65ebfc7SToomas Soome             m->mDNSStats.WakeOnResolves++;
3555c65ebfc7SToomas Soome             mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3556c65ebfc7SToomas Soome             return;
3557c65ebfc7SToomas Soome         }
3558c65ebfc7SToomas Soome         else if (d->c[i] == ':')
3559c65ebfc7SToomas Soome             cnt++;
3560c65ebfc7SToomas Soome     }
3561c65ebfc7SToomas Soome     LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3562c65ebfc7SToomas Soome }
3563c65ebfc7SToomas Soome 
3564c65ebfc7SToomas Soome 
AccelerateThisQuery(mDNS * const m,DNSQuestion * q)3565c65ebfc7SToomas Soome mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3566c65ebfc7SToomas Soome {
3567c65ebfc7SToomas Soome     // If more than 90% of the way to the query time, we should unconditionally accelerate it
3568c65ebfc7SToomas Soome     if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3569c65ebfc7SToomas Soome         return(mDNStrue);
3570c65ebfc7SToomas Soome 
3571c65ebfc7SToomas Soome     // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3572c65ebfc7SToomas Soome     if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3573c65ebfc7SToomas Soome     {
3574c65ebfc7SToomas Soome         // We forecast: qname (n) type (2) class (2)
3575c65ebfc7SToomas Soome         mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3576c65ebfc7SToomas Soome         const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3577*472cd20dSToomas Soome         const CacheRecord *cr;
3578*472cd20dSToomas Soome         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)              // If we have a resource record in our cache,
3579*472cd20dSToomas Soome             if (cr->resrec.rdlength <= SmallRecordLimit &&                   // which is small enough to sensibly fit in the packet
3580*472cd20dSToomas Soome                 SameNameCacheRecordAnswersQuestion(cr, q) &&                 // which answers our question
3581*472cd20dSToomas Soome                 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >= 0 &&           // and it is less than half-way to expiry
3582*472cd20dSToomas Soome                 cr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3583c65ebfc7SToomas Soome             {
3584c65ebfc7SToomas Soome                 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3585*472cd20dSToomas Soome                 forecast += 12 + cr->resrec.rdestimate;
3586c65ebfc7SToomas Soome                 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3587c65ebfc7SToomas Soome             }
3588c65ebfc7SToomas Soome         return(mDNStrue);
3589c65ebfc7SToomas Soome     }
3590c65ebfc7SToomas Soome 
3591c65ebfc7SToomas Soome     return(mDNSfalse);
3592c65ebfc7SToomas Soome }
3593c65ebfc7SToomas Soome 
3594c65ebfc7SToomas Soome // How Standard Queries are generated:
3595c65ebfc7SToomas Soome // 1. The Question Section contains the question
3596c65ebfc7SToomas Soome // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3597c65ebfc7SToomas Soome 
3598c65ebfc7SToomas Soome // How Probe Queries are generated:
3599c65ebfc7SToomas Soome // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3600c65ebfc7SToomas Soome // if some other host is already using *any* records with this name, we want to know about it.
3601c65ebfc7SToomas Soome // 2. The Authority Section contains the proposed values we intend to use for one or more
3602c65ebfc7SToomas Soome // of our records with that name (analogous to the Update section of DNS Update packets)
3603c65ebfc7SToomas Soome // because if some other host is probing at the same time, we each want to know what the other is
3604c65ebfc7SToomas Soome // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3605c65ebfc7SToomas Soome 
SendQueries(mDNS * const m)3606c65ebfc7SToomas Soome mDNSlocal void SendQueries(mDNS *const m)
3607c65ebfc7SToomas Soome {
3608c65ebfc7SToomas Soome     mDNSu32 slot;
3609c65ebfc7SToomas Soome     CacheGroup *cg;
3610c65ebfc7SToomas Soome     CacheRecord *cr;
3611c65ebfc7SToomas Soome     AuthRecord *ar;
3612c65ebfc7SToomas Soome     int pktcount = 0;
3613c65ebfc7SToomas Soome     DNSQuestion *q;
3614c65ebfc7SToomas Soome     // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3615c65ebfc7SToomas Soome     mDNSs32 maxExistingQuestionInterval = 0;
3616c65ebfc7SToomas Soome     const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3617c65ebfc7SToomas Soome     CacheRecord *KnownAnswerList = mDNSNULL;
3618c65ebfc7SToomas Soome 
3619c65ebfc7SToomas Soome     // 1. If time for a query, work out what we need to do
3620c65ebfc7SToomas Soome 
3621c65ebfc7SToomas Soome     // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3622c65ebfc7SToomas Soome     // to their NextRequiredQuery to be worth batching them together with this one
3623c65ebfc7SToomas Soome     FORALL_CACHERECORDS(slot, cg, cr)
3624c65ebfc7SToomas Soome     {
3625c65ebfc7SToomas Soome         if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3626c65ebfc7SToomas Soome         {
3627c65ebfc7SToomas Soome             if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3628c65ebfc7SToomas Soome             {
3629c65ebfc7SToomas Soome                 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3630c65ebfc7SToomas Soome                 q = cr->CRActiveQuestion;
3631c65ebfc7SToomas Soome                 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3632c65ebfc7SToomas Soome                 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3633c65ebfc7SToomas Soome                 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3634*472cd20dSToomas Soome                 if (!mDNSOpaque16IsZero(q->TargetQID))
3635c65ebfc7SToomas Soome                 {
3636c65ebfc7SToomas Soome                     q->LastQTime = m->timenow - q->ThisQInterval;
3637c65ebfc7SToomas Soome                     cr->UnansweredQueries++;
3638c65ebfc7SToomas Soome                     m->mDNSStats.CacheRefreshQueries++;
3639c65ebfc7SToomas Soome                 }
3640c65ebfc7SToomas Soome                 else if (q->SendQNow == mDNSNULL)
3641c65ebfc7SToomas Soome                 {
3642c65ebfc7SToomas Soome                     q->SendQNow = cr->resrec.InterfaceID;
3643c65ebfc7SToomas Soome                 }
3644c65ebfc7SToomas Soome                 else if (q->SendQNow != cr->resrec.InterfaceID)
3645c65ebfc7SToomas Soome                 {
3646c65ebfc7SToomas Soome                     q->SendQNow = mDNSInterfaceMark;
3647c65ebfc7SToomas Soome                 }
3648c65ebfc7SToomas Soome 
3649c65ebfc7SToomas Soome                 // Indicate that this question was marked for sending
3650c65ebfc7SToomas Soome                 // to update an existing cached answer record.
3651c65ebfc7SToomas Soome                 // The browse throttling logic below uses this to determine
3652c65ebfc7SToomas Soome                 // if the query should be sent.
3653c65ebfc7SToomas Soome                 if (mDNSOpaque16IsZero(q->TargetQID))
3654c65ebfc7SToomas Soome                     q->CachedAnswerNeedsUpdate = mDNStrue;
3655c65ebfc7SToomas Soome             }
3656c65ebfc7SToomas Soome         }
3657c65ebfc7SToomas Soome     }
3658c65ebfc7SToomas Soome 
3659c65ebfc7SToomas Soome     // Scan our list of questions to see which:
3660c65ebfc7SToomas Soome     //     *WideArea*  queries need to be sent
3661c65ebfc7SToomas Soome     //     *unicast*   queries need to be sent
3662c65ebfc7SToomas Soome     //     *multicast* queries we're definitely going to send
3663c65ebfc7SToomas Soome     if (m->CurrentQuestion)
3664c65ebfc7SToomas Soome         LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3665c65ebfc7SToomas Soome     m->CurrentQuestion = m->Questions;
3666c65ebfc7SToomas Soome     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3667c65ebfc7SToomas Soome     {
3668c65ebfc7SToomas Soome         q = m->CurrentQuestion;
3669*472cd20dSToomas Soome         if (mDNSOpaque16IsZero(q->TargetQID) && TimeToSendThisQuestion(q, m->timenow))
3670c65ebfc7SToomas Soome         {
3671c65ebfc7SToomas Soome             //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3672c65ebfc7SToomas Soome             q->SendQNow = mDNSInterfaceMark;        // Mark this question for sending on all interfaces
3673c65ebfc7SToomas Soome             if (maxExistingQuestionInterval < q->ThisQInterval)
3674c65ebfc7SToomas Soome                 maxExistingQuestionInterval = q->ThisQInterval;
3675c65ebfc7SToomas Soome         }
3676c65ebfc7SToomas Soome         // If m->CurrentQuestion wasn't modified out from under us, advance it now
3677c65ebfc7SToomas Soome         // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3678c65ebfc7SToomas Soome         // m->CurrentQuestion point to the right question
3679c65ebfc7SToomas Soome         if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3680c65ebfc7SToomas Soome     }
3681c65ebfc7SToomas Soome     while (m->CurrentQuestion)
3682c65ebfc7SToomas Soome     {
3683c65ebfc7SToomas Soome         LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3684c65ebfc7SToomas Soome         m->CurrentQuestion = m->CurrentQuestion->next;
3685c65ebfc7SToomas Soome     }
3686c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
3687c65ebfc7SToomas Soome 
3688c65ebfc7SToomas Soome     // Scan our list of questions
3689c65ebfc7SToomas Soome     // (a) to see if there are any more that are worth accelerating, and
3690c65ebfc7SToomas Soome     // (b) to update the state variables for *all* the questions we're going to send
3691c65ebfc7SToomas Soome     // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3692c65ebfc7SToomas Soome     // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3693c65ebfc7SToomas Soome     // 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.
3694c65ebfc7SToomas Soome     m->NextScheduledQuery = m->timenow + FutureTime;
3695c65ebfc7SToomas Soome     for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3696c65ebfc7SToomas Soome     {
3697c65ebfc7SToomas Soome         if (mDNSOpaque16IsZero(q->TargetQID)
3698*472cd20dSToomas Soome             && (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3699c65ebfc7SToomas Soome         {
3700c65ebfc7SToomas Soome             // If at least halfway to next query time, advance to next interval
3701c65ebfc7SToomas Soome             // If less than halfway to next query time, then
3702c65ebfc7SToomas Soome             // treat this as logically a repeat of the last transmission, without advancing the interval
3703c65ebfc7SToomas Soome             if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3704c65ebfc7SToomas Soome             {
3705c65ebfc7SToomas Soome                 // If we have reached the answer threshold for this question,
3706c65ebfc7SToomas Soome                 // don't send it again until MaxQuestionInterval unless:
3707c65ebfc7SToomas Soome                 //  one of its cached answers needs to be refreshed,
3708c65ebfc7SToomas Soome                 //  or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3709c65ebfc7SToomas Soome                 if (q->BrowseThreshold
3710c65ebfc7SToomas Soome                     && (q->CurrentAnswers >= q->BrowseThreshold)
3711c65ebfc7SToomas Soome                     && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3712c65ebfc7SToomas Soome                     && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3713c65ebfc7SToomas Soome                 {
3714c65ebfc7SToomas Soome                     q->SendQNow = mDNSNULL;
3715c65ebfc7SToomas Soome                     q->ThisQInterval = MaxQuestionInterval;
3716c65ebfc7SToomas Soome                     q->LastQTime = m->timenow;
3717c65ebfc7SToomas Soome                     q->RequestUnicast = 0;
3718c65ebfc7SToomas Soome                     LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3719c65ebfc7SToomas Soome                          DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3720c65ebfc7SToomas Soome                 }
3721c65ebfc7SToomas Soome                 else
3722c65ebfc7SToomas Soome                 {
3723c65ebfc7SToomas Soome                     // Mark this question for sending on all interfaces
3724c65ebfc7SToomas Soome                     q->SendQNow = mDNSInterfaceMark;
3725c65ebfc7SToomas Soome                     q->ThisQInterval *= QuestionIntervalStep;
3726c65ebfc7SToomas Soome                 }
3727c65ebfc7SToomas Soome 
3728c65ebfc7SToomas Soome                 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3729c65ebfc7SToomas Soome                        q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3730c65ebfc7SToomas Soome 
3731c65ebfc7SToomas Soome                 if (q->ThisQInterval > MaxQuestionInterval)
3732c65ebfc7SToomas Soome                 {
3733c65ebfc7SToomas Soome                     q->ThisQInterval = MaxQuestionInterval;
3734c65ebfc7SToomas Soome                 }
37353b436d06SToomas Soome                 else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID &&
37363b436d06SToomas Soome                          q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3737c65ebfc7SToomas Soome                          !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3738c65ebfc7SToomas Soome                 {
3739c65ebfc7SToomas Soome                     // Generally don't need to log this.
3740c65ebfc7SToomas Soome                     // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3741c65ebfc7SToomas Soome                     // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3742c65ebfc7SToomas Soome                     // and when there simply happen to be no instances of the service the client is looking
3743c65ebfc7SToomas Soome                     // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3744c65ebfc7SToomas Soome                     debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3745c65ebfc7SToomas Soome                            q->qname.c, DNSTypeName(q->qtype));
3746c65ebfc7SToomas Soome                     // Sending third query, and no answers yet; time to begin doubting the source
37473b436d06SToomas Soome                     ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0);
3748c65ebfc7SToomas Soome                 }
3749c65ebfc7SToomas Soome             }
3750c65ebfc7SToomas Soome 
3751c65ebfc7SToomas Soome             // Mark for sending. (If no active interfaces, then don't even try.)
3752c65ebfc7SToomas Soome             q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3753c65ebfc7SToomas Soome             if (q->SendOnAll)
3754c65ebfc7SToomas Soome             {
3755c65ebfc7SToomas Soome                 q->SendQNow  = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3756c65ebfc7SToomas Soome                 q->LastQTime = m->timenow;
3757c65ebfc7SToomas Soome             }
3758c65ebfc7SToomas Soome 
3759c65ebfc7SToomas Soome             // If we recorded a duplicate suppression for this question less than half an interval ago,
3760c65ebfc7SToomas Soome             // then we consider it recent enough that we don't need to do an identical query ourselves.
3761c65ebfc7SToomas Soome             ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3762c65ebfc7SToomas Soome 
3763c65ebfc7SToomas Soome             q->LastQTxTime      = m->timenow;
3764c65ebfc7SToomas Soome             q->RecentAnswerPkts = 0;
3765c65ebfc7SToomas Soome             if (q->RequestUnicast) q->RequestUnicast--;
3766c65ebfc7SToomas Soome         }
3767c65ebfc7SToomas Soome         // For all questions (not just the ones we're sending) check what the next scheduled event will be
3768c65ebfc7SToomas Soome         // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3769c65ebfc7SToomas Soome         SetNextQueryTime(m,q);
3770c65ebfc7SToomas Soome     }
3771c65ebfc7SToomas Soome 
3772c65ebfc7SToomas Soome     // 2. Scan our authoritative RR list to see what probes we might need to send
3773c65ebfc7SToomas Soome 
3774c65ebfc7SToomas Soome     m->NextScheduledProbe = m->timenow + FutureTime;
3775c65ebfc7SToomas Soome 
3776c65ebfc7SToomas Soome     if (m->CurrentRecord)
3777c65ebfc7SToomas Soome         LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3778c65ebfc7SToomas Soome     m->CurrentRecord = m->ResourceRecords;
3779c65ebfc7SToomas Soome     while (m->CurrentRecord)
3780c65ebfc7SToomas Soome     {
3781c65ebfc7SToomas Soome         ar = m->CurrentRecord;
3782c65ebfc7SToomas Soome         m->CurrentRecord = ar->next;
3783c65ebfc7SToomas Soome         if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique)  // For all records that are still probing...
3784c65ebfc7SToomas Soome         {
3785c65ebfc7SToomas Soome             // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3786c65ebfc7SToomas Soome             if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3787c65ebfc7SToomas Soome             {
3788c65ebfc7SToomas Soome                 SetNextAnnounceProbeTime(m, ar);
3789c65ebfc7SToomas Soome             }
3790c65ebfc7SToomas Soome             // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3791c65ebfc7SToomas Soome             else if (ar->ProbeCount)
3792c65ebfc7SToomas Soome             {
3793c65ebfc7SToomas Soome                 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3794c65ebfc7SToomas Soome                 {
3795c65ebfc7SToomas Soome                     // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3796c65ebfc7SToomas Soome                     // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3797c65ebfc7SToomas Soome                     // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3798c65ebfc7SToomas Soome                     // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3799c65ebfc7SToomas Soome                     // A similar concern may apply to the NDP Probe too. -- SC
3800c65ebfc7SToomas Soome                     LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3801c65ebfc7SToomas Soome                     SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3802c65ebfc7SToomas Soome                 }
3803c65ebfc7SToomas Soome                 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3804c65ebfc7SToomas Soome                 {
3805c65ebfc7SToomas Soome                     LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3806c65ebfc7SToomas Soome                     // IPv6 source = zero
3807c65ebfc7SToomas Soome                     // No target hardware address
3808c65ebfc7SToomas Soome                     // IPv6 target address is address we're probing
3809c65ebfc7SToomas Soome                     // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3810c65ebfc7SToomas Soome                     SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3811c65ebfc7SToomas Soome                 }
3812c65ebfc7SToomas Soome                 // Mark for sending. (If no active interfaces, then don't even try.)
3813c65ebfc7SToomas Soome                 ar->SendRNow   = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3814c65ebfc7SToomas Soome                 ar->LastAPTime = m->timenow;
3815c65ebfc7SToomas Soome                 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3816c65ebfc7SToomas Soome                 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3817c65ebfc7SToomas Soome                 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3818c65ebfc7SToomas Soome                     ar->ProbeCount = DefaultProbeCountForTypeUnique;
3819c65ebfc7SToomas Soome                 ar->ProbeCount--;
3820c65ebfc7SToomas Soome                 SetNextAnnounceProbeTime(m, ar);
3821c65ebfc7SToomas Soome                 if (ar->ProbeCount == 0)
3822c65ebfc7SToomas Soome                 {
3823c65ebfc7SToomas Soome                     // If this is the last probe for this record, then see if we have any matching records
3824c65ebfc7SToomas Soome                     // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3825c65ebfc7SToomas Soome                     AuthRecord *r2;
3826c65ebfc7SToomas Soome                     for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3827c65ebfc7SToomas Soome                         if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3828c65ebfc7SToomas Soome                             r2->ProbeCount = 0;
3829c65ebfc7SToomas Soome                     // ... then acknowledge this record to the client.
3830c65ebfc7SToomas Soome                     // We do this optimistically, just as we're about to send the third probe.
3831c65ebfc7SToomas Soome                     // This helps clients that both advertise and browse, and want to filter themselves
3832c65ebfc7SToomas Soome                     // from the browse results list, because it helps ensure that the registration
3833c65ebfc7SToomas Soome                     // confirmation will be delivered 1/4 second *before* the browse "add" event.
3834c65ebfc7SToomas Soome                     // A potential downside is that we could deliver a registration confirmation and then find out
3835c65ebfc7SToomas Soome                     // moments later that there's a name conflict, but applications have to be prepared to handle
3836c65ebfc7SToomas Soome                     // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3837c65ebfc7SToomas Soome                     if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3838c65ebfc7SToomas Soome                 }
3839c65ebfc7SToomas Soome             }
3840c65ebfc7SToomas Soome             // else, if it has now finished probing, move it to state Verified,
3841c65ebfc7SToomas Soome             // and update m->NextScheduledResponse so it will be announced
3842c65ebfc7SToomas Soome             else
3843c65ebfc7SToomas Soome             {
3844c65ebfc7SToomas Soome                 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);    // Defensive, just in case it got missed somehow
3845c65ebfc7SToomas Soome                 ar->resrec.RecordType     = kDNSRecordTypeVerified;
3846c65ebfc7SToomas Soome                 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3847c65ebfc7SToomas Soome                 ar->LastAPTime     = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3848c65ebfc7SToomas Soome                 SetNextAnnounceProbeTime(m, ar);
3849c65ebfc7SToomas Soome             }
3850c65ebfc7SToomas Soome         }
3851c65ebfc7SToomas Soome     }
3852c65ebfc7SToomas Soome     m->CurrentRecord = m->DuplicateRecords;
3853c65ebfc7SToomas Soome     while (m->CurrentRecord)
3854c65ebfc7SToomas Soome     {
3855c65ebfc7SToomas Soome         ar = m->CurrentRecord;
3856c65ebfc7SToomas Soome         m->CurrentRecord = ar->next;
3857c65ebfc7SToomas Soome         if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3858c65ebfc7SToomas Soome             AcknowledgeRecord(m, ar);
3859c65ebfc7SToomas Soome     }
3860c65ebfc7SToomas Soome 
3861c65ebfc7SToomas Soome     // 3. Now we know which queries and probes we're sending,
3862c65ebfc7SToomas Soome     // go through our interface list sending the appropriate queries on each interface
3863c65ebfc7SToomas Soome     while (intf)
3864c65ebfc7SToomas Soome     {
3865c65ebfc7SToomas Soome         int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3866c65ebfc7SToomas Soome         int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3867c65ebfc7SToomas Soome         mDNSu8 *queryptr = m->omsg.data;
3868c65ebfc7SToomas Soome         mDNSBool useBackgroundTrafficClass = mDNSfalse;    // set if we should use background traffic class
3869c65ebfc7SToomas Soome 
3870c65ebfc7SToomas Soome         InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3871c65ebfc7SToomas Soome         if (KnownAnswerList) verbosedebugf("SendQueries:   KnownAnswerList set... Will continue from previous packet");
3872c65ebfc7SToomas Soome         if (!KnownAnswerList)
3873c65ebfc7SToomas Soome         {
3874c65ebfc7SToomas Soome             // Start a new known-answer list
3875c65ebfc7SToomas Soome             CacheRecord **kalistptr = &KnownAnswerList;
3876c65ebfc7SToomas Soome             mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace;  // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3877c65ebfc7SToomas Soome 
3878c65ebfc7SToomas Soome             // Put query questions in this packet
3879c65ebfc7SToomas Soome             for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3880c65ebfc7SToomas Soome             {
3881c65ebfc7SToomas Soome                 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3882c65ebfc7SToomas Soome                 {
3883c65ebfc7SToomas Soome                     mDNSBool Suppress = mDNSfalse;
3884c65ebfc7SToomas Soome                     debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3885c65ebfc7SToomas Soome                            SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting    ",
3886c65ebfc7SToomas Soome                            q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3887c65ebfc7SToomas Soome 
3888c65ebfc7SToomas Soome                     // If interface is P2P type, verify that query should be sent over it.
3889c65ebfc7SToomas Soome                     if (!mDNSPlatformValidQuestionForInterface(q, intf))
3890c65ebfc7SToomas Soome                     {
3891c65ebfc7SToomas Soome                         q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3892c65ebfc7SToomas Soome                     }
3893c65ebfc7SToomas Soome                     // If we're suppressing this question, or we successfully put it, update its SendQNow state
3894c65ebfc7SToomas Soome                     else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3895c65ebfc7SToomas Soome                         BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3896c65ebfc7SToomas Soome                     {
3897c65ebfc7SToomas Soome                         if (Suppress)
3898c65ebfc7SToomas Soome                             m->mDNSStats.DupQuerySuppressions++;
3899c65ebfc7SToomas Soome 
3900c65ebfc7SToomas Soome                         q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3901c65ebfc7SToomas Soome                         if (q->WakeOnResolveCount)
3902c65ebfc7SToomas Soome                         {
3903c65ebfc7SToomas Soome                             mDNSSendWakeOnResolve(m, q);
3904c65ebfc7SToomas Soome                             q->WakeOnResolveCount--;
3905c65ebfc7SToomas Soome                         }
3906c65ebfc7SToomas Soome 
3907c65ebfc7SToomas Soome                         // use background traffic class if any included question requires it
3908*472cd20dSToomas Soome                         if (q->UseBackgroundTraffic)
3909c65ebfc7SToomas Soome                         {
3910c65ebfc7SToomas Soome                             useBackgroundTrafficClass = mDNStrue;
3911c65ebfc7SToomas Soome                         }
3912c65ebfc7SToomas Soome                     }
3913c65ebfc7SToomas Soome                 }
3914c65ebfc7SToomas Soome             }
3915c65ebfc7SToomas Soome 
3916c65ebfc7SToomas Soome             // Put probe questions in this packet
3917c65ebfc7SToomas Soome             for (ar = m->ResourceRecords; ar; ar=ar->next)
3918c65ebfc7SToomas Soome             {
3919c65ebfc7SToomas Soome                 if (ar->SendRNow != intf->InterfaceID)
3920c65ebfc7SToomas Soome                     continue;
3921c65ebfc7SToomas Soome 
3922c65ebfc7SToomas Soome                 // If interface is a P2P variant, verify that the probe should be sent over it.
3923c65ebfc7SToomas Soome                 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID))
3924c65ebfc7SToomas Soome                 {
3925c65ebfc7SToomas Soome                     ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3926c65ebfc7SToomas Soome                     ar->IncludeInProbe = mDNSfalse;
3927c65ebfc7SToomas Soome                 }
3928c65ebfc7SToomas Soome                 else
3929c65ebfc7SToomas Soome                 {
3930c65ebfc7SToomas Soome                     mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3931c65ebfc7SToomas Soome                     mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3932c65ebfc7SToomas Soome                     const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3933c65ebfc7SToomas Soome                     // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3934c65ebfc7SToomas Soome                     mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3935c65ebfc7SToomas Soome                     mDNSBool putProbe = mDNStrue;
3936c65ebfc7SToomas Soome                     mDNSu16 qclass = ar->resrec.rrclass | ucbit;
3937c65ebfc7SToomas Soome 
3938c65ebfc7SToomas Soome                     {// Determine if this probe question is already in packet's dns message
3939c65ebfc7SToomas Soome                         const mDNSu8 *questionptr = m->omsg.data;
3940c65ebfc7SToomas Soome                         DNSQuestion question;
3941c65ebfc7SToomas Soome                         mDNSu16 n;
3942c65ebfc7SToomas Soome                         for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++)
3943c65ebfc7SToomas Soome                         {
3944c65ebfc7SToomas Soome                             questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question);
3945c65ebfc7SToomas Soome                             if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) &&
3946c65ebfc7SToomas Soome                                 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name))
3947c65ebfc7SToomas Soome                             {
3948c65ebfc7SToomas Soome                                 putProbe = mDNSfalse;  // set to false if already in message
3949c65ebfc7SToomas Soome                                 break;
3950c65ebfc7SToomas Soome                             }
3951c65ebfc7SToomas Soome                         }
3952c65ebfc7SToomas Soome                     }
3953c65ebfc7SToomas Soome 
3954c65ebfc7SToomas Soome                     if (putProbe)
3955c65ebfc7SToomas Soome                     {
3956c65ebfc7SToomas Soome                         mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass);
3957c65ebfc7SToomas Soome                         if (newptr)
3958c65ebfc7SToomas Soome                         {
3959c65ebfc7SToomas Soome                             queryptr       = newptr;
3960c65ebfc7SToomas Soome                             answerforecast = forecast;
3961c65ebfc7SToomas Soome                             ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3962c65ebfc7SToomas Soome                             ar->IncludeInProbe = mDNStrue;
3963c65ebfc7SToomas Soome                             verbosedebugf("SendQueries:   Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3964c65ebfc7SToomas Soome                                       ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast);
3965c65ebfc7SToomas Soome                         }
3966c65ebfc7SToomas Soome                     }
3967c65ebfc7SToomas Soome                     else
3968c65ebfc7SToomas Soome                     {
3969c65ebfc7SToomas Soome                         ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3970c65ebfc7SToomas Soome                         ar->IncludeInProbe = mDNStrue;
3971c65ebfc7SToomas Soome                     }
3972c65ebfc7SToomas Soome                 }
3973c65ebfc7SToomas Soome             }
3974c65ebfc7SToomas Soome         }
3975c65ebfc7SToomas Soome 
3976c65ebfc7SToomas Soome         // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3977c65ebfc7SToomas Soome         while (KnownAnswerList)
3978c65ebfc7SToomas Soome         {
3979c65ebfc7SToomas Soome             CacheRecord *ka = KnownAnswerList;
3980c65ebfc7SToomas Soome             mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3981c65ebfc7SToomas Soome             mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3982c65ebfc7SToomas Soome                                                            m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3983c65ebfc7SToomas Soome             if (newptr)
3984c65ebfc7SToomas Soome             {
3985c65ebfc7SToomas Soome                 verbosedebugf("SendQueries:   Put %##s (%s) at %d - %d",
3986c65ebfc7SToomas Soome                               ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3987c65ebfc7SToomas Soome                 queryptr = newptr;
3988c65ebfc7SToomas Soome                 KnownAnswerList = ka->NextInKAList;
3989c65ebfc7SToomas Soome                 ka->NextInKAList = mDNSNULL;
3990c65ebfc7SToomas Soome             }
3991c65ebfc7SToomas Soome             else
3992c65ebfc7SToomas Soome             {
3993c65ebfc7SToomas Soome                 // If we ran out of space and we have more than one question in the packet, that's an error --
3994c65ebfc7SToomas Soome                 // we shouldn't have put more than one question if there was a risk of us running out of space.
3995c65ebfc7SToomas Soome                 if (m->omsg.h.numQuestions > 1)
3996c65ebfc7SToomas Soome                     LogMsg("SendQueries:   Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3997c65ebfc7SToomas Soome                 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3998c65ebfc7SToomas Soome                 break;
3999c65ebfc7SToomas Soome             }
4000c65ebfc7SToomas Soome         }
4001c65ebfc7SToomas Soome 
4002c65ebfc7SToomas Soome         for (ar = m->ResourceRecords; ar; ar=ar->next)
4003c65ebfc7SToomas Soome         {
4004c65ebfc7SToomas Soome             if (ar->IncludeInProbe)
4005c65ebfc7SToomas Soome             {
4006c65ebfc7SToomas Soome                 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
4007c65ebfc7SToomas Soome                 ar->IncludeInProbe = mDNSfalse;
4008c65ebfc7SToomas Soome                 if (newptr) queryptr = newptr;
4009c65ebfc7SToomas Soome                 else LogMsg("SendQueries:   How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
4010c65ebfc7SToomas Soome             }
4011c65ebfc7SToomas Soome         }
4012c65ebfc7SToomas Soome 
4013c65ebfc7SToomas Soome         if (queryptr > m->omsg.data)
4014c65ebfc7SToomas Soome         {
4015c65ebfc7SToomas Soome             // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
4016c65ebfc7SToomas Soome             if (OwnerRecordSpace || TraceRecordSpace)
4017c65ebfc7SToomas Soome             {
4018c65ebfc7SToomas Soome                 AuthRecord opt;
4019c65ebfc7SToomas Soome                 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
4020c65ebfc7SToomas Soome                 opt.resrec.rrclass    = NormalMaxDNSMessageData;
4021c65ebfc7SToomas Soome                 opt.resrec.rdlength   = sizeof(rdataOPT);
4022c65ebfc7SToomas Soome                 opt.resrec.rdestimate = sizeof(rdataOPT);
4023c65ebfc7SToomas Soome                 if (OwnerRecordSpace && TraceRecordSpace)
4024c65ebfc7SToomas Soome                 {
4025c65ebfc7SToomas Soome                     opt.resrec.rdlength   += sizeof(rdataOPT);  // Two options in this OPT record
4026c65ebfc7SToomas Soome                     opt.resrec.rdestimate += sizeof(rdataOPT);
4027c65ebfc7SToomas Soome                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4028c65ebfc7SToomas Soome                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
4029c65ebfc7SToomas Soome                 }
4030c65ebfc7SToomas Soome                 else if (OwnerRecordSpace)
4031c65ebfc7SToomas Soome                 {
4032c65ebfc7SToomas Soome                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4033c65ebfc7SToomas Soome                 }
4034c65ebfc7SToomas Soome                 else if (TraceRecordSpace)
4035c65ebfc7SToomas Soome                 {
4036c65ebfc7SToomas Soome                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
4037c65ebfc7SToomas Soome                 }
4038c65ebfc7SToomas Soome                 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
4039c65ebfc7SToomas Soome                                                          &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4040c65ebfc7SToomas Soome                 if (!queryptr)
4041c65ebfc7SToomas Soome                 {
4042c65ebfc7SToomas Soome                     LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
4043c65ebfc7SToomas Soome                            m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4044c65ebfc7SToomas Soome                 }
4045c65ebfc7SToomas Soome                 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
4046c65ebfc7SToomas Soome                 {
4047c65ebfc7SToomas Soome                     if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
4048c65ebfc7SToomas Soome                         LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
4049c65ebfc7SToomas Soome                                 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
4050c65ebfc7SToomas Soome                                 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4051c65ebfc7SToomas Soome                 }
4052c65ebfc7SToomas Soome             }
4053c65ebfc7SToomas Soome 
4054c65ebfc7SToomas Soome             if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
4055c65ebfc7SToomas Soome                 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
4056*472cd20dSToomas Soome             debugf("SendQueries:   Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4057c65ebfc7SToomas Soome                    m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
4058c65ebfc7SToomas Soome                    m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
4059*472cd20dSToomas Soome                    m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", IIDPrintable(intf->InterfaceID), intf->ifname);
4060*472cd20dSToomas Soome             if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4061*472cd20dSToomas Soome             if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4062c65ebfc7SToomas Soome             if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
4063c65ebfc7SToomas Soome             if (++pktcount >= 1000)
4064c65ebfc7SToomas Soome             { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
4065c65ebfc7SToomas Soome             // There might be more records left in the known answer list, or more questions to send
4066c65ebfc7SToomas Soome             // on this interface, so go around one more time and try again.
4067c65ebfc7SToomas Soome         }
4068c65ebfc7SToomas Soome         else    // Nothing more to send on this interface; go to next
4069c65ebfc7SToomas Soome         {
4070c65ebfc7SToomas Soome             const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
4071c65ebfc7SToomas Soome             #if MDNS_DEBUGMSGS && 0
4072c65ebfc7SToomas Soome             const char *const msg = next ? "SendQueries:   Nothing more on %p; moving to %p" : "SendQueries:   Nothing more on %p";
4073c65ebfc7SToomas Soome             debugf(msg, intf, next);
4074c65ebfc7SToomas Soome             #endif
4075c65ebfc7SToomas Soome             intf = next;
4076c65ebfc7SToomas Soome         }
4077c65ebfc7SToomas Soome     }
4078c65ebfc7SToomas Soome 
4079c65ebfc7SToomas Soome     // 4. Final housekeeping
4080c65ebfc7SToomas Soome 
4081c65ebfc7SToomas Soome     // 4a. Debugging check: Make sure we announced all our records
4082c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar; ar=ar->next)
4083c65ebfc7SToomas Soome         if (ar->SendRNow)
4084c65ebfc7SToomas Soome         {
4085c65ebfc7SToomas Soome             if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
4086c65ebfc7SToomas Soome                 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4087*472cd20dSToomas Soome                         IIDPrintable(ar->SendRNow), IIDPrintable(ar->resrec.InterfaceID), ARDisplayString(m, ar));
4088c65ebfc7SToomas Soome             ar->SendRNow = mDNSNULL;
4089c65ebfc7SToomas Soome         }
4090c65ebfc7SToomas Soome 
4091c65ebfc7SToomas Soome     // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4092c65ebfc7SToomas Soome     // that their interface which went away might come back again, the logic will want to send queries
4093c65ebfc7SToomas Soome     // for those records, but we can't because their interface isn't here any more, so to keep the
4094c65ebfc7SToomas Soome     // state machine ticking over we just pretend we did so.
4095c65ebfc7SToomas Soome     // If the interface does not come back in time, the cache record will expire naturally
4096c65ebfc7SToomas Soome     FORALL_CACHERECORDS(slot, cg, cr)
4097c65ebfc7SToomas Soome     {
4098c65ebfc7SToomas Soome         if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
4099c65ebfc7SToomas Soome         {
4100c65ebfc7SToomas Soome             if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
4101c65ebfc7SToomas Soome             {
4102c65ebfc7SToomas Soome                 cr->UnansweredQueries++;
4103c65ebfc7SToomas Soome                 cr->CRActiveQuestion->SendQNow = mDNSNULL;
4104c65ebfc7SToomas Soome                 SetNextCacheCheckTimeForRecord(m, cr);
4105c65ebfc7SToomas Soome             }
4106c65ebfc7SToomas Soome         }
4107c65ebfc7SToomas Soome     }
4108c65ebfc7SToomas Soome 
4109c65ebfc7SToomas Soome     // 4c. Debugging check: Make sure we sent all our planned questions
4110c65ebfc7SToomas Soome     // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4111c65ebfc7SToomas Soome     // we legitimately couldn't send because the interface is no longer available
4112c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next)
4113c65ebfc7SToomas Soome     {
4114c65ebfc7SToomas Soome         if (q->SendQNow)
4115c65ebfc7SToomas Soome         {
4116c65ebfc7SToomas Soome             DNSQuestion *x;
4117c65ebfc7SToomas Soome             for (x = m->NewQuestions; x; x=x->next) if (x == q) break;  // Check if this question is a NewQuestion
4118c65ebfc7SToomas Soome             // There will not be an active interface for questions applied to mDNSInterface_BLE
4119c65ebfc7SToomas Soome             // so don't log the warning in that case.
4120c65ebfc7SToomas Soome             if (q->InterfaceID != mDNSInterface_BLE)
4121c65ebfc7SToomas Soome                 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4122*472cd20dSToomas Soome                         IIDPrintable(q->SendQNow), x ? "new" : "old", IIDPrintable(q->InterfaceID), q->qname.c, DNSTypeName(q->qtype));
4123c65ebfc7SToomas Soome             q->SendQNow = mDNSNULL;
4124c65ebfc7SToomas Soome         }
4125c65ebfc7SToomas Soome         q->CachedAnswerNeedsUpdate = mDNSfalse;
4126c65ebfc7SToomas Soome     }
4127c65ebfc7SToomas Soome }
4128c65ebfc7SToomas Soome 
SendWakeup(mDNS * const m,mDNSInterfaceID InterfaceID,mDNSEthAddr * EthAddr,mDNSOpaque48 * password,mDNSBool unicastOnly)4129c65ebfc7SToomas Soome mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly)
4130c65ebfc7SToomas Soome {
4131c65ebfc7SToomas Soome     int i, j;
4132c65ebfc7SToomas Soome 
4133c65ebfc7SToomas Soome     mDNSu8 *ptr = m->omsg.data;
4134c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
4135c65ebfc7SToomas Soome     if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
4136c65ebfc7SToomas Soome 
4137c65ebfc7SToomas Soome     // 0x00 Destination address
4138c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4139c65ebfc7SToomas Soome 
4140c65ebfc7SToomas Soome     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4141c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
4142c65ebfc7SToomas Soome 
4143c65ebfc7SToomas Soome     // 0x0C Ethertype (0x0842)
4144c65ebfc7SToomas Soome     *ptr++ = 0x08;
4145c65ebfc7SToomas Soome     *ptr++ = 0x42;
4146c65ebfc7SToomas Soome 
4147c65ebfc7SToomas Soome     // 0x0E Wakeup sync sequence
4148c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = 0xFF;
4149c65ebfc7SToomas Soome 
4150c65ebfc7SToomas Soome     // 0x14 Wakeup data
4151c65ebfc7SToomas Soome     for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4152c65ebfc7SToomas Soome 
4153c65ebfc7SToomas Soome     // 0x74 Password
4154c65ebfc7SToomas Soome     for (i=0; i<6; i++) *ptr++ = password->b[i];
4155c65ebfc7SToomas Soome 
4156c65ebfc7SToomas Soome     mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4157c65ebfc7SToomas Soome 
4158c65ebfc7SToomas Soome     if (!unicastOnly)
4159c65ebfc7SToomas Soome     {
4160c65ebfc7SToomas Soome         // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4161c65ebfc7SToomas Soome         // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4162c65ebfc7SToomas Soome         // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4163c65ebfc7SToomas Soome         // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4164c65ebfc7SToomas Soome         // So, we send one of each, unicast first, then broadcast second.
4165c65ebfc7SToomas Soome         for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
4166c65ebfc7SToomas Soome         mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4167c65ebfc7SToomas Soome     }
4168c65ebfc7SToomas Soome }
4169c65ebfc7SToomas Soome 
4170c65ebfc7SToomas Soome // ***************************************************************************
4171c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
4172c65ebfc7SToomas Soome #pragma mark -
4173c65ebfc7SToomas Soome #pragma mark - RR List Management & Task Management
4174c65ebfc7SToomas Soome #endif
4175c65ebfc7SToomas Soome 
4176c65ebfc7SToomas Soome // Whenever a question is answered, reset its state so that we don't query
4177c65ebfc7SToomas Soome // the network repeatedly. This happens first time when we answer the question and
4178c65ebfc7SToomas Soome // and later when we refresh the cache.
ResetQuestionState(mDNS * const m,DNSQuestion * q)4179c65ebfc7SToomas Soome mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
4180c65ebfc7SToomas Soome {
4181c65ebfc7SToomas Soome     q->LastQTime        = m->timenow;
4182c65ebfc7SToomas Soome     q->LastQTxTime      = m->timenow;
4183c65ebfc7SToomas Soome     q->RecentAnswerPkts = 0;
4184c65ebfc7SToomas Soome     q->ThisQInterval    = MaxQuestionInterval;
4185c65ebfc7SToomas Soome     q->RequestUnicast   = 0;
4186*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4187c65ebfc7SToomas Soome     // Reset unansweredQueries so that we don't penalize this server later when we
4188c65ebfc7SToomas Soome     // start sending queries when the cache expires.
4189c65ebfc7SToomas Soome     q->unansweredQueries = 0;
4190*472cd20dSToomas Soome #endif
4191c65ebfc7SToomas Soome     debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4192c65ebfc7SToomas Soome }
4193c65ebfc7SToomas Soome 
AdjustUnansweredQueries(mDNS * const m,CacheRecord * const rr)4194*472cd20dSToomas Soome mDNSlocal void AdjustUnansweredQueries(mDNS *const m, CacheRecord *const rr)
4195*472cd20dSToomas Soome {
4196*472cd20dSToomas Soome     const mDNSs32 expireTime = RRExpireTime(rr);
4197*472cd20dSToomas Soome     const mDNSu32 interval = TicksTTL(rr) / 20; // Calculate 5% of the cache record's TTL.
4198*472cd20dSToomas Soome     mDNSu32 rem;
4199*472cd20dSToomas Soome 
4200*472cd20dSToomas Soome     // If the record is expired or UnansweredQueries is already at the max, then return early.
4201*472cd20dSToomas Soome     if (((m->timenow - expireTime) >= 0) || (rr->UnansweredQueries >= MaxUnansweredQueries)) return;
4202*472cd20dSToomas Soome 
4203*472cd20dSToomas Soome     if (interval == 0)
4204*472cd20dSToomas Soome     {
4205*472cd20dSToomas Soome         LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr), CRDisplayString(m, rr));
4206*472cd20dSToomas Soome         return;
4207*472cd20dSToomas Soome     }
4208*472cd20dSToomas Soome 
4209*472cd20dSToomas Soome     // Calculate the number of whole 5% TTL intervals between now and expiration time.
4210*472cd20dSToomas Soome     rem = ((mDNSu32)(expireTime - m->timenow)) / interval;
4211*472cd20dSToomas Soome 
4212*472cd20dSToomas Soome     // Calculate the expected number of remaining refresher queries.
4213*472cd20dSToomas Soome     // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4214*472cd20dSToomas Soome     if (rem > MaxUnansweredQueries) rem = MaxUnansweredQueries;
4215*472cd20dSToomas Soome 
4216*472cd20dSToomas Soome     // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4217*472cd20dSToomas Soome     // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4218*472cd20dSToomas Soome     // refresher queries would have been sent if the cache record did have an active question. The cache record's
4219*472cd20dSToomas Soome     // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4220*472cd20dSToomas Soome     // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4221*472cd20dSToomas Soome     // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4222*472cd20dSToomas Soome     // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4223*472cd20dSToomas Soome     // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4224*472cd20dSToomas Soome 	// Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4225*472cd20dSToomas Soome     if ((MaxUnansweredQueries - rr->UnansweredQueries) > (mDNSs32)rem)
4226*472cd20dSToomas Soome     {
4227*472cd20dSToomas Soome         if (rem == 0) rem++;
4228*472cd20dSToomas Soome         rr->UnansweredQueries = (mDNSu8)(MaxUnansweredQueries - rem);
4229*472cd20dSToomas Soome     }
4230*472cd20dSToomas Soome }
4231*472cd20dSToomas Soome 
4232c65ebfc7SToomas Soome // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4233c65ebfc7SToomas Soome // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4234c65ebfc7SToomas Soome // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4235c65ebfc7SToomas Soome // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
AnswerCurrentQuestionWithResourceRecord(mDNS * const m,CacheRecord * const rr,const QC_result AddRecord)4236c65ebfc7SToomas Soome mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
4237c65ebfc7SToomas Soome {
4238c65ebfc7SToomas Soome     DNSQuestion *const q = m->CurrentQuestion;
4239c65ebfc7SToomas Soome     const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
4240c65ebfc7SToomas Soome 
42413b436d06SToomas Soome     verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
42423b436d06SToomas Soome                   q->CurrentAnswers, AddRecord ? "Add" : "Rmv", MortalityDisplayString(rr->resrec.mortality),
42433b436d06SToomas Soome                   rr->resrec.rroriginalttl, CRDisplayString(m, rr));
4244c65ebfc7SToomas Soome 
4245c65ebfc7SToomas Soome     // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4246c65ebfc7SToomas Soome     // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4247c65ebfc7SToomas Soome     // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4248c65ebfc7SToomas Soome     // we check to see if that query already has a unique local answer.
4249c65ebfc7SToomas Soome     if (q->LOAddressAnswers)
4250c65ebfc7SToomas Soome     {
4251c65ebfc7SToomas Soome         LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4252c65ebfc7SToomas Soome                 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
4253c65ebfc7SToomas Soome                 q->LOAddressAnswers);
4254c65ebfc7SToomas Soome         return;
4255c65ebfc7SToomas Soome     }
4256c65ebfc7SToomas Soome 
4257*472cd20dSToomas Soome     if (q->Suppressed && (AddRecord != QC_suppressed))
4258c65ebfc7SToomas Soome     {
4259c65ebfc7SToomas Soome         // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4260c65ebfc7SToomas Soome         // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4261c65ebfc7SToomas Soome         // that are timing out, which we know are answered with negative cache record when timing out.
4262c65ebfc7SToomas Soome         if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
4263c65ebfc7SToomas Soome             return;
4264c65ebfc7SToomas Soome     }
4265c65ebfc7SToomas Soome 
42663b436d06SToomas Soome     //  Set the record to immortal if appropriate
42673b436d06SToomas Soome     if (AddRecord == QC_add && Question_uDNS(q) && rr->resrec.RecordType != kDNSRecordTypePacketNegative &&
42683b436d06SToomas Soome         q->allowExpired != AllowExpired_None && rr->resrec.mortality == Mortality_Mortal ) rr->resrec.mortality = Mortality_Immortal; // Update a non-expired cache record to immortal if appropriate
42693b436d06SToomas Soome 
4270*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4271*472cd20dSToomas Soome     if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname && !q->metrics.answered)
4272*472cd20dSToomas Soome     {
4273*472cd20dSToomas Soome         mDNSBool skipUpdate = mDNSfalse;
4274*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4275*472cd20dSToomas Soome         if (!q->dnsservice || (mdns_dns_service_get_resolver_type(q->dnsservice) != mdns_resolver_type_normal))
4276*472cd20dSToomas Soome         {
4277*472cd20dSToomas Soome             skipUpdate = mDNStrue;
4278*472cd20dSToomas Soome         }
4279*472cd20dSToomas Soome #endif
4280*472cd20dSToomas Soome         if (!skipUpdate)
4281c65ebfc7SToomas Soome         {
4282c65ebfc7SToomas Soome             const domainname *  queryName;
4283*472cd20dSToomas Soome             mDNSu32             responseLatencyMs, querySendCount;
4284c65ebfc7SToomas Soome             mDNSBool            isForCellular;
4285c65ebfc7SToomas Soome 
4286c65ebfc7SToomas Soome             queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname;
4287*472cd20dSToomas Soome             querySendCount = q->metrics.querySendCount;
4288*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4289*472cd20dSToomas Soome             if (q->querier)
4290c65ebfc7SToomas Soome             {
4291*472cd20dSToomas Soome                 querySendCount += mdns_querier_get_send_count(q->querier);
4292*472cd20dSToomas Soome             }
4293*472cd20dSToomas Soome             isForCellular = mdns_dns_service_interface_is_cellular(q->dnsservice);
4294*472cd20dSToomas Soome #else
4295*472cd20dSToomas Soome             isForCellular = (q->qDNSServer && q->qDNSServer->isCell);
4296*472cd20dSToomas Soome #endif
4297c65ebfc7SToomas Soome             if (q->metrics.querySendCount > 0)
4298c65ebfc7SToomas Soome             {
4299c65ebfc7SToomas Soome                 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
4300c65ebfc7SToomas Soome             }
4301c65ebfc7SToomas Soome             else
4302c65ebfc7SToomas Soome             {
4303c65ebfc7SToomas Soome                 responseLatencyMs = 0;
4304c65ebfc7SToomas Soome             }
4305*472cd20dSToomas Soome             MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, querySendCount, q->metrics.expiredAnswerState,
4306*472cd20dSToomas Soome                 q->metrics.dnsOverTCPState, responseLatencyMs, isForCellular);
4307*472cd20dSToomas Soome         }
4308c65ebfc7SToomas Soome         q->metrics.answered = mDNStrue;
4309c65ebfc7SToomas Soome     }
4310c65ebfc7SToomas Soome #endif
4311c65ebfc7SToomas Soome     // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4312c65ebfc7SToomas Soome     // may be called twice, once when the record is received, and again when it's time to notify local clients.
4313c65ebfc7SToomas Soome     // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4314c65ebfc7SToomas Soome 
43153b436d06SToomas Soome     if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost)
4316c65ebfc7SToomas Soome     {
4317c65ebfc7SToomas Soome         debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4318c65ebfc7SToomas Soome                rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
4319*472cd20dSToomas Soome         if (!rr->CRActiveQuestion)
4320*472cd20dSToomas Soome         {
4321*472cd20dSToomas Soome             m->rrcache_active++;            // If not previously active, increment rrcache_active count
4322*472cd20dSToomas Soome             AdjustUnansweredQueries(m, rr); // Adjust UnansweredQueries in case the record missed out on refresher queries
4323*472cd20dSToomas Soome         }
4324c65ebfc7SToomas Soome         rr->CRActiveQuestion = q;           // We know q is non-null
4325c65ebfc7SToomas Soome         SetNextCacheCheckTimeForRecord(m, rr);
4326c65ebfc7SToomas Soome     }
4327c65ebfc7SToomas Soome 
4328c65ebfc7SToomas Soome     // If this is:
4329c65ebfc7SToomas Soome     // (a) a no-cache add, where we've already done at least one 'QM' query, or
4330c65ebfc7SToomas Soome     // (b) a normal add, where we have at least one unique-type answer,
4331c65ebfc7SToomas Soome     // then there's no need to keep polling the network.
4332c65ebfc7SToomas Soome     // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4333c65ebfc7SToomas Soome     // We do this for mDNS questions and uDNS one-shot questions, but not for
4334c65ebfc7SToomas Soome     // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4335c65ebfc7SToomas Soome     if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
4336c65ebfc7SToomas Soome         (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
4337c65ebfc7SToomas Soome         if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4338c65ebfc7SToomas Soome         {
4339c65ebfc7SToomas Soome             ResetQuestionState(m, q);
4340c65ebfc7SToomas Soome         }
4341c65ebfc7SToomas Soome 
4342c65ebfc7SToomas Soome     if (rr->DelayDelivery) return;      // We'll come back later when CacheRecordDeferredAdd() calls us
4343c65ebfc7SToomas Soome 
4344*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4345c65ebfc7SToomas Soome     // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4346c65ebfc7SToomas Soome     if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return;
4347c65ebfc7SToomas Soome #endif
4348c65ebfc7SToomas Soome 
4349c65ebfc7SToomas Soome #ifdef USE_LIBIDN
4350c65ebfc7SToomas Soome     if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)  // If negative answer, check if we need to try Punycode conversion
4351c65ebfc7SToomas Soome     {
4352c65ebfc7SToomas Soome         domainname newname;
4353c65ebfc7SToomas Soome         if (PerformNextPunycodeConversion(q, &newname))         // Itertative Punycode conversion succeeded, so reissue question with new name
4354c65ebfc7SToomas Soome         {
4355c65ebfc7SToomas Soome             UDPSocket *const sock = q->LocalSocket;             // Save old socket and transaction ID
4356c65ebfc7SToomas Soome             const mDNSOpaque16 id = q->TargetQID;
4357c65ebfc7SToomas Soome             q->LocalSocket = mDNSNULL;
4358c65ebfc7SToomas Soome             mDNS_StopQuery_internal(m, q);                      // Stop old query
4359c65ebfc7SToomas Soome             AssignDomainName(&q->qname, &newname);              // Update qname
4360c65ebfc7SToomas Soome             q->qnamehash = DomainNameHashValue(&q->qname);      // and namehash
4361c65ebfc7SToomas Soome             mDNS_StartQuery_internal(m, q);                     // Start new query
4362c65ebfc7SToomas Soome 
4363c65ebfc7SToomas Soome             if (sock)                                           // Transplant saved socket, if appropriate
4364c65ebfc7SToomas Soome             {
4365c65ebfc7SToomas Soome                 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
4366c65ebfc7SToomas Soome                 else { q->LocalSocket = sock; q->TargetQID = id; }
4367c65ebfc7SToomas Soome             }
4368c65ebfc7SToomas Soome             return;                                             // All done for now; wait until we get the next answer
4369c65ebfc7SToomas Soome         }
4370c65ebfc7SToomas Soome     }
4371c65ebfc7SToomas Soome #endif // USE_LIBIDN
4372c65ebfc7SToomas Soome 
4373c65ebfc7SToomas Soome     // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4374c65ebfc7SToomas Soome     // for the purpose of retrying search domains/timeout OR the question is suppressed
4375c65ebfc7SToomas Soome     if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4376c65ebfc7SToomas Soome         if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4377c65ebfc7SToomas Soome 
4378c65ebfc7SToomas Soome     // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4379c65ebfc7SToomas Soome     if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4380c65ebfc7SToomas Soome     {
4381c65ebfc7SToomas Soome         mDNS_DropLockBeforeCallback();      // Allow client (and us) to legally make mDNS API calls
4382c65ebfc7SToomas Soome         if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4383c65ebfc7SToomas Soome         {
4384*472cd20dSToomas Soome             if (mDNSOpaque16IsZero(q->TargetQID))
4385*472cd20dSToomas Soome             {
4386c65ebfc7SToomas Soome                 CacheRecord neg;
4387*472cd20dSToomas Soome             #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4388*472cd20dSToomas Soome                 mDNSPlatformMemZero(&neg, sizeof(neg));
4389*472cd20dSToomas Soome                 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->dnsservice);
4390*472cd20dSToomas Soome             #else
4391c65ebfc7SToomas Soome                 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4392*472cd20dSToomas Soome             #endif
4393c65ebfc7SToomas Soome                 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4394c65ebfc7SToomas Soome             }
4395*472cd20dSToomas Soome         }
4396c65ebfc7SToomas Soome         else
4397c65ebfc7SToomas Soome         {
4398*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4399c65ebfc7SToomas Soome             if (DNS64ShouldAnswerQuestion(q, &rr->resrec))
4400c65ebfc7SToomas Soome             {
4401*472cd20dSToomas Soome                 DNS64AnswerCurrentQuestion(m, &rr->resrec, AddRecord);
4402c65ebfc7SToomas Soome             }
4403c65ebfc7SToomas Soome             else
4404c65ebfc7SToomas Soome #endif
4405c65ebfc7SToomas Soome             {
4406*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4407*472cd20dSToomas Soome                 get_denial_records_from_negative_cache_to_dnssec_context(q->DNSSECStatus.enable_dnssec,
4408*472cd20dSToomas Soome                     q->DNSSECStatus.context, rr);
4409*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4410c65ebfc7SToomas Soome                 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4411c65ebfc7SToomas Soome             }
4412c65ebfc7SToomas Soome         }
4413c65ebfc7SToomas Soome         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
4414c65ebfc7SToomas Soome     }
4415*472cd20dSToomas Soome     // Note: Proceed with caution after this point because client callback function
4416*472cd20dSToomas Soome     // invoked above is allowed to do anything, such as starting/stopping queries
4417*472cd20dSToomas Soome     // (including this one itself, or the next or previous query in the linked list),
4418*472cd20dSToomas Soome     // registering/deregistering records, starting/stopping NAT traversals, etc.
4419c65ebfc7SToomas Soome 
4420*472cd20dSToomas Soome     if (m->CurrentQuestion == q)
44213b436d06SToomas Soome     {
4422c65ebfc7SToomas Soome         // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4423c65ebfc7SToomas Soome         // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4424c65ebfc7SToomas Soome         // first before following it
44253b436d06SToomas Soome         if (followcname)  AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
44263b436d06SToomas Soome 
44273b436d06SToomas Soome         // If we are returning expired RRs, then remember the first expired qname we we can start the query again
44283b436d06SToomas Soome         if (rr->resrec.mortality == Mortality_Ghost && !q->firstExpiredQname.c[0] && (q->allowExpired == AllowExpired_AllowExpiredAnswers) && rr->resrec.RecordType != kDNSRecordTypePacketNegative)
44293b436d06SToomas Soome         {
44303b436d06SToomas Soome             debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m,rr), q);
44313b436d06SToomas Soome             // Note: question->qname is already changed at this point if following a CNAME
44323b436d06SToomas Soome             AssignDomainName(&q->firstExpiredQname, rr->resrec.name);           // Update firstExpiredQname
44333b436d06SToomas Soome         }
44343b436d06SToomas Soome     }
4435c65ebfc7SToomas Soome }
4436c65ebfc7SToomas Soome 
CacheRecordDeferredAdd(mDNS * const m,CacheRecord * cr)4437*472cd20dSToomas Soome mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *cr)
4438c65ebfc7SToomas Soome {
4439*472cd20dSToomas Soome     cr->DelayDelivery = 0;
4440c65ebfc7SToomas Soome     if (m->CurrentQuestion)
4441c65ebfc7SToomas Soome         LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4442c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4443c65ebfc7SToomas Soome     m->CurrentQuestion = m->Questions;
4444c65ebfc7SToomas Soome     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4445c65ebfc7SToomas Soome     {
4446c65ebfc7SToomas Soome         DNSQuestion *q = m->CurrentQuestion;
4447*472cd20dSToomas Soome         if (CacheRecordAnswersQuestion(cr, q))
4448*472cd20dSToomas Soome             AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4449c65ebfc7SToomas Soome         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4450c65ebfc7SToomas Soome             m->CurrentQuestion = q->next;
4451c65ebfc7SToomas Soome     }
4452c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
4453c65ebfc7SToomas Soome }
4454c65ebfc7SToomas Soome 
CheckForSoonToExpireRecords(mDNS * const m,const domainname * const name,const mDNSu32 namehash)44553b436d06SToomas Soome mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
4456c65ebfc7SToomas Soome {
44573b436d06SToomas Soome     const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond;  // See if there are any records expiring within one second
4458c65ebfc7SToomas Soome     const mDNSs32 start      = m->timenow - 0x10000000;
4459c65ebfc7SToomas Soome     mDNSs32 delay = start;
4460c65ebfc7SToomas Soome     CacheGroup *cg = CacheGroupForName(m, namehash, name);
4461c65ebfc7SToomas Soome     const CacheRecord *rr;
4462c65ebfc7SToomas Soome 
4463c65ebfc7SToomas Soome     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4464c65ebfc7SToomas Soome     {
44653b436d06SToomas Soome         if (threshold - RRExpireTime(rr) >= 0)     // If we have records about to expire within a second
4466c65ebfc7SToomas Soome         {
4467c65ebfc7SToomas Soome             if (delay - RRExpireTime(rr) < 0)       // then delay until after they've been deleted
4468c65ebfc7SToomas Soome                 delay = RRExpireTime(rr);
4469c65ebfc7SToomas Soome         }
4470c65ebfc7SToomas Soome     }
4471c65ebfc7SToomas Soome     if (delay - start > 0)
4472c65ebfc7SToomas Soome         return(NonZeroTime(delay));
4473c65ebfc7SToomas Soome     else
4474c65ebfc7SToomas Soome         return(0);
4475c65ebfc7SToomas Soome }
4476c65ebfc7SToomas Soome 
4477c65ebfc7SToomas Soome // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4478c65ebfc7SToomas Soome // If new questions are created as a result of invoking client callbacks, they will be added to
4479c65ebfc7SToomas Soome // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4480c65ebfc7SToomas Soome // rr is a new CacheRecord just received into our cache
4481c65ebfc7SToomas Soome // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4482c65ebfc7SToomas Soome // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4483c65ebfc7SToomas Soome // which may change the record list and/or question list.
4484c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
CacheRecordAdd(mDNS * const m,CacheRecord * cr)4485*472cd20dSToomas Soome mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *cr)
4486c65ebfc7SToomas Soome {
4487c65ebfc7SToomas Soome     DNSQuestion *q;
4488c65ebfc7SToomas Soome 
4489c65ebfc7SToomas Soome     // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4490c65ebfc7SToomas Soome     // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4491c65ebfc7SToomas Soome     for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4492c65ebfc7SToomas Soome     {
4493*472cd20dSToomas Soome         if (CacheRecordAnswersQuestion(cr, q))
4494c65ebfc7SToomas Soome         {
44953b436d06SToomas Soome 	    mDNSIPPort zp = zeroIPPort;
4496c65ebfc7SToomas Soome             // If this question is one that's actively sending queries, and it's received ten answers within one
4497c65ebfc7SToomas Soome             // second of sending the last query packet, then that indicates some radical network topology change,
4498c65ebfc7SToomas Soome             // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4499c65ebfc7SToomas Soome             // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4500c65ebfc7SToomas Soome             // because we will anyway send another query within a few seconds. The first reset query is sent out
4501c65ebfc7SToomas Soome             // randomized over the next four seconds to reduce possible synchronization between machines.
4502c65ebfc7SToomas Soome             if (q->LastAnswerPktNum != m->PktNum)
4503c65ebfc7SToomas Soome             {
4504c65ebfc7SToomas Soome                 q->LastAnswerPktNum = m->PktNum;
4505c65ebfc7SToomas Soome                 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4506c65ebfc7SToomas Soome                     q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4507c65ebfc7SToomas Soome                 {
4508c65ebfc7SToomas Soome                     LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4509c65ebfc7SToomas Soome                            q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4510c65ebfc7SToomas Soome                     q->LastQTime      = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4511c65ebfc7SToomas Soome                     q->ThisQInterval  = InitialQuestionInterval;
4512c65ebfc7SToomas Soome                     SetNextQueryTime(m,q);
4513c65ebfc7SToomas Soome                 }
4514c65ebfc7SToomas Soome             }
4515*472cd20dSToomas Soome             verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr, cr->resrec.name->c,
4516*472cd20dSToomas Soome                           DNSTypeName(cr->resrec.rrtype), cr->resrec.rroriginalttl, cr->resrec.rDNSServer ?
4517*472cd20dSToomas Soome                           &cr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(cr->resrec.rDNSServer ?
4518*472cd20dSToomas Soome                                                                              cr->resrec.rDNSServer->port : zeroIPPort), q);
4519c65ebfc7SToomas Soome             q->CurrentAnswers++;
4520c65ebfc7SToomas Soome 
4521*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4522c65ebfc7SToomas Soome             q->unansweredQueries = 0;
4523*472cd20dSToomas Soome #endif
4524*472cd20dSToomas Soome             if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4525*472cd20dSToomas Soome             if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4526c65ebfc7SToomas Soome             if (q->CurrentAnswers > 4000)
4527c65ebfc7SToomas Soome             {
4528c65ebfc7SToomas Soome                 static int msgcount = 0;
4529c65ebfc7SToomas Soome                 if (msgcount++ < 10)
4530c65ebfc7SToomas Soome                     LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4531c65ebfc7SToomas Soome                            q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4532*472cd20dSToomas Soome                 cr->resrec.rroriginalttl = 0;
4533*472cd20dSToomas Soome                 cr->UnansweredQueries = MaxUnansweredQueries;
4534c65ebfc7SToomas Soome             }
4535c65ebfc7SToomas Soome         }
4536c65ebfc7SToomas Soome     }
4537c65ebfc7SToomas Soome 
4538*472cd20dSToomas Soome     if (!cr->DelayDelivery)
4539c65ebfc7SToomas Soome     {
4540c65ebfc7SToomas Soome         if (m->CurrentQuestion)
4541c65ebfc7SToomas Soome             LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4542c65ebfc7SToomas Soome         m->CurrentQuestion = m->Questions;
4543c65ebfc7SToomas Soome         while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4544c65ebfc7SToomas Soome         {
4545c65ebfc7SToomas Soome             q = m->CurrentQuestion;
4546*472cd20dSToomas Soome             if (CacheRecordAnswersQuestion(cr, q))
4547*472cd20dSToomas Soome                 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4548c65ebfc7SToomas Soome             if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4549c65ebfc7SToomas Soome                 m->CurrentQuestion = q->next;
4550c65ebfc7SToomas Soome         }
4551c65ebfc7SToomas Soome         m->CurrentQuestion = mDNSNULL;
4552c65ebfc7SToomas Soome     }
4553c65ebfc7SToomas Soome 
4554*472cd20dSToomas Soome     SetNextCacheCheckTimeForRecord(m, cr);
4555c65ebfc7SToomas Soome }
4556c65ebfc7SToomas Soome 
4557c65ebfc7SToomas Soome // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4558c65ebfc7SToomas Soome // If new questions are created as a result of invoking client callbacks, they will be added to
4559c65ebfc7SToomas Soome // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4560c65ebfc7SToomas Soome // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4561c65ebfc7SToomas Soome // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4562c65ebfc7SToomas Soome // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4563c65ebfc7SToomas Soome // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4564c65ebfc7SToomas Soome // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4565c65ebfc7SToomas Soome // which may change the record list and/or question list.
4566c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
NoCacheAnswer(mDNS * const m,CacheRecord * cr)4567*472cd20dSToomas Soome mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *cr)
4568c65ebfc7SToomas Soome {
4569c65ebfc7SToomas Soome     LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4570c65ebfc7SToomas Soome     if (m->CurrentQuestion)
4571c65ebfc7SToomas Soome         LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4572c65ebfc7SToomas Soome     m->CurrentQuestion = m->Questions;
4573c65ebfc7SToomas Soome     // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4574c65ebfc7SToomas Soome     // since we're not caching the record and we'll get no opportunity to do this later
4575c65ebfc7SToomas Soome     while (m->CurrentQuestion)
4576c65ebfc7SToomas Soome     {
4577c65ebfc7SToomas Soome         DNSQuestion *q = m->CurrentQuestion;
4578*472cd20dSToomas Soome         if (CacheRecordAnswersQuestion(cr, q))
4579*472cd20dSToomas Soome             AnswerCurrentQuestionWithResourceRecord(m, cr, QC_addnocache);  // QC_addnocache means "don't expect remove events for this"
4580c65ebfc7SToomas Soome         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4581c65ebfc7SToomas Soome             m->CurrentQuestion = q->next;
4582c65ebfc7SToomas Soome     }
4583c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
4584c65ebfc7SToomas Soome }
4585c65ebfc7SToomas Soome 
4586c65ebfc7SToomas Soome // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4587c65ebfc7SToomas Soome // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4588c65ebfc7SToomas Soome // If new questions are created as a result of invoking client callbacks, they will be added to
4589c65ebfc7SToomas Soome // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4590*472cd20dSToomas Soome // cr is an existing cache CacheRecord that just expired and is being deleted
4591c65ebfc7SToomas Soome // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4592c65ebfc7SToomas Soome // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4593c65ebfc7SToomas Soome // which may change the record list and/or question list.
4594c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
CacheRecordRmv(mDNS * const m,CacheRecord * cr)4595*472cd20dSToomas Soome mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *cr)
4596c65ebfc7SToomas Soome {
4597c65ebfc7SToomas Soome     if (m->CurrentQuestion)
4598c65ebfc7SToomas Soome         LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4599c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4600c65ebfc7SToomas Soome     m->CurrentQuestion = m->Questions;
4601c65ebfc7SToomas Soome 
4602c65ebfc7SToomas Soome     // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4603c65ebfc7SToomas Soome     // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4604c65ebfc7SToomas Soome     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4605c65ebfc7SToomas Soome     {
4606c65ebfc7SToomas Soome         DNSQuestion *q = m->CurrentQuestion;
4607c65ebfc7SToomas Soome         // When a question enters suppressed state, we generate RMV events and generate a negative
4608c65ebfc7SToomas Soome         // response. A cache may be present that answers this question e.g., cache entry generated
4609c65ebfc7SToomas Soome         // before the question became suppressed. We need to skip the suppressed questions here as
4610c65ebfc7SToomas Soome         // the RMV event has already been generated.
4611*472cd20dSToomas Soome         if (!q->Suppressed && CacheRecordAnswersQuestion(cr, q) &&
4612*472cd20dSToomas Soome             (q->allowExpired == AllowExpired_None || cr->resrec.mortality == Mortality_Mortal))
4613c65ebfc7SToomas Soome         {
4614*472cd20dSToomas Soome             verbosedebugf("CacheRecordRmv %p %s", cr, CRDisplayString(m, cr));
4615c65ebfc7SToomas Soome             q->FlappingInterface1 = mDNSNULL;
4616c65ebfc7SToomas Soome             q->FlappingInterface2 = mDNSNULL;
4617c65ebfc7SToomas Soome 
4618*472cd20dSToomas Soome             if (q->CurrentAnswers == 0)
4619*472cd20dSToomas Soome             {
4620*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4621c65ebfc7SToomas Soome                 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4622c65ebfc7SToomas Soome                        q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4623*472cd20dSToomas Soome                        mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4624*472cd20dSToomas Soome #endif
46253b436d06SToomas Soome             }
4626c65ebfc7SToomas Soome             else
4627c65ebfc7SToomas Soome             {
4628c65ebfc7SToomas Soome                 q->CurrentAnswers--;
4629*472cd20dSToomas Soome                 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4630*472cd20dSToomas Soome                 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4631c65ebfc7SToomas Soome             }
4632c65ebfc7SToomas Soome 
4633c65ebfc7SToomas Soome             // If we have dropped below the answer threshold for this mDNS question,
4634c65ebfc7SToomas Soome             // restart the queries at InitialQuestionInterval.
4635c65ebfc7SToomas Soome             if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4636c65ebfc7SToomas Soome             {
4637c65ebfc7SToomas Soome                 q->ThisQInterval = InitialQuestionInterval;
4638c65ebfc7SToomas Soome                 q->LastQTime     = m->timenow - q->ThisQInterval;
4639c65ebfc7SToomas Soome                 SetNextQueryTime(m,q);
4640c65ebfc7SToomas Soome                 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4641c65ebfc7SToomas Soome                     DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4642c65ebfc7SToomas Soome             }
4643*472cd20dSToomas Soome             if (cr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4644c65ebfc7SToomas Soome             {
46453b436d06SToomas Soome                 if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID))
4646c65ebfc7SToomas Soome                 {
4647c65ebfc7SToomas Soome                     LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4648c65ebfc7SToomas Soome                             q->qname.c, DNSTypeName(q->qtype));
4649*472cd20dSToomas Soome                     ReconfirmAntecedents(m, &q->qname, q->qnamehash, cr->resrec.InterfaceID, 0);
4650c65ebfc7SToomas Soome                 }
4651*472cd20dSToomas Soome                 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
4652c65ebfc7SToomas Soome             }
4653c65ebfc7SToomas Soome         }
4654c65ebfc7SToomas Soome         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4655c65ebfc7SToomas Soome             m->CurrentQuestion = q->next;
4656c65ebfc7SToomas Soome     }
4657c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
4658c65ebfc7SToomas Soome }
4659c65ebfc7SToomas Soome 
ReleaseCacheEntity(mDNS * const m,CacheEntity * e)4660c65ebfc7SToomas Soome mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4661c65ebfc7SToomas Soome {
4662*472cd20dSToomas Soome #if MDNS_MALLOC_DEBUGGING >= 1
4663c65ebfc7SToomas Soome     unsigned int i;
4664c65ebfc7SToomas Soome     for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4665c65ebfc7SToomas Soome #endif
4666c65ebfc7SToomas Soome     e->next = m->rrcache_free;
4667c65ebfc7SToomas Soome     m->rrcache_free = e;
4668c65ebfc7SToomas Soome     m->rrcache_totalused--;
4669c65ebfc7SToomas Soome }
4670c65ebfc7SToomas Soome 
ReleaseCacheGroup(mDNS * const m,CacheGroup ** cp)4671c65ebfc7SToomas Soome mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4672c65ebfc7SToomas Soome {
4673c65ebfc7SToomas Soome     CacheEntity *e = (CacheEntity *)(*cp);
4674c65ebfc7SToomas Soome     //LogMsg("ReleaseCacheGroup:  Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4675c65ebfc7SToomas Soome     if ((*cp)->rrcache_tail != &(*cp)->members)
4676c65ebfc7SToomas Soome         LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4677c65ebfc7SToomas Soome     //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4678c65ebfc7SToomas Soome     //  LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4679c65ebfc7SToomas Soome     if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4680c65ebfc7SToomas Soome     (*cp)->name = mDNSNULL;
4681c65ebfc7SToomas Soome     *cp = (*cp)->next;          // Cut record from list
4682c65ebfc7SToomas Soome     ReleaseCacheEntity(m, e);
4683c65ebfc7SToomas Soome }
4684c65ebfc7SToomas Soome 
ReleaseAdditionalCacheRecords(mDNS * const m,CacheRecord ** rp)4685c65ebfc7SToomas Soome mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4686c65ebfc7SToomas Soome {
4687c65ebfc7SToomas Soome     while (*rp)
4688c65ebfc7SToomas Soome     {
4689c65ebfc7SToomas Soome         CacheRecord *rr = *rp;
4690c65ebfc7SToomas Soome         *rp = (*rp)->next;          // Cut record from list
4691c65ebfc7SToomas Soome         if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4692c65ebfc7SToomas Soome         {
4693c65ebfc7SToomas Soome             mDNSPlatformMemFree(rr->resrec.rdata);
4694c65ebfc7SToomas Soome             rr->resrec.rdata = mDNSNULL;
4695c65ebfc7SToomas Soome         }
4696c65ebfc7SToomas Soome         // NSEC or SOA records that are not added to the CacheGroup do not share the name
4697c65ebfc7SToomas Soome         // of the CacheGroup.
4698c65ebfc7SToomas Soome         if (rr->resrec.name)
4699c65ebfc7SToomas Soome         {
4700c65ebfc7SToomas Soome             debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4701c65ebfc7SToomas Soome             mDNSPlatformMemFree((void *)rr->resrec.name);
4702c65ebfc7SToomas Soome             rr->resrec.name = mDNSNULL;
4703c65ebfc7SToomas Soome         }
4704c65ebfc7SToomas Soome         // Don't count the NSEC3 records used by anonymous browse/reg
4705c65ebfc7SToomas Soome         if (!rr->resrec.InterfaceID)
4706c65ebfc7SToomas Soome         {
4707c65ebfc7SToomas Soome             m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4708c65ebfc7SToomas Soome         }
4709c65ebfc7SToomas Soome         ReleaseCacheEntity(m, (CacheEntity *)rr);
4710c65ebfc7SToomas Soome     }
4711c65ebfc7SToomas Soome }
4712c65ebfc7SToomas Soome 
ReleaseCacheRecord(mDNS * const m,CacheRecord * r)4713c65ebfc7SToomas Soome mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4714c65ebfc7SToomas Soome {
4715c65ebfc7SToomas Soome     CacheGroup *cg;
4716c65ebfc7SToomas Soome 
4717c65ebfc7SToomas Soome     //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4718c65ebfc7SToomas Soome     if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4719c65ebfc7SToomas Soome     r->resrec.rdata = mDNSNULL;
4720*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4721*472cd20dSToomas Soome     mdns_forget(&r->resrec.dnsservice);
4722*472cd20dSToomas Soome #endif
4723*472cd20dSToomas Soome 
4724*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4725*472cd20dSToomas Soome     release_denial_records_in_cache_record(r);
4726*472cd20dSToomas Soome #endif
4727c65ebfc7SToomas Soome 
4728c65ebfc7SToomas Soome     cg = CacheGroupForRecord(m, &r->resrec);
4729c65ebfc7SToomas Soome 
4730c65ebfc7SToomas Soome     if (!cg)
4731c65ebfc7SToomas Soome     {
4732c65ebfc7SToomas Soome         // It is okay to have this printed for NSEC/NSEC3s
4733c65ebfc7SToomas Soome         LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4734c65ebfc7SToomas Soome     }
4735c65ebfc7SToomas Soome     // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4736c65ebfc7SToomas Soome     // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4737c65ebfc7SToomas Soome     // (which is handled below) and in that case it should be freed here.
4738c65ebfc7SToomas Soome     if (r->resrec.name && cg && r->resrec.name != cg->name)
4739c65ebfc7SToomas Soome     {
4740c65ebfc7SToomas Soome         debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4741c65ebfc7SToomas Soome         mDNSPlatformMemFree((void *)r->resrec.name);
4742c65ebfc7SToomas Soome     }
4743c65ebfc7SToomas Soome     r->resrec.name = mDNSNULL;
4744c65ebfc7SToomas Soome 
4745c65ebfc7SToomas Soome     if (!r->resrec.InterfaceID)
4746c65ebfc7SToomas Soome     {
4747c65ebfc7SToomas Soome         m->rrcache_totalused_unicast -= r->resrec.rdlength;
4748c65ebfc7SToomas Soome     }
4749c65ebfc7SToomas Soome 
4750c65ebfc7SToomas Soome     ReleaseAdditionalCacheRecords(m, &r->soa);
4751c65ebfc7SToomas Soome 
4752c65ebfc7SToomas Soome     ReleaseCacheEntity(m, (CacheEntity *)r);
4753c65ebfc7SToomas Soome }
4754c65ebfc7SToomas Soome 
4755c65ebfc7SToomas Soome // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4756c65ebfc7SToomas Soome // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4757c65ebfc7SToomas Soome // callbacks for old records are delivered before callbacks for newer records.
CheckCacheExpiration(mDNS * const m,const mDNSu32 slot,CacheGroup * const cg)4758c65ebfc7SToomas Soome mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4759c65ebfc7SToomas Soome {
4760c65ebfc7SToomas Soome     CacheRecord **rp = &cg->members;
4761c65ebfc7SToomas Soome 
4762c65ebfc7SToomas Soome     if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4763c65ebfc7SToomas Soome     m->lock_rrcache = 1;
4764c65ebfc7SToomas Soome 
4765c65ebfc7SToomas Soome     while (*rp)
4766c65ebfc7SToomas Soome     {
4767c65ebfc7SToomas Soome         CacheRecord *const rr = *rp;
47683b436d06SToomas Soome         mDNSBool recordReleased = mDNSfalse;
4769c65ebfc7SToomas Soome         mDNSs32 event = RRExpireTime(rr);
4770c65ebfc7SToomas Soome         if (m->timenow - event >= 0)    // If expired, delete it
4771c65ebfc7SToomas Soome         {
4772c65ebfc7SToomas Soome             if (rr->CRActiveQuestion)   // If this record has one or more active questions, tell them it's going away
4773c65ebfc7SToomas Soome             {
4774c65ebfc7SToomas Soome                 DNSQuestion *q = rr->CRActiveQuestion;
47753b436d06SToomas Soome                 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
47763b436d06SToomas Soome                               m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4777c65ebfc7SToomas Soome                 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4778c65ebfc7SToomas Soome                 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4779c65ebfc7SToomas Soome                 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4780c65ebfc7SToomas Soome                 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4781c65ebfc7SToomas Soome                 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4782c65ebfc7SToomas Soome                 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4783c65ebfc7SToomas Soome                 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4784*472cd20dSToomas Soome                 if (((mDNSOpaque16IsZero(q->TargetQID) && (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) ||
4785*472cd20dSToomas Soome                      (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived)) && ActiveQuestion(q))
4786c65ebfc7SToomas Soome                 {
4787c65ebfc7SToomas Soome                     q->ThisQInterval = InitialQuestionInterval;
4788c65ebfc7SToomas Soome                     q->LastQTime     = m->timenow - q->ThisQInterval;
4789c65ebfc7SToomas Soome                     SetNextQueryTime(m, q);
4790c65ebfc7SToomas Soome                 }
4791c65ebfc7SToomas Soome                 CacheRecordRmv(m, rr);
4792c65ebfc7SToomas Soome                 m->rrcache_active--;
4793c65ebfc7SToomas Soome             }
47943b436d06SToomas Soome 
47953b436d06SToomas Soome             event += MAX_GHOST_TIME;                                                    // Adjust so we can check for a ghost expiration
47963b436d06SToomas Soome             if (rr->resrec.mortality == Mortality_Mortal ||                             // Normal expired mortal record that needs released
4797*472cd20dSToomas Soome                 rr->resrec.rroriginalttl == 0            ||                             // Non-mortal record that is set to be purged
47983b436d06SToomas Soome                 (rr->resrec.mortality == Mortality_Ghost && m->timenow - event >= 0))   // A ghost record that expired more than MAX_GHOST_TIME ago
47993b436d06SToomas Soome             {   //  Release as normal
48003b436d06SToomas Soome                 *rp = rr->next;                                     // Cut it from the list before ReleaseCacheRecord
48013b436d06SToomas Soome                 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
48023b436d06SToomas Soome                               MortalityDisplayString(rr->resrec.mortality),
48033b436d06SToomas Soome                               m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4804c65ebfc7SToomas Soome                 ReleaseCacheRecord(m, rr);
48053b436d06SToomas Soome                 recordReleased = mDNStrue;
48063b436d06SToomas Soome             }
48073b436d06SToomas Soome             else                                                    // An immortal record needs to become a ghost when it expires
48083b436d06SToomas Soome             {   // Don't release this entry
48093b436d06SToomas Soome                 if (rr->resrec.mortality == Mortality_Immortal)
48103b436d06SToomas Soome                 {
48113b436d06SToomas Soome                     rr->resrec.mortality = Mortality_Ghost;         // Expired immortal records become ghosts
48123b436d06SToomas Soome                     verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
48133b436d06SToomas Soome                                   MortalityDisplayString(rr->resrec.mortality),
48143b436d06SToomas Soome                                   m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
48153b436d06SToomas Soome                 }
48163b436d06SToomas Soome             }
4817c65ebfc7SToomas Soome         }
4818c65ebfc7SToomas Soome         else                                                        // else, not expired; see if we need to query
4819c65ebfc7SToomas Soome         {
4820c65ebfc7SToomas Soome             // If waiting to delay delivery, do nothing until then
4821c65ebfc7SToomas Soome             if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4822c65ebfc7SToomas Soome                 event = rr->DelayDelivery;
4823c65ebfc7SToomas Soome             else
4824c65ebfc7SToomas Soome             {
4825c65ebfc7SToomas Soome                 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4826c65ebfc7SToomas Soome                 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4827c65ebfc7SToomas Soome                 {
4828c65ebfc7SToomas Soome                     if (m->timenow - rr->NextRequiredQuery < 0)     // If not yet time for next query
4829c65ebfc7SToomas Soome                         event = NextCacheCheckEvent(rr);            // then just record when we want the next query
4830c65ebfc7SToomas Soome                     else                                            // else trigger our question to go out now
4831c65ebfc7SToomas Soome                     {
4832c65ebfc7SToomas Soome                         // Set NextScheduledQuery to timenow so that SendQueries() will run.
4833c65ebfc7SToomas Soome                         // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4834c65ebfc7SToomas Soome                         m->NextScheduledQuery = m->timenow;
4835c65ebfc7SToomas Soome                         // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4836c65ebfc7SToomas Soome                         // which will correctly update m->NextCacheCheck for us.
4837c65ebfc7SToomas Soome                         event = m->timenow + FutureTime;
4838c65ebfc7SToomas Soome                     }
4839c65ebfc7SToomas Soome                 }
4840c65ebfc7SToomas Soome             }
48413b436d06SToomas Soome         }
48423b436d06SToomas Soome 
48433b436d06SToomas Soome         if (!recordReleased)  //  Schedule if we did not release the record
48443b436d06SToomas Soome         {
4845c65ebfc7SToomas Soome             verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4846c65ebfc7SToomas Soome                           (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4847c65ebfc7SToomas Soome             if (m->rrcache_nextcheck[slot] - event > 0)
4848c65ebfc7SToomas Soome                 m->rrcache_nextcheck[slot] = event;
4849c65ebfc7SToomas Soome             rp = &rr->next;
4850c65ebfc7SToomas Soome         }
4851c65ebfc7SToomas Soome     }
4852c65ebfc7SToomas Soome     if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4853c65ebfc7SToomas Soome     cg->rrcache_tail = rp;
4854c65ebfc7SToomas Soome     m->lock_rrcache = 0;
4855c65ebfc7SToomas Soome }
4856c65ebfc7SToomas Soome 
4857c65ebfc7SToomas Soome // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4858c65ebfc7SToomas Soome //
4859c65ebfc7SToomas Soome // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4860c65ebfc7SToomas Soome // returns true if there is an answer.
4861c65ebfc7SToomas Soome //
4862c65ebfc7SToomas Soome // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4863c65ebfc7SToomas Soome // returns true to indicate the same.
AnswerQuestionWithLORecord(mDNS * const m,DNSQuestion * q,mDNSBool checkOnly)4864c65ebfc7SToomas Soome mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4865c65ebfc7SToomas Soome {
4866c65ebfc7SToomas Soome     AuthRecord *lr;
4867c65ebfc7SToomas Soome     AuthGroup *ag;
4868c65ebfc7SToomas Soome 
4869c65ebfc7SToomas Soome     if (m->CurrentRecord)
4870c65ebfc7SToomas Soome         LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4871c65ebfc7SToomas Soome 
4872c65ebfc7SToomas Soome     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4873c65ebfc7SToomas Soome     if (ag)
4874c65ebfc7SToomas Soome     {
4875c65ebfc7SToomas Soome         m->CurrentRecord = ag->members;
4876c65ebfc7SToomas Soome         while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4877c65ebfc7SToomas Soome         {
4878c65ebfc7SToomas Soome             AuthRecord *rr = m->CurrentRecord;
4879c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
4880c65ebfc7SToomas Soome             //
4881c65ebfc7SToomas Soome             // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4882c65ebfc7SToomas Soome             // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4883c65ebfc7SToomas Soome             //
4884c65ebfc7SToomas Soome             // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4885c65ebfc7SToomas Soome             // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4886c65ebfc7SToomas Soome             // we handle both mDNSInterface_Any and scoped questions.
4887c65ebfc7SToomas Soome 
4888c65ebfc7SToomas Soome             if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE)))
4889c65ebfc7SToomas Soome                 if (LocalOnlyRecordAnswersQuestion(rr, q))
4890c65ebfc7SToomas Soome                 {
4891c65ebfc7SToomas Soome                     if (checkOnly)
4892c65ebfc7SToomas Soome                     {
4893c65ebfc7SToomas Soome                         LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4894c65ebfc7SToomas Soome                             ARDisplayString(m, rr));
4895c65ebfc7SToomas Soome                         m->CurrentRecord = mDNSNULL;
4896c65ebfc7SToomas Soome                         return mDNStrue;
4897c65ebfc7SToomas Soome                     }
48983b436d06SToomas Soome                     AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4899c65ebfc7SToomas Soome                     if (m->CurrentQuestion != q)
4900c65ebfc7SToomas Soome                         break;     // If callback deleted q, then we're finished here
4901c65ebfc7SToomas Soome                 }
4902c65ebfc7SToomas Soome         }
4903c65ebfc7SToomas Soome     }
4904c65ebfc7SToomas Soome     m->CurrentRecord = mDNSNULL;
4905c65ebfc7SToomas Soome 
4906c65ebfc7SToomas Soome     if (m->CurrentQuestion != q)
4907c65ebfc7SToomas Soome     {
4908c65ebfc7SToomas Soome         LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4909c65ebfc7SToomas Soome         return mDNStrue;
4910c65ebfc7SToomas Soome     }
4911c65ebfc7SToomas Soome 
4912c65ebfc7SToomas Soome     if (q->LOAddressAnswers)
4913c65ebfc7SToomas Soome     {
4914c65ebfc7SToomas Soome         LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4915c65ebfc7SToomas Soome                 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4916c65ebfc7SToomas Soome         return mDNStrue;
4917c65ebfc7SToomas Soome     }
4918c65ebfc7SToomas Soome 
4919c65ebfc7SToomas Soome     // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4920c65ebfc7SToomas Soome     // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4921c65ebfc7SToomas Soome     // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4922c65ebfc7SToomas Soome     // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4923c65ebfc7SToomas Soome     // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4924c65ebfc7SToomas Soome     if (ag)
4925c65ebfc7SToomas Soome     {
4926c65ebfc7SToomas Soome         lr = ag->NewLocalOnlyRecords;
4927c65ebfc7SToomas Soome         while (lr)
4928c65ebfc7SToomas Soome         {
4929c65ebfc7SToomas Soome             if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4930c65ebfc7SToomas Soome             {
4931c65ebfc7SToomas Soome                 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4932c65ebfc7SToomas Soome                         " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4933c65ebfc7SToomas Soome                 return mDNStrue;
4934c65ebfc7SToomas Soome             }
4935c65ebfc7SToomas Soome             lr = lr->next;
4936c65ebfc7SToomas Soome         }
4937c65ebfc7SToomas Soome     }
4938c65ebfc7SToomas Soome     return mDNSfalse;
4939c65ebfc7SToomas Soome }
4940c65ebfc7SToomas Soome 
4941c65ebfc7SToomas Soome // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4942c65ebfc7SToomas Soome // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4943*472cd20dSToomas Soome // DNS requests.
AnswerSuppressedQuestion(mDNS * const m,DNSQuestion * q)4944c65ebfc7SToomas Soome mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4945c65ebfc7SToomas Soome {
4946*472cd20dSToomas Soome     // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4947*472cd20dSToomas Soome     // just deactivate the DNSQuestion.
4948*472cd20dSToomas Soome     if (q->ReturnIntermed)
4949*472cd20dSToomas Soome     {
4950*472cd20dSToomas Soome         GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed);
4951*472cd20dSToomas Soome     }
4952*472cd20dSToomas Soome     else
4953c65ebfc7SToomas Soome     {
4954c65ebfc7SToomas Soome         q->ThisQInterval = 0;
4955c65ebfc7SToomas Soome     }
4956c65ebfc7SToomas Soome }
4957c65ebfc7SToomas Soome 
AnswerNewQuestion(mDNS * const m)4958c65ebfc7SToomas Soome mDNSlocal void AnswerNewQuestion(mDNS *const m)
4959c65ebfc7SToomas Soome {
4960c65ebfc7SToomas Soome     mDNSBool ShouldQueryImmediately = mDNStrue;
4961c65ebfc7SToomas Soome     DNSQuestion *const q = m->NewQuestions;     // Grab the question we're going to answer
4962*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4963c65ebfc7SToomas Soome     if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q);
4964c65ebfc7SToomas Soome #endif
4965c65ebfc7SToomas Soome     CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
4966c65ebfc7SToomas Soome 
4967c65ebfc7SToomas Soome     verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4968c65ebfc7SToomas Soome 
4969c65ebfc7SToomas Soome     if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg);
4970c65ebfc7SToomas Soome     if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4971c65ebfc7SToomas Soome     m->NewQuestions = q->next;
4972c65ebfc7SToomas Soome     // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4973c65ebfc7SToomas Soome     // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4974c65ebfc7SToomas Soome     //
4975c65ebfc7SToomas Soome     // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4976c65ebfc7SToomas Soome     // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4977c65ebfc7SToomas Soome     // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4978c65ebfc7SToomas Soome     // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4979c65ebfc7SToomas Soome     // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4980c65ebfc7SToomas Soome     // advanced it), that means the question was deleted, so we no longer need to worry about answering
4981c65ebfc7SToomas Soome     // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4982c65ebfc7SToomas Soome     // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4983c65ebfc7SToomas Soome     //
4984c65ebfc7SToomas Soome     // We can't use the usual m->CurrentQuestion mechanism for this because  CacheRecordDeferredAdd() and
4985c65ebfc7SToomas Soome     // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4986c65ebfc7SToomas Soome     // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4987c65ebfc7SToomas Soome     // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4988c65ebfc7SToomas Soome 
4989c65ebfc7SToomas Soome     if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4990c65ebfc7SToomas Soome     // This should be safe, because calling the client's question callback may cause the
4991c65ebfc7SToomas Soome     // question list to be modified, but should not ever cause the rrcache list to be modified.
4992c65ebfc7SToomas Soome     // If the client's question callback deletes the question, then m->CurrentQuestion will
4993c65ebfc7SToomas Soome     // be advanced, and we'll exit out of the loop
4994c65ebfc7SToomas Soome     m->lock_rrcache = 1;
4995*472cd20dSToomas Soome     if (m->CurrentQuestion) {
4996*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
4997*472cd20dSToomas Soome                "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME " (" PUB_S ")",
4998*472cd20dSToomas Soome                m->CurrentQuestion->request_id, mDNSVal16(m->CurrentQuestion->TargetQID),
4999*472cd20dSToomas Soome                DM_NAME_PARAM(&m->CurrentQuestion->qname), DNSTypeName(m->CurrentQuestion->qtype));
5000*472cd20dSToomas Soome     }
5001*472cd20dSToomas Soome 
5002c65ebfc7SToomas Soome     m->CurrentQuestion = q;     // Indicate which question we're answering, so we'll know if it gets deleted
5003c65ebfc7SToomas Soome 
5004c65ebfc7SToomas Soome     if (q->NoAnswer == NoAnswer_Fail)
5005c65ebfc7SToomas Soome     {
5006*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5007*472cd20dSToomas Soome                "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME " (" PUB_S ")",
5008*472cd20dSToomas Soome                q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
5009*472cd20dSToomas Soome 
5010*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5011*472cd20dSToomas Soome         MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->dnsservice);
5012*472cd20dSToomas Soome #else
5013c65ebfc7SToomas Soome         MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
5014*472cd20dSToomas Soome #endif
5015c65ebfc7SToomas Soome         q->NoAnswer = NoAnswer_Normal;      // Temporarily turn off answer suppression
5016c65ebfc7SToomas Soome         AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
5017c65ebfc7SToomas Soome         // Don't touch the question if it has been stopped already
5018c65ebfc7SToomas Soome         if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail;       // Restore NoAnswer state
5019c65ebfc7SToomas Soome         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
5020c65ebfc7SToomas Soome     }
5021c65ebfc7SToomas Soome 
5022c65ebfc7SToomas Soome     if (m->CurrentQuestion != q)
5023c65ebfc7SToomas Soome     {
5024c65ebfc7SToomas Soome         LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
5025c65ebfc7SToomas Soome         goto exit;
5026c65ebfc7SToomas Soome     }
5027c65ebfc7SToomas Soome 
5028c65ebfc7SToomas Soome     // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
5029c65ebfc7SToomas Soome     // or P2P record, then we are done.
5030c65ebfc7SToomas Soome     if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
5031c65ebfc7SToomas Soome         goto exit;
5032c65ebfc7SToomas Soome 
5033c65ebfc7SToomas Soome     // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5034c65ebfc7SToomas Soome     // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5035c65ebfc7SToomas Soome     // the question out.
5036*472cd20dSToomas Soome     if (q->Suppressed)
5037c65ebfc7SToomas Soome     {
5038c65ebfc7SToomas Soome         AnswerSuppressedQuestion(m, q);
5039c65ebfc7SToomas Soome     }
5040*472cd20dSToomas Soome     else
5041c65ebfc7SToomas Soome     {
5042*472cd20dSToomas Soome         CacheRecord *cr;
5043*472cd20dSToomas Soome         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5044*472cd20dSToomas Soome             if (SameNameCacheRecordAnswersQuestion(cr, q))
5045c65ebfc7SToomas Soome             {
5046c65ebfc7SToomas Soome                 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5047*472cd20dSToomas Soome                 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - cr->TimeRcvd)) / mDNSPlatformOneSecond;
5048*472cd20dSToomas Soome                 mDNSBool IsExpired = (cr->resrec.rroriginalttl <= SecsSinceRcvd);
5049*472cd20dSToomas Soome                 if (IsExpired && q->allowExpired != AllowExpired_AllowExpiredAnswers) continue;   // Go to next one in loop
5050c65ebfc7SToomas Soome 
5051c65ebfc7SToomas Soome                 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5052c65ebfc7SToomas Soome                 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5053*472cd20dSToomas Soome                 if ((cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
5054c65ebfc7SToomas Soome                     ShouldQueryImmediately = mDNSfalse;
5055c65ebfc7SToomas Soome                 q->CurrentAnswers++;
5056*472cd20dSToomas Soome                 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
5057*472cd20dSToomas Soome                 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
5058*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5059*472cd20dSToomas Soome                 if (q->metrics.expiredAnswerState == ExpiredAnswer_Allowed) q->metrics.expiredAnswerState = IsExpired ? ExpiredAnswer_AnsweredWithExpired : ExpiredAnswer_AnsweredWithCache;
50603b436d06SToomas Soome #endif
5061*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5062*472cd20dSToomas Soome                 cr->LastCachedAnswerTime = m->timenow;
5063*472cd20dSToomas Soome                 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_hit);
5064*472cd20dSToomas Soome #endif
5065*472cd20dSToomas Soome                 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
5066c65ebfc7SToomas Soome                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
5067c65ebfc7SToomas Soome             }
5068*472cd20dSToomas Soome             else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(cr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
5069c65ebfc7SToomas Soome                 ShouldQueryImmediately = mDNSfalse;
5070c65ebfc7SToomas Soome     }
5071c65ebfc7SToomas Soome     // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5072c65ebfc7SToomas Soome     // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5073c65ebfc7SToomas Soome     if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
5074c65ebfc7SToomas Soome 
5075*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5076*472cd20dSToomas Soome     dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_miss);
5077*472cd20dSToomas Soome #endif
5078*472cd20dSToomas Soome     q->InitialCacheMiss  = mDNStrue;                                    // Initial cache check is done, so mark as a miss from now on
50793b436d06SToomas Soome     if (q->allowExpired == AllowExpired_AllowExpiredAnswers)
50803b436d06SToomas Soome     {
50813b436d06SToomas Soome         q->allowExpired = AllowExpired_MakeAnswersImmortal;             // After looking through the cache for an answer, demote to make immortal
50823b436d06SToomas Soome         if (q->firstExpiredQname.c[0])                                  // If an original query name was saved on an expired answer, start it over in case it is updated
50833b436d06SToomas Soome         {
5084*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5085*472cd20dSToomas Soome                    "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME " for allowExpiredAnswers question",
5086*472cd20dSToomas Soome                    q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->firstExpiredQname));
50873b436d06SToomas Soome             mDNS_StopQuery_internal(m, q);                              // Stop old query
5088*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5089*472cd20dSToomas Soome             if (!SameDomainName(&q->qname, &q->firstExpiredQname))
5090*472cd20dSToomas Soome             {
5091*472cd20dSToomas Soome                 Querier_PrepareQuestionForUnwindRestart(q);
5092*472cd20dSToomas Soome             }
5093*472cd20dSToomas Soome #endif
50943b436d06SToomas Soome             AssignDomainName(&q->qname, &q->firstExpiredQname);         // Update qname
50953b436d06SToomas Soome             q->qnamehash = DomainNameHashValue(&q->qname);              // and namehash
50963b436d06SToomas Soome             mDNS_StartQuery_internal(m, q);                             // start new query
50973b436d06SToomas Soome             q->CNAMEReferrals = 0;                                      // Reset referral count
50983b436d06SToomas Soome             q->firstExpiredQname.c[0] = 0;                              // Erase the domain name
50993b436d06SToomas Soome         }
51003b436d06SToomas Soome     }
51013b436d06SToomas Soome 
5102c65ebfc7SToomas Soome     // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5103c65ebfc7SToomas Soome     // Hence we don't execute the following block of code for those cases.
5104c65ebfc7SToomas Soome     if (ShouldQueryImmediately && ActiveQuestion(q))
5105c65ebfc7SToomas Soome     {
5106*472cd20dSToomas Soome         debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->request_id, mDNSVal16(q->TargetQID), q->qname.c, DNSTypeName(q->qtype));
5107c65ebfc7SToomas Soome         q->ThisQInterval  = InitialQuestionInterval;
5108c65ebfc7SToomas Soome         q->LastQTime      = m->timenow - q->ThisQInterval;
5109c65ebfc7SToomas Soome         if (mDNSOpaque16IsZero(q->TargetQID))       // For mDNS, spread packets to avoid a burst of simultaneous queries
5110c65ebfc7SToomas Soome         {
5111c65ebfc7SToomas Soome             // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5112c65ebfc7SToomas Soome             if (!m->RandomQueryDelay)
5113c65ebfc7SToomas Soome                 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
5114c65ebfc7SToomas Soome             q->LastQTime += m->RandomQueryDelay;
5115c65ebfc7SToomas Soome         }
5116c65ebfc7SToomas Soome     }
5117c65ebfc7SToomas Soome 
5118c65ebfc7SToomas Soome     // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5119c65ebfc7SToomas Soome     // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5120c65ebfc7SToomas Soome     // answers for this question until *after* its scheduled transmission time, in which case
5121c65ebfc7SToomas Soome     // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5122c65ebfc7SToomas Soome     // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5123c65ebfc7SToomas Soome     SetNextQueryTime(m,q);
5124c65ebfc7SToomas Soome 
5125c65ebfc7SToomas Soome exit:
5126c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
5127c65ebfc7SToomas Soome     m->lock_rrcache = 0;
5128c65ebfc7SToomas Soome }
5129c65ebfc7SToomas Soome 
5130c65ebfc7SToomas Soome // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5131c65ebfc7SToomas Soome // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
AnswerNewLocalOnlyQuestion(mDNS * const m)5132c65ebfc7SToomas Soome mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
5133c65ebfc7SToomas Soome {
5134c65ebfc7SToomas Soome     AuthGroup *ag;
5135c65ebfc7SToomas Soome     DNSQuestion *q = m->NewLocalOnlyQuestions;      // Grab the question we're going to answer
5136c65ebfc7SToomas Soome     mDNSBool retEv = mDNSfalse;
5137c65ebfc7SToomas Soome     m->NewLocalOnlyQuestions = q->next;             // Advance NewLocalOnlyQuestions to the next (if any)
5138c65ebfc7SToomas Soome 
5139c65ebfc7SToomas Soome     debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5140c65ebfc7SToomas Soome 
5141c65ebfc7SToomas Soome     if (m->CurrentQuestion)
5142c65ebfc7SToomas Soome         LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5143c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5144c65ebfc7SToomas Soome     m->CurrentQuestion = q;     // Indicate which question we're answering, so we'll know if it gets deleted
5145c65ebfc7SToomas Soome 
5146c65ebfc7SToomas Soome     if (m->CurrentRecord)
5147c65ebfc7SToomas Soome         LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5148c65ebfc7SToomas Soome 
5149c65ebfc7SToomas Soome     // 1. First walk the LocalOnly records answering the LocalOnly question
5150c65ebfc7SToomas Soome     // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5151c65ebfc7SToomas Soome     //    walk the ResourceRecords list delivering the answers
5152c65ebfc7SToomas Soome     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5153c65ebfc7SToomas Soome     if (ag)
5154c65ebfc7SToomas Soome     {
5155c65ebfc7SToomas Soome         m->CurrentRecord = ag->members;
5156c65ebfc7SToomas Soome         while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
5157c65ebfc7SToomas Soome         {
5158c65ebfc7SToomas Soome             AuthRecord *rr = m->CurrentRecord;
5159c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
5160c65ebfc7SToomas Soome             if (LocalOnlyRecordAnswersQuestion(rr, q))
5161c65ebfc7SToomas Soome             {
5162c65ebfc7SToomas Soome                 retEv = mDNStrue;
5163*472cd20dSToomas Soome                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
5164c65ebfc7SToomas Soome                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
5165c65ebfc7SToomas Soome             }
5166c65ebfc7SToomas Soome         }
5167c65ebfc7SToomas Soome     }
5168c65ebfc7SToomas Soome 
5169c65ebfc7SToomas Soome     if (m->CurrentQuestion == q)
5170c65ebfc7SToomas Soome     {
5171c65ebfc7SToomas Soome         m->CurrentRecord = m->ResourceRecords;
5172c65ebfc7SToomas Soome 
5173c65ebfc7SToomas Soome         while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
5174c65ebfc7SToomas Soome         {
5175*472cd20dSToomas Soome             AuthRecord *ar = m->CurrentRecord;
5176*472cd20dSToomas Soome             m->CurrentRecord = ar->next;
5177*472cd20dSToomas Soome             if (AuthRecordAnswersQuestion(ar, q))
5178c65ebfc7SToomas Soome             {
5179c65ebfc7SToomas Soome                 retEv = mDNStrue;
5180*472cd20dSToomas Soome                 AnswerLocalQuestionWithLocalAuthRecord(m, ar, QC_add);
5181c65ebfc7SToomas Soome                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
5182c65ebfc7SToomas Soome             }
5183c65ebfc7SToomas Soome         }
5184c65ebfc7SToomas Soome     }
5185c65ebfc7SToomas Soome 
5186c65ebfc7SToomas Soome     // The local host is the authoritative source for LocalOnly questions
5187c65ebfc7SToomas Soome     // so if no records exist and client requested intermediates, then generate a negative response
5188c65ebfc7SToomas Soome     if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed)
5189c65ebfc7SToomas Soome         GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse);
5190c65ebfc7SToomas Soome 
5191c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
5192c65ebfc7SToomas Soome     m->CurrentRecord   = mDNSNULL;
5193c65ebfc7SToomas Soome }
5194c65ebfc7SToomas Soome 
GetCacheEntity(mDNS * const m,const CacheGroup * const PreserveCG)5195c65ebfc7SToomas Soome mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
5196c65ebfc7SToomas Soome {
5197c65ebfc7SToomas Soome     CacheEntity *e = mDNSNULL;
5198c65ebfc7SToomas Soome 
5199c65ebfc7SToomas Soome     if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
5200c65ebfc7SToomas Soome     m->lock_rrcache = 1;
5201c65ebfc7SToomas Soome 
5202c65ebfc7SToomas Soome     // If we have no free records, ask the client layer to give us some more memory
5203c65ebfc7SToomas Soome     if (!m->rrcache_free && m->MainCallback)
5204c65ebfc7SToomas Soome     {
5205c65ebfc7SToomas Soome         if (m->rrcache_totalused != m->rrcache_size)
5206*472cd20dSToomas Soome         {
5207*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5208*472cd20dSToomas Soome                       "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5209c65ebfc7SToomas Soome                       m->rrcache_totalused, m->rrcache_size);
5210*472cd20dSToomas Soome         }
5211c65ebfc7SToomas Soome 
5212c65ebfc7SToomas Soome         // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5213c65ebfc7SToomas Soome         // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5214c65ebfc7SToomas Soome         // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5215c65ebfc7SToomas Soome         // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5216c65ebfc7SToomas Soome         // and recycle them, instead of allocating more memory.
5217c65ebfc7SToomas Soome         if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
5218*472cd20dSToomas Soome         {
5219*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
5220*472cd20dSToomas Soome                       "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5221c65ebfc7SToomas Soome                       m->rrcache_size, m->rrcache_active);
5222*472cd20dSToomas Soome         }
5223c65ebfc7SToomas Soome         else
5224c65ebfc7SToomas Soome         {
5225c65ebfc7SToomas Soome             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
5226c65ebfc7SToomas Soome             m->MainCallback(m, mStatus_GrowCache);
5227c65ebfc7SToomas Soome             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
5228c65ebfc7SToomas Soome         }
5229c65ebfc7SToomas Soome     }
5230c65ebfc7SToomas Soome 
5231c65ebfc7SToomas Soome     // If we still have no free records, recycle all the records we can.
5232c65ebfc7SToomas Soome     // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5233c65ebfc7SToomas Soome     if (!m->rrcache_free)
5234c65ebfc7SToomas Soome     {
5235c65ebfc7SToomas Soome         mDNSu32 oldtotalused = m->rrcache_totalused;
5236c65ebfc7SToomas Soome         mDNSu32 slot;
5237c65ebfc7SToomas Soome         for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5238c65ebfc7SToomas Soome         {
5239c65ebfc7SToomas Soome             CacheGroup **cp = &m->rrcache_hash[slot];
5240c65ebfc7SToomas Soome             while (*cp)
5241c65ebfc7SToomas Soome             {
5242c65ebfc7SToomas Soome                 CacheRecord **rp = &(*cp)->members;
5243c65ebfc7SToomas Soome                 while (*rp)
5244c65ebfc7SToomas Soome                 {
5245c65ebfc7SToomas Soome                     // Records that answer still-active questions are not candidates for recycling
5246c65ebfc7SToomas Soome                     // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5247c65ebfc7SToomas Soome                     if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
5248c65ebfc7SToomas Soome                         rp=&(*rp)->next;
5249c65ebfc7SToomas Soome                     else
5250c65ebfc7SToomas Soome                     {
5251c65ebfc7SToomas Soome                         CacheRecord *rr = *rp;
5252c65ebfc7SToomas Soome                         *rp = (*rp)->next;          // Cut record from list
5253c65ebfc7SToomas Soome                         ReleaseCacheRecord(m, rr);
5254c65ebfc7SToomas Soome                     }
5255c65ebfc7SToomas Soome                 }
5256c65ebfc7SToomas Soome                 if ((*cp)->rrcache_tail != rp)
5257c65ebfc7SToomas Soome                     verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
5258c65ebfc7SToomas Soome                 (*cp)->rrcache_tail = rp;
5259c65ebfc7SToomas Soome                 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
5260c65ebfc7SToomas Soome                 else ReleaseCacheGroup(m, cp);
5261c65ebfc7SToomas Soome             }
5262c65ebfc7SToomas Soome         }
5263*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5264c65ebfc7SToomas Soome                   oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
5265c65ebfc7SToomas Soome     }
5266c65ebfc7SToomas Soome 
5267c65ebfc7SToomas Soome     if (m->rrcache_free)    // If there are records in the free list, take one
5268c65ebfc7SToomas Soome     {
5269c65ebfc7SToomas Soome         e = m->rrcache_free;
5270c65ebfc7SToomas Soome         m->rrcache_free = e->next;
5271c65ebfc7SToomas Soome         if (++m->rrcache_totalused >= m->rrcache_report)
5272c65ebfc7SToomas Soome         {
5273*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "RR Cache now using %u objects", m->rrcache_totalused);
5274c65ebfc7SToomas Soome             if      (m->rrcache_report <  100) m->rrcache_report += 10;
5275c65ebfc7SToomas Soome             else if (m->rrcache_report < 1000) m->rrcache_report += 100;
5276c65ebfc7SToomas Soome             else m->rrcache_report += 1000;
5277c65ebfc7SToomas Soome         }
5278c65ebfc7SToomas Soome         mDNSPlatformMemZero(e, sizeof(*e));
5279c65ebfc7SToomas Soome     }
5280c65ebfc7SToomas Soome 
5281c65ebfc7SToomas Soome     m->lock_rrcache = 0;
5282c65ebfc7SToomas Soome 
5283c65ebfc7SToomas Soome     return(e);
5284c65ebfc7SToomas Soome }
5285c65ebfc7SToomas Soome 
GetCacheRecord(mDNS * const m,CacheGroup * cg,mDNSu16 RDLength)5286c65ebfc7SToomas Soome mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
5287c65ebfc7SToomas Soome {
5288c65ebfc7SToomas Soome     CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
5289c65ebfc7SToomas Soome     if (r)
5290c65ebfc7SToomas Soome     {
5291c65ebfc7SToomas Soome         r->resrec.rdata = (RData*)&r->smallrdatastorage;    // By default, assume we're usually going to be using local storage
5292c65ebfc7SToomas Soome         if (RDLength > InlineCacheRDSize)           // If RDLength is too big, allocate extra storage
5293c65ebfc7SToomas Soome         {
5294*472cd20dSToomas Soome             r->resrec.rdata = (RData*) mDNSPlatformMemAllocateClear(sizeofRDataHeader + RDLength);
5295c65ebfc7SToomas Soome             if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
5296c65ebfc7SToomas Soome             else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
5297c65ebfc7SToomas Soome         }
5298c65ebfc7SToomas Soome     }
5299c65ebfc7SToomas Soome     return(r);
5300c65ebfc7SToomas Soome }
5301c65ebfc7SToomas Soome 
GetCacheGroup(mDNS * const m,const mDNSu32 slot,const ResourceRecord * const rr)5302c65ebfc7SToomas Soome mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
5303c65ebfc7SToomas Soome {
5304c65ebfc7SToomas Soome     mDNSu16 namelen = DomainNameLength(rr->name);
5305c65ebfc7SToomas Soome     CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
5306c65ebfc7SToomas Soome     if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
5307c65ebfc7SToomas Soome     cg->next         = m->rrcache_hash[slot];
5308c65ebfc7SToomas Soome     cg->namehash     = rr->namehash;
5309c65ebfc7SToomas Soome     cg->members      = mDNSNULL;
5310c65ebfc7SToomas Soome     cg->rrcache_tail = &cg->members;
5311c65ebfc7SToomas Soome     if (namelen > sizeof(cg->namestorage))
5312*472cd20dSToomas Soome         cg->name = (domainname *) mDNSPlatformMemAllocate(namelen);
5313c65ebfc7SToomas Soome     else
5314c65ebfc7SToomas Soome         cg->name = (domainname*)cg->namestorage;
5315c65ebfc7SToomas Soome     if (!cg->name)
5316c65ebfc7SToomas Soome     {
5317c65ebfc7SToomas Soome         LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
5318c65ebfc7SToomas Soome         ReleaseCacheEntity(m, (CacheEntity*)cg);
5319c65ebfc7SToomas Soome         return(mDNSNULL);
5320c65ebfc7SToomas Soome     }
5321c65ebfc7SToomas Soome     AssignDomainName(cg->name, rr->name);
5322c65ebfc7SToomas Soome 
5323c65ebfc7SToomas Soome     if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
5324c65ebfc7SToomas Soome     m->rrcache_hash[slot] = cg;
5325c65ebfc7SToomas Soome     if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
5326c65ebfc7SToomas Soome 
5327c65ebfc7SToomas Soome     return(cg);
5328c65ebfc7SToomas Soome }
5329c65ebfc7SToomas Soome 
mDNS_PurgeCacheResourceRecord(mDNS * const m,CacheRecord * rr)5330c65ebfc7SToomas Soome mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
5331c65ebfc7SToomas Soome {
5332c65ebfc7SToomas Soome     mDNS_CheckLock(m);
5333c65ebfc7SToomas Soome 
5334c65ebfc7SToomas Soome     // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5335c65ebfc7SToomas Soome     // a positive answer using an expired record (e.g. from an interface that has gone away).
5336c65ebfc7SToomas Soome     // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5337c65ebfc7SToomas Soome     // summary deletion without giving the proper callback to any questions that are monitoring it.
5338c65ebfc7SToomas Soome     // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5339c65ebfc7SToomas Soome     rr->TimeRcvd          = m->timenow - mDNSPlatformOneSecond * 60;
5340c65ebfc7SToomas Soome     rr->UnansweredQueries = MaxUnansweredQueries;
5341c65ebfc7SToomas Soome     rr->resrec.rroriginalttl     = 0;
5342c65ebfc7SToomas Soome     SetNextCacheCheckTimeForRecord(m, rr);
5343c65ebfc7SToomas Soome }
5344c65ebfc7SToomas Soome 
mDNS_TimeNow(const mDNS * const m)5345c65ebfc7SToomas Soome mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
5346c65ebfc7SToomas Soome {
5347c65ebfc7SToomas Soome     mDNSs32 time;
5348c65ebfc7SToomas Soome     mDNSPlatformLock(m);
5349c65ebfc7SToomas Soome     if (m->mDNS_busy)
5350c65ebfc7SToomas Soome     {
5351c65ebfc7SToomas Soome         LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5352c65ebfc7SToomas Soome         if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
5353c65ebfc7SToomas Soome     }
5354c65ebfc7SToomas Soome 
5355c65ebfc7SToomas Soome     if (m->timenow) time = m->timenow;
5356c65ebfc7SToomas Soome     else time = mDNS_TimeNow_NoLock(m);
5357c65ebfc7SToomas Soome     mDNSPlatformUnlock(m);
5358c65ebfc7SToomas Soome     return(time);
5359c65ebfc7SToomas Soome }
5360c65ebfc7SToomas Soome 
5361c65ebfc7SToomas Soome // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5362c65ebfc7SToomas Soome // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5363c65ebfc7SToomas Soome // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5364c65ebfc7SToomas Soome #define SetSPSProxyListChanged(X) do { \
5365c65ebfc7SToomas Soome         if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5366c65ebfc7SToomas Soome         m->SPSProxyListChanged = (X); } while(0)
5367c65ebfc7SToomas Soome 
5368c65ebfc7SToomas Soome // Called from mDNS_Execute() to expire stale proxy records
CheckProxyRecords(mDNS * const m,AuthRecord * list)5369c65ebfc7SToomas Soome mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
5370c65ebfc7SToomas Soome {
5371c65ebfc7SToomas Soome     m->CurrentRecord = list;
5372c65ebfc7SToomas Soome     while (m->CurrentRecord)
5373c65ebfc7SToomas Soome     {
5374c65ebfc7SToomas Soome         AuthRecord *rr = m->CurrentRecord;
5375c65ebfc7SToomas Soome         if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
5376c65ebfc7SToomas Soome         {
5377c65ebfc7SToomas Soome             // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5378c65ebfc7SToomas Soome             // so we need to cease proxying for *all* records we may have, expired or not.
5379c65ebfc7SToomas Soome             if (m->SPSSocket && m->timenow - rr->TimeExpire < 0)    // If proxy record not expired yet, update m->NextScheduledSPS
5380c65ebfc7SToomas Soome             {
5381c65ebfc7SToomas Soome                 if (m->NextScheduledSPS - rr->TimeExpire > 0)
5382c65ebfc7SToomas Soome                     m->NextScheduledSPS = rr->TimeExpire;
5383c65ebfc7SToomas Soome             }
5384c65ebfc7SToomas Soome             else                                                    // else proxy record expired, so remove it
5385c65ebfc7SToomas Soome             {
5386c65ebfc7SToomas Soome                 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5387c65ebfc7SToomas Soome                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
5388c65ebfc7SToomas Soome                 SetSPSProxyListChanged(rr->resrec.InterfaceID);
5389c65ebfc7SToomas Soome                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5390c65ebfc7SToomas Soome                 // Don't touch rr after this -- memory may have been free'd
5391c65ebfc7SToomas Soome             }
5392c65ebfc7SToomas Soome         }
5393c65ebfc7SToomas Soome         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5394c65ebfc7SToomas Soome         // new records could have been added to the end of the list as a result of that call.
5395c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5396c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
5397c65ebfc7SToomas Soome     }
5398c65ebfc7SToomas Soome }
5399c65ebfc7SToomas Soome 
CheckRmvEventsForLocalRecords(mDNS * const m)5400c65ebfc7SToomas Soome mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5401c65ebfc7SToomas Soome {
5402c65ebfc7SToomas Soome     while (m->CurrentRecord)
5403c65ebfc7SToomas Soome     {
5404c65ebfc7SToomas Soome         AuthRecord *rr = m->CurrentRecord;
5405c65ebfc7SToomas Soome         if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5406c65ebfc7SToomas Soome         {
5407c65ebfc7SToomas Soome             debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5408c65ebfc7SToomas Soome             rr->resrec.RecordType = kDNSRecordTypeShared;
54093b436d06SToomas Soome             AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv);
5410c65ebfc7SToomas Soome             if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5411c65ebfc7SToomas Soome             {
5412c65ebfc7SToomas Soome                 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5413c65ebfc7SToomas Soome                 rr->AnsweredLocalQ = mDNSfalse;
5414c65ebfc7SToomas Soome                 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5415c65ebfc7SToomas Soome                 // For LocalOnly records, we don't do that and hence we need to do that here.
5416c65ebfc7SToomas Soome                 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5417c65ebfc7SToomas Soome             }
5418c65ebfc7SToomas Soome         }
5419c65ebfc7SToomas Soome         if (m->CurrentRecord == rr)     // If m->CurrentRecord was not auto-advanced, do it ourselves now
5420c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
5421c65ebfc7SToomas Soome     }
5422c65ebfc7SToomas Soome }
5423c65ebfc7SToomas Soome 
TimeoutQuestions_internal(mDNS * const m,DNSQuestion * questions,mDNSInterfaceID InterfaceID)5424c65ebfc7SToomas Soome mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID)
5425c65ebfc7SToomas Soome {
5426c65ebfc7SToomas Soome     if (m->CurrentQuestion)
5427c65ebfc7SToomas Soome         LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5428c65ebfc7SToomas Soome                DNSTypeName(m->CurrentQuestion->qtype));
5429c65ebfc7SToomas Soome     m->CurrentQuestion = questions;
5430c65ebfc7SToomas Soome     while (m->CurrentQuestion)
5431c65ebfc7SToomas Soome     {
5432c65ebfc7SToomas Soome         DNSQuestion *const q = m->CurrentQuestion;
5433c65ebfc7SToomas Soome         if (q->StopTime)
5434c65ebfc7SToomas Soome         {
5435c65ebfc7SToomas Soome             if (!q->TimeoutQuestion)
5436c65ebfc7SToomas Soome                 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5437c65ebfc7SToomas Soome 
5438c65ebfc7SToomas Soome             if (m->timenow - q->StopTime >= 0)
5439c65ebfc7SToomas Soome             {
5440c65ebfc7SToomas Soome                 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5441c65ebfc7SToomas Soome                 q->LOAddressAnswers = 0; // unset since timing out the question
5442c65ebfc7SToomas Soome                 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse);
5443c65ebfc7SToomas Soome                 if (m->CurrentQuestion == q) q->StopTime = 0;
5444c65ebfc7SToomas Soome             }
5445c65ebfc7SToomas Soome             else
5446c65ebfc7SToomas Soome             {
5447c65ebfc7SToomas Soome                 if (m->NextScheduledStopTime - q->StopTime > 0)
5448c65ebfc7SToomas Soome                     m->NextScheduledStopTime = q->StopTime;
5449c65ebfc7SToomas Soome             }
5450c65ebfc7SToomas Soome         }
5451c65ebfc7SToomas Soome         // If m->CurrentQuestion wasn't modified out from under us, advance it now
5452c65ebfc7SToomas Soome         // We can't do this at the start of the loop because GenerateNegativeResponse
5453c65ebfc7SToomas Soome         // depends on having m->CurrentQuestion point to the right question
5454c65ebfc7SToomas Soome         if (m->CurrentQuestion == q)
5455c65ebfc7SToomas Soome             m->CurrentQuestion = q->next;
5456c65ebfc7SToomas Soome     }
5457c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
5458c65ebfc7SToomas Soome }
5459c65ebfc7SToomas Soome 
TimeoutQuestions(mDNS * const m)5460c65ebfc7SToomas Soome mDNSlocal void TimeoutQuestions(mDNS *const m)
5461c65ebfc7SToomas Soome {
5462c65ebfc7SToomas Soome     m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future
5463c65ebfc7SToomas Soome     TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any);
5464c65ebfc7SToomas Soome     TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly);
5465c65ebfc7SToomas Soome }
5466c65ebfc7SToomas Soome 
mDNSCoreFreeProxyRR(mDNS * const m)5467c65ebfc7SToomas Soome mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5468c65ebfc7SToomas Soome {
5469c65ebfc7SToomas Soome     AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5470c65ebfc7SToomas Soome     LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5471c65ebfc7SToomas Soome     while (rrPtr)
5472c65ebfc7SToomas Soome     {
5473c65ebfc7SToomas Soome         rrNext = rrPtr->next;
5474c65ebfc7SToomas Soome         mDNSPlatformMemFree(rrPtr);
5475c65ebfc7SToomas Soome         rrPtr  = rrNext;
5476c65ebfc7SToomas Soome     }
5477c65ebfc7SToomas Soome     m->SPSRRSet = mDNSNULL;
5478c65ebfc7SToomas Soome }
5479c65ebfc7SToomas Soome 
mDNS_Execute(mDNS * const m)5480c65ebfc7SToomas Soome mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5481c65ebfc7SToomas Soome {
5482c65ebfc7SToomas Soome     mDNS_Lock(m);   // Must grab lock before trying to read m->timenow
5483c65ebfc7SToomas Soome 
5484c65ebfc7SToomas Soome     if (m->timenow - m->NextScheduledEvent >= 0)
5485c65ebfc7SToomas Soome     {
5486c65ebfc7SToomas Soome         int i;
5487c65ebfc7SToomas Soome         AuthRecord *head, *tail;
5488c65ebfc7SToomas Soome         mDNSu32 slot;
5489c65ebfc7SToomas Soome         AuthGroup *ag;
5490c65ebfc7SToomas Soome 
5491c65ebfc7SToomas Soome         verbosedebugf("mDNS_Execute");
5492c65ebfc7SToomas Soome 
5493c65ebfc7SToomas Soome         if (m->CurrentQuestion)
5494c65ebfc7SToomas Soome             LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5495c65ebfc7SToomas Soome                    m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5496c65ebfc7SToomas Soome 
5497c65ebfc7SToomas Soome         if (m->CurrentRecord)
5498c65ebfc7SToomas Soome             LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5499c65ebfc7SToomas Soome 
5500c65ebfc7SToomas Soome         // 1. If we're past the probe suppression time, we can clear it
5501c65ebfc7SToomas Soome         if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5502c65ebfc7SToomas Soome 
5503c65ebfc7SToomas Soome         // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5504c65ebfc7SToomas Soome         if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5505c65ebfc7SToomas Soome 
5506c65ebfc7SToomas Soome         // 3. Purge our cache of stale old records
5507c65ebfc7SToomas Soome         if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5508c65ebfc7SToomas Soome         {
5509c65ebfc7SToomas Soome             mDNSu32 numchecked = 0;
5510c65ebfc7SToomas Soome             m->NextCacheCheck = m->timenow + FutureTime;
5511c65ebfc7SToomas Soome             for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5512c65ebfc7SToomas Soome             {
5513c65ebfc7SToomas Soome                 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5514c65ebfc7SToomas Soome                 {
5515c65ebfc7SToomas Soome                     CacheGroup **cp = &m->rrcache_hash[slot];
5516c65ebfc7SToomas Soome                     m->rrcache_nextcheck[slot] = m->timenow + FutureTime;
5517c65ebfc7SToomas Soome                     while (*cp)
5518c65ebfc7SToomas Soome                     {
5519c65ebfc7SToomas Soome                         debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5520c65ebfc7SToomas Soome                         numchecked++;
5521c65ebfc7SToomas Soome                         CheckCacheExpiration(m, slot, *cp);
5522c65ebfc7SToomas Soome                         if ((*cp)->members) cp=&(*cp)->next;
5523c65ebfc7SToomas Soome                         else ReleaseCacheGroup(m, cp);
5524c65ebfc7SToomas Soome                     }
5525c65ebfc7SToomas Soome                 }
5526c65ebfc7SToomas Soome                 // Even if we didn't need to actually check this slot yet, still need to
5527c65ebfc7SToomas Soome                 // factor its nextcheck time into our overall NextCacheCheck value
5528c65ebfc7SToomas Soome                 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5529c65ebfc7SToomas Soome                     m->NextCacheCheck = m->rrcache_nextcheck[slot];
5530c65ebfc7SToomas Soome             }
5531c65ebfc7SToomas Soome             debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5532c65ebfc7SToomas Soome         }
5533c65ebfc7SToomas Soome 
5534c65ebfc7SToomas Soome         if (m->timenow - m->NextScheduledSPS >= 0)
5535c65ebfc7SToomas Soome         {
5536c65ebfc7SToomas Soome             m->NextScheduledSPS = m->timenow + FutureTime;
5537c65ebfc7SToomas Soome             CheckProxyRecords(m, m->DuplicateRecords);  // Clear m->DuplicateRecords first, then m->ResourceRecords
5538c65ebfc7SToomas Soome             CheckProxyRecords(m, m->ResourceRecords);
5539c65ebfc7SToomas Soome         }
5540c65ebfc7SToomas Soome 
5541c65ebfc7SToomas Soome         SetSPSProxyListChanged(mDNSNULL);       // Perform any deferred BPF reconfiguration now
5542c65ebfc7SToomas Soome 
5543c65ebfc7SToomas Soome         // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5544c65ebfc7SToomas Soome         // as records could have expired during that check
5545c65ebfc7SToomas Soome         if (m->timenow - m->NextScheduledKA >= 0)
5546c65ebfc7SToomas Soome         {
5547c65ebfc7SToomas Soome             m->NextScheduledKA = m->timenow + FutureTime;
5548c65ebfc7SToomas Soome             mDNS_SendKeepalives(m);
5549c65ebfc7SToomas Soome         }
5550c65ebfc7SToomas Soome 
5551*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5552c65ebfc7SToomas Soome         if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0))
5553c65ebfc7SToomas Soome         {
5554c65ebfc7SToomas Soome             // Schedule immediate network change processing to leave the multicast group
5555c65ebfc7SToomas Soome             // since the delay time has expired since the previous active registration or query.
5556c65ebfc7SToomas Soome             m->NetworkChanged = m->timenow;
5557c65ebfc7SToomas Soome             m->NextBonjourDisableTime = 0;
5558c65ebfc7SToomas Soome             m->BonjourEnabled = 0;
5559c65ebfc7SToomas Soome 
5560c65ebfc7SToomas Soome             LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5561c65ebfc7SToomas Soome         }
5562*472cd20dSToomas Soome #endif
5563c65ebfc7SToomas Soome 
5564c65ebfc7SToomas Soome         // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5565c65ebfc7SToomas Soome         if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5566c65ebfc7SToomas Soome         {
5567c65ebfc7SToomas Soome             m->AnnounceOwner = 0;
5568c65ebfc7SToomas Soome         }
5569c65ebfc7SToomas Soome 
5570c65ebfc7SToomas Soome         if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5571c65ebfc7SToomas Soome         {
5572c65ebfc7SToomas Soome             m->DelaySleep = 0;
5573c65ebfc7SToomas Soome             if (m->SleepState == SleepState_Transferring)
5574c65ebfc7SToomas Soome             {
5575c65ebfc7SToomas Soome                 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5576c65ebfc7SToomas Soome                 BeginSleepProcessing(m);
5577c65ebfc7SToomas Soome             }
5578c65ebfc7SToomas Soome         }
5579c65ebfc7SToomas Soome 
5580c65ebfc7SToomas Soome         // 4. See if we can answer any of our new local questions from the cache
5581c65ebfc7SToomas Soome         for (i=0; m->NewQuestions && i<1000; i++)
5582c65ebfc7SToomas Soome         {
5583c65ebfc7SToomas Soome             if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5584c65ebfc7SToomas Soome             AnswerNewQuestion(m);
5585c65ebfc7SToomas Soome         }
5586c65ebfc7SToomas Soome         if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5587c65ebfc7SToomas Soome 
5588c65ebfc7SToomas Soome         // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5589c65ebfc7SToomas Soome         // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5590c65ebfc7SToomas Soome         for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5591c65ebfc7SToomas Soome         {
5592c65ebfc7SToomas Soome             m->LocalRemoveEvents = mDNSfalse;
5593c65ebfc7SToomas Soome             m->CurrentRecord = m->ResourceRecords;
5594c65ebfc7SToomas Soome             CheckRmvEventsForLocalRecords(m);
5595c65ebfc7SToomas Soome             // Walk the LocalOnly records and deliver the RMV events
5596c65ebfc7SToomas Soome             for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5597c65ebfc7SToomas Soome                 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5598c65ebfc7SToomas Soome                 {
5599c65ebfc7SToomas Soome                     m->CurrentRecord = ag->members;
5600c65ebfc7SToomas Soome                     if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5601c65ebfc7SToomas Soome                 }
5602c65ebfc7SToomas Soome         }
5603c65ebfc7SToomas Soome 
5604c65ebfc7SToomas Soome         if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5605c65ebfc7SToomas Soome 
5606c65ebfc7SToomas Soome         for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5607c65ebfc7SToomas Soome         if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5608c65ebfc7SToomas Soome 
5609c65ebfc7SToomas Soome         head = tail = mDNSNULL;
5610c65ebfc7SToomas Soome         for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5611c65ebfc7SToomas Soome         {
5612c65ebfc7SToomas Soome             AuthRecord *rr = m->NewLocalRecords;
5613c65ebfc7SToomas Soome             m->NewLocalRecords = m->NewLocalRecords->next;
5614c65ebfc7SToomas Soome             if (LocalRecordReady(rr))
5615c65ebfc7SToomas Soome             {
5616c65ebfc7SToomas Soome                 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
56173b436d06SToomas Soome                 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5618c65ebfc7SToomas Soome             }
5619c65ebfc7SToomas Soome             else if (!rr->next)
5620c65ebfc7SToomas Soome             {
5621c65ebfc7SToomas Soome                 // If we have just one record that is not ready, we don't have to unlink and
5622c65ebfc7SToomas Soome                 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5623c65ebfc7SToomas Soome                 // terminate and set the NewLocalRecords to rr.
5624c65ebfc7SToomas Soome                 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5625c65ebfc7SToomas Soome                 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5626c65ebfc7SToomas Soome                     LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5627c65ebfc7SToomas Soome 
5628c65ebfc7SToomas Soome                 head = rr;
5629c65ebfc7SToomas Soome             }
5630c65ebfc7SToomas Soome             else
5631c65ebfc7SToomas Soome             {
5632c65ebfc7SToomas Soome                 AuthRecord **p = &m->ResourceRecords;   // Find this record in our list of active records
5633c65ebfc7SToomas Soome                 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5634c65ebfc7SToomas Soome                 // if this is the first record we are skipping, move to the end of the list.
5635c65ebfc7SToomas Soome                 // if we have already skipped records before, append it at the end.
5636c65ebfc7SToomas Soome                 while (*p && *p != rr) p=&(*p)->next;
5637c65ebfc7SToomas Soome                 if (*p) *p = rr->next;                  // Cut this record from the list
5638c65ebfc7SToomas Soome                 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5639c65ebfc7SToomas Soome                 if (!head)
5640c65ebfc7SToomas Soome                 {
5641c65ebfc7SToomas Soome                     while (*p) p=&(*p)->next;
5642c65ebfc7SToomas Soome                     *p = rr;
5643c65ebfc7SToomas Soome                     head = tail = rr;
5644c65ebfc7SToomas Soome                 }
5645c65ebfc7SToomas Soome                 else
5646c65ebfc7SToomas Soome                 {
5647c65ebfc7SToomas Soome                     tail->next = rr;
5648c65ebfc7SToomas Soome                     tail = rr;
5649c65ebfc7SToomas Soome                 }
5650c65ebfc7SToomas Soome                 rr->next = mDNSNULL;
5651c65ebfc7SToomas Soome             }
5652c65ebfc7SToomas Soome         }
5653c65ebfc7SToomas Soome         m->NewLocalRecords = head;
5654c65ebfc7SToomas Soome         debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5655c65ebfc7SToomas Soome 
5656c65ebfc7SToomas Soome         if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5657c65ebfc7SToomas Soome 
5658c65ebfc7SToomas Soome         // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5659c65ebfc7SToomas Soome         // to our local questions
5660c65ebfc7SToomas Soome         if (m->NewLocalOnlyRecords)
5661c65ebfc7SToomas Soome         {
5662c65ebfc7SToomas Soome             m->NewLocalOnlyRecords = mDNSfalse;
5663c65ebfc7SToomas Soome             for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5664*472cd20dSToomas Soome             {
5665c65ebfc7SToomas Soome                 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5666c65ebfc7SToomas Soome                 {
5667c65ebfc7SToomas Soome                     for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5668c65ebfc7SToomas Soome                     {
5669c65ebfc7SToomas Soome                         AuthRecord *rr = ag->NewLocalOnlyRecords;
5670c65ebfc7SToomas Soome                         ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5671c65ebfc7SToomas Soome                         // LocalOnly records should always be ready as they never probe
5672c65ebfc7SToomas Soome                         if (LocalRecordReady(rr))
5673c65ebfc7SToomas Soome                         {
5674c65ebfc7SToomas Soome                             debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
56753b436d06SToomas Soome                             AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5676c65ebfc7SToomas Soome                         }
5677c65ebfc7SToomas Soome                         else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5678c65ebfc7SToomas Soome                     }
5679c65ebfc7SToomas Soome                     // We limit about 100 per AuthGroup that can be serviced at a time
5680c65ebfc7SToomas Soome                     if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5681c65ebfc7SToomas Soome                 }
5682c65ebfc7SToomas Soome             }
5683*472cd20dSToomas Soome         }
5684c65ebfc7SToomas Soome 
5685c65ebfc7SToomas Soome         // 5. See what packets we need to send
5686c65ebfc7SToomas Soome         if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5687c65ebfc7SToomas Soome             DiscardDeregistrations(m);
5688c65ebfc7SToomas Soome         if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5689c65ebfc7SToomas Soome         {
5690c65ebfc7SToomas Soome             // If the platform code is ready, and we're not suppressing packet generation right now
5691c65ebfc7SToomas Soome             // then send our responses, probes, and questions.
5692c65ebfc7SToomas Soome             // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5693c65ebfc7SToomas Soome             // We send queries next, because there might be final-stage probes that complete their probing here, causing
5694c65ebfc7SToomas Soome             // them to advance to announcing state, and we want those to be included in any announcements we send out.
5695c65ebfc7SToomas Soome             // Finally, we send responses, including the previously mentioned records that just completed probing.
5696c65ebfc7SToomas Soome             m->SuppressSending = 0;
5697c65ebfc7SToomas Soome 
5698c65ebfc7SToomas Soome             // 6. Send Query packets. This may cause some probing records to advance to announcing state
5699c65ebfc7SToomas Soome             if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5700c65ebfc7SToomas Soome             if (m->timenow - m->NextScheduledQuery >= 0)
5701c65ebfc7SToomas Soome             {
5702c65ebfc7SToomas Soome                 DNSQuestion *q;
5703c65ebfc7SToomas Soome                 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5704c65ebfc7SToomas Soome                        m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5705c65ebfc7SToomas Soome                 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5706c65ebfc7SToomas Soome                 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5707c65ebfc7SToomas Soome                     if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5708c65ebfc7SToomas Soome                         LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5709c65ebfc7SToomas Soome             }
5710c65ebfc7SToomas Soome             if (m->timenow - m->NextScheduledProbe >= 0)
5711c65ebfc7SToomas Soome             {
5712c65ebfc7SToomas Soome                 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5713c65ebfc7SToomas Soome                        m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5714c65ebfc7SToomas Soome                 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5715c65ebfc7SToomas Soome             }
5716c65ebfc7SToomas Soome 
5717c65ebfc7SToomas Soome             // 7. Send Response packets, including probing records just advanced to announcing state
5718c65ebfc7SToomas Soome             if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5719c65ebfc7SToomas Soome             if (m->timenow - m->NextScheduledResponse >= 0)
5720c65ebfc7SToomas Soome             {
5721c65ebfc7SToomas Soome                 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5722c65ebfc7SToomas Soome                 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5723c65ebfc7SToomas Soome             }
5724c65ebfc7SToomas Soome         }
5725c65ebfc7SToomas Soome 
5726c65ebfc7SToomas Soome         // Clear RandomDelay values, ready to pick a new different value next time
5727c65ebfc7SToomas Soome         m->RandomQueryDelay     = 0;
5728c65ebfc7SToomas Soome         m->RandomReconfirmDelay = 0;
5729c65ebfc7SToomas Soome 
5730c65ebfc7SToomas Soome         // See if any questions (or local-only questions) have timed out
5731c65ebfc7SToomas Soome         if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5732c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
5733c65ebfc7SToomas Soome         if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5734c65ebfc7SToomas Soome         if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5735c65ebfc7SToomas Soome         if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5736c65ebfc7SToomas Soome #endif
5737c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5738c65ebfc7SToomas Soome         extern void serviceBLE();
5739c65ebfc7SToomas Soome         if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE();
5740c65ebfc7SToomas Soome #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5741c65ebfc7SToomas Soome     }
5742c65ebfc7SToomas Soome 
5743c65ebfc7SToomas Soome     // Note about multi-threaded systems:
5744c65ebfc7SToomas Soome     // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5745c65ebfc7SToomas Soome     // performing mDNS API operations that change our next scheduled event time.
5746c65ebfc7SToomas Soome     //
5747c65ebfc7SToomas Soome     // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5748c65ebfc7SToomas Soome     // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5749c65ebfc7SToomas Soome     // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5750c65ebfc7SToomas Soome     // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5751c65ebfc7SToomas Soome     // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5752c65ebfc7SToomas Soome     // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5753c65ebfc7SToomas Soome     // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5754c65ebfc7SToomas Soome     // without blocking. This avoids the race condition between the signal from the other thread arriving
5755c65ebfc7SToomas Soome     // just *before* or just *after* the main thread enters the blocking primitive.
5756c65ebfc7SToomas Soome     //
5757c65ebfc7SToomas Soome     // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5758c65ebfc7SToomas Soome     // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5759c65ebfc7SToomas Soome     // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5760c65ebfc7SToomas Soome     // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5761c65ebfc7SToomas Soome     // by the time it gets to the timer callback function).
5762c65ebfc7SToomas Soome 
5763c65ebfc7SToomas Soome     mDNS_Unlock(m);     // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5764c65ebfc7SToomas Soome     return(m->NextScheduledEvent);
5765c65ebfc7SToomas Soome }
5766c65ebfc7SToomas Soome 
5767c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
SuspendLLQs(mDNS * m)5768c65ebfc7SToomas Soome mDNSlocal void SuspendLLQs(mDNS *m)
5769c65ebfc7SToomas Soome {
5770c65ebfc7SToomas Soome     DNSQuestion *q;
5771c65ebfc7SToomas Soome     for (q = m->Questions; q; q = q->next)
5772c65ebfc7SToomas Soome         if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5773c65ebfc7SToomas Soome         { q->ReqLease = 0; sendLLQRefresh(m, q); }
5774c65ebfc7SToomas Soome }
5775c65ebfc7SToomas Soome #endif // UNICAST_DISABLED
5776c65ebfc7SToomas Soome 
QuestionHasLocalAnswers(mDNS * const m,DNSQuestion * q)5777c65ebfc7SToomas Soome mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5778c65ebfc7SToomas Soome {
5779c65ebfc7SToomas Soome     AuthRecord *rr;
5780c65ebfc7SToomas Soome     AuthGroup *ag;
5781c65ebfc7SToomas Soome 
5782c65ebfc7SToomas Soome     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5783c65ebfc7SToomas Soome     if (ag)
5784c65ebfc7SToomas Soome     {
5785c65ebfc7SToomas Soome         for (rr = ag->members; rr; rr=rr->next)
5786c65ebfc7SToomas Soome             // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5787c65ebfc7SToomas Soome             if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5788c65ebfc7SToomas Soome             {
5789c65ebfc7SToomas Soome                 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5790c65ebfc7SToomas Soome                 return mDNStrue;
5791c65ebfc7SToomas Soome             }
5792c65ebfc7SToomas Soome     }
5793c65ebfc7SToomas Soome     return mDNSfalse;
5794c65ebfc7SToomas Soome }
5795c65ebfc7SToomas Soome 
5796c65ebfc7SToomas Soome // ActivateUnicastQuery() is called from three places:
5797c65ebfc7SToomas Soome // 1. When a new question is created
5798c65ebfc7SToomas Soome // 2. On wake from sleep
5799c65ebfc7SToomas Soome // 3. When the DNS configuration changes
5800c65ebfc7SToomas Soome // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5801c65ebfc7SToomas Soome // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
ActivateUnicastQuery(mDNS * const m,DNSQuestion * const question,mDNSBool ScheduleImmediately)5802c65ebfc7SToomas Soome mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5803c65ebfc7SToomas Soome {
5804c65ebfc7SToomas Soome     if (!question->DuplicateOf)
5805c65ebfc7SToomas Soome     {
5806*472cd20dSToomas Soome         debugf("ActivateUnicastQuery: %##s %s%s",
5807*472cd20dSToomas Soome                question->qname.c, DNSTypeName(question->qtype), ScheduleImmediately ? " ScheduleImmediately" : "");
5808c65ebfc7SToomas Soome         question->CNAMEReferrals = 0;
5809c65ebfc7SToomas Soome         if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5810c65ebfc7SToomas Soome         if (question->LongLived)
5811c65ebfc7SToomas Soome         {
5812*472cd20dSToomas Soome             question->state = LLQ_Init;
5813c65ebfc7SToomas Soome             question->id = zeroOpaque64;
5814c65ebfc7SToomas Soome             question->servPort = zeroIPPort;
5815c65ebfc7SToomas Soome             if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5816c65ebfc7SToomas Soome         }
5817c65ebfc7SToomas Soome         // If the question has local answers, then we don't want answers from outside
5818c65ebfc7SToomas Soome         if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5819c65ebfc7SToomas Soome         {
5820c65ebfc7SToomas Soome             question->ThisQInterval = InitialQuestionInterval;
5821c65ebfc7SToomas Soome             question->LastQTime     = m->timenow - question->ThisQInterval;
5822c65ebfc7SToomas Soome             SetNextQueryTime(m, question);
5823c65ebfc7SToomas Soome         }
5824c65ebfc7SToomas Soome     }
5825c65ebfc7SToomas Soome }
5826c65ebfc7SToomas Soome 
5827c65ebfc7SToomas Soome // Caller should hold the lock
mDNSCoreRestartAddressQueries(mDNS * const m,mDNSBool SearchDomainsChanged,FlushCache flushCacheRecords,CallbackBeforeStartQuery BeforeStartCallback,void * context)5828c65ebfc7SToomas Soome mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5829c65ebfc7SToomas Soome                                               CallbackBeforeStartQuery BeforeStartCallback, void *context)
5830c65ebfc7SToomas Soome {
5831c65ebfc7SToomas Soome     DNSQuestion *q;
5832c65ebfc7SToomas Soome     DNSQuestion *restart = mDNSNULL;
5833c65ebfc7SToomas Soome 
5834c65ebfc7SToomas Soome     mDNS_CheckLock(m);
5835c65ebfc7SToomas Soome 
5836c65ebfc7SToomas Soome     // 1. Flush the cache records
5837c65ebfc7SToomas Soome     if (flushCacheRecords) flushCacheRecords(m);
5838c65ebfc7SToomas Soome 
5839c65ebfc7SToomas Soome     // 2. Even though we may have purged the cache records above, before it can generate RMV event
5840c65ebfc7SToomas Soome     // we are going to stop the question. Hence we need to deliver the RMV event before we
5841c65ebfc7SToomas Soome     // stop the question.
5842c65ebfc7SToomas Soome     //
5843c65ebfc7SToomas Soome     // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5844c65ebfc7SToomas Soome     // application callback can potentially stop the current question (detected by CurrentQuestion) or
5845c65ebfc7SToomas Soome     // *any* other question which could be the next one that we may process here. RestartQuestion
5846c65ebfc7SToomas Soome     // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5847c65ebfc7SToomas Soome     // if the "next" question is stopped while the CurrentQuestion is stopped
5848c65ebfc7SToomas Soome 
5849c65ebfc7SToomas Soome     if (m->RestartQuestion)
5850c65ebfc7SToomas Soome         LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5851c65ebfc7SToomas Soome                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5852c65ebfc7SToomas Soome 
5853c65ebfc7SToomas Soome     m->RestartQuestion = m->Questions;
5854c65ebfc7SToomas Soome     while (m->RestartQuestion)
5855c65ebfc7SToomas Soome     {
5856c65ebfc7SToomas Soome         q = m->RestartQuestion;
5857c65ebfc7SToomas Soome         m->RestartQuestion = q->next;
5858c65ebfc7SToomas Soome         // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5859c65ebfc7SToomas Soome         // question)  through their "nta" pointer. Normally when the original query stops, it stops the
5860c65ebfc7SToomas Soome         // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5861c65ebfc7SToomas Soome         // question followed by the original query that refers to this GetZoneData question, we will end up
5862c65ebfc7SToomas Soome         // freeing the GetZoneData question and then start the "freed" question at the end.
5863c65ebfc7SToomas Soome 
5864c65ebfc7SToomas Soome         if (IsGetZoneDataQuestion(q))
5865c65ebfc7SToomas Soome         {
5866c65ebfc7SToomas Soome             DNSQuestion *refq = q->next;
5867c65ebfc7SToomas Soome             LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5868c65ebfc7SToomas Soome             // debug stuff, we just try to find the referencing question and don't do much with it
5869c65ebfc7SToomas Soome             while (refq)
5870c65ebfc7SToomas Soome             {
5871c65ebfc7SToomas Soome                 if (q == &refq->nta->question)
5872c65ebfc7SToomas Soome                 {
5873c65ebfc7SToomas Soome                     LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5874c65ebfc7SToomas Soome                 }
5875c65ebfc7SToomas Soome                 refq = refq->next;
5876c65ebfc7SToomas Soome             }
5877c65ebfc7SToomas Soome             continue;
5878c65ebfc7SToomas Soome         }
5879c65ebfc7SToomas Soome 
5880c65ebfc7SToomas Soome         // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5881c65ebfc7SToomas Soome         if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5882c65ebfc7SToomas Soome 
5883c65ebfc7SToomas Soome         // If the search domains did not change, then we restart all the queries. Otherwise, only
5884c65ebfc7SToomas Soome         // for queries for which we "might" have appended search domains ("might" because we may
5885c65ebfc7SToomas Soome         // find results before we apply search domains even though AppendSearchDomains is set to 1)
5886c65ebfc7SToomas Soome         if (!SearchDomainsChanged || q->AppendSearchDomains)
5887c65ebfc7SToomas Soome         {
5888c65ebfc7SToomas Soome             // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5889c65ebfc7SToomas Soome             // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5890c65ebfc7SToomas Soome             // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5891c65ebfc7SToomas Soome             // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5892c65ebfc7SToomas Soome             // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5893c65ebfc7SToomas Soome             // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5894c65ebfc7SToomas Soome             // for the original query using these cache entries as ADDs were never delivered using these cache
5895c65ebfc7SToomas Soome             // entries and hence this order is needed.
5896c65ebfc7SToomas Soome 
5897c65ebfc7SToomas Soome             // If the query is suppressed, the RMV events won't be delivered
5898c65ebfc7SToomas Soome             if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5899c65ebfc7SToomas Soome 
5900*472cd20dSToomas Soome             // Suppressed status does not affect questions that are answered using local records
5901c65ebfc7SToomas Soome             if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5902c65ebfc7SToomas Soome 
5903*472cd20dSToomas Soome             LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q,
5904*472cd20dSToomas Soome                     q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains);
5905c65ebfc7SToomas Soome             mDNS_StopQuery_internal(m, q);
5906*472cd20dSToomas Soome             if (q->ResetHandler) q->ResetHandler(q);
5907c65ebfc7SToomas Soome             q->next = restart;
5908c65ebfc7SToomas Soome             restart = q;
5909c65ebfc7SToomas Soome         }
5910c65ebfc7SToomas Soome     }
5911c65ebfc7SToomas Soome 
5912c65ebfc7SToomas Soome     // 3. Callback before we start the query
5913c65ebfc7SToomas Soome     if (BeforeStartCallback) BeforeStartCallback(m, context);
5914c65ebfc7SToomas Soome 
5915c65ebfc7SToomas Soome     // 4. Restart all the stopped queries
5916c65ebfc7SToomas Soome     while (restart)
5917c65ebfc7SToomas Soome     {
5918c65ebfc7SToomas Soome         q = restart;
5919c65ebfc7SToomas Soome         restart = restart->next;
5920c65ebfc7SToomas Soome         q->next = mDNSNULL;
5921c65ebfc7SToomas Soome         LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5922c65ebfc7SToomas Soome         mDNS_StartQuery_internal(m, q);
5923c65ebfc7SToomas Soome     }
5924c65ebfc7SToomas Soome }
5925c65ebfc7SToomas Soome 
mDNSCoreRestartQueries(mDNS * const m)5926c65ebfc7SToomas Soome mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5927c65ebfc7SToomas Soome {
5928c65ebfc7SToomas Soome     DNSQuestion *q;
5929c65ebfc7SToomas Soome 
5930c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
5931c65ebfc7SToomas Soome     // Retrigger all our uDNS questions
5932c65ebfc7SToomas Soome     if (m->CurrentQuestion)
5933c65ebfc7SToomas Soome         LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5934c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5935c65ebfc7SToomas Soome     m->CurrentQuestion = m->Questions;
5936c65ebfc7SToomas Soome     while (m->CurrentQuestion)
5937c65ebfc7SToomas Soome     {
5938c65ebfc7SToomas Soome         q = m->CurrentQuestion;
5939c65ebfc7SToomas Soome         m->CurrentQuestion = m->CurrentQuestion->next;
5940*472cd20dSToomas Soome         if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5941*472cd20dSToomas Soome         {
5942*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5943*472cd20dSToomas Soome             mdns_querier_forget(&q->querier);
5944*472cd20dSToomas Soome #endif
5945*472cd20dSToomas Soome             ActivateUnicastQuery(m, q, mDNStrue);
5946*472cd20dSToomas Soome         }
5947c65ebfc7SToomas Soome     }
5948c65ebfc7SToomas Soome #endif
5949c65ebfc7SToomas Soome 
5950c65ebfc7SToomas Soome     // Retrigger all our mDNS questions
5951c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next)                // Scan our list of questions
5952c65ebfc7SToomas Soome             mDNSCoreRestartQuestion(m, q);
5953c65ebfc7SToomas Soome }
5954c65ebfc7SToomas Soome 
5955c65ebfc7SToomas Soome // restart question if it's multicast and currently active
mDNSCoreRestartQuestion(mDNS * const m,DNSQuestion * q)5956c65ebfc7SToomas Soome mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5957c65ebfc7SToomas Soome {
5958c65ebfc7SToomas Soome     if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5959c65ebfc7SToomas Soome     {
5960c65ebfc7SToomas Soome         q->ThisQInterval    = InitialQuestionInterval;  // MUST be > zero for an active question
5961c65ebfc7SToomas Soome         q->RequestUnicast   = kDefaultRequestUnicastCount;
5962c65ebfc7SToomas Soome         q->LastQTime        = m->timenow - q->ThisQInterval;
5963c65ebfc7SToomas Soome         q->RecentAnswerPkts = 0;
5964c65ebfc7SToomas Soome         ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5965c65ebfc7SToomas Soome         m->NextScheduledQuery = m->timenow;
5966c65ebfc7SToomas Soome     }
5967c65ebfc7SToomas Soome }
5968c65ebfc7SToomas Soome 
5969c65ebfc7SToomas Soome // restart the probe/announce cycle for multicast record
mDNSCoreRestartRegistration(mDNS * const m,AuthRecord * rr,int announceCount)5970c65ebfc7SToomas Soome mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5971c65ebfc7SToomas Soome {
5972c65ebfc7SToomas Soome     if (!AuthRecord_uDNS(rr))
5973c65ebfc7SToomas Soome     {
5974c65ebfc7SToomas Soome         if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5975c65ebfc7SToomas Soome         rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5976c65ebfc7SToomas Soome 
5977c65ebfc7SToomas Soome         if (mDNS_KeepaliveRecord(&rr->resrec))
5978c65ebfc7SToomas Soome         {
5979c65ebfc7SToomas Soome             rr->AnnounceCount = 0; // Do not announce keepalive records
5980c65ebfc7SToomas Soome         }
5981c65ebfc7SToomas Soome         else
5982c65ebfc7SToomas Soome         {
5983c65ebfc7SToomas Soome             // announceCount < 0 indicates default announce count should be used
5984c65ebfc7SToomas Soome             if (announceCount < 0)
5985c65ebfc7SToomas Soome                 announceCount = InitialAnnounceCount;
5986c65ebfc7SToomas Soome             if (rr->AnnounceCount < (mDNSu8)announceCount)
5987c65ebfc7SToomas Soome                 rr->AnnounceCount = (mDNSu8)announceCount;
5988c65ebfc7SToomas Soome         }
5989c65ebfc7SToomas Soome 
5990c65ebfc7SToomas Soome         rr->SendNSECNow    = mDNSNULL;
5991c65ebfc7SToomas Soome         InitializeLastAPTime(m, rr);
5992c65ebfc7SToomas Soome     }
5993c65ebfc7SToomas Soome }
5994c65ebfc7SToomas Soome 
5995c65ebfc7SToomas Soome // ***************************************************************************
5996c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
5997c65ebfc7SToomas Soome #pragma mark -
5998c65ebfc7SToomas Soome #pragma mark - Power Management (Sleep/Wake)
5999c65ebfc7SToomas Soome #endif
6000c65ebfc7SToomas Soome 
mDNS_UpdateAllowSleep(mDNS * const m)6001c65ebfc7SToomas Soome mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
6002c65ebfc7SToomas Soome {
6003c65ebfc7SToomas Soome #ifndef IDLESLEEPCONTROL_DISABLED
6004c65ebfc7SToomas Soome     mDNSBool allowSleep = mDNStrue;
6005c65ebfc7SToomas Soome     char reason[128];
6006c65ebfc7SToomas Soome 
6007c65ebfc7SToomas Soome     reason[0] = 0;
6008c65ebfc7SToomas Soome 
6009c65ebfc7SToomas Soome     if (m->SystemSleepOnlyIfWakeOnLAN)
6010c65ebfc7SToomas Soome     {
6011c65ebfc7SToomas Soome         // Don't sleep if we are a proxy for any services
6012c65ebfc7SToomas Soome         if (m->ProxyRecords)
6013c65ebfc7SToomas Soome         {
6014c65ebfc7SToomas Soome             allowSleep = mDNSfalse;
6015c65ebfc7SToomas Soome             mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
6016c65ebfc7SToomas Soome             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
6017c65ebfc7SToomas Soome         }
6018c65ebfc7SToomas Soome 
6019c65ebfc7SToomas Soome         if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
6020c65ebfc7SToomas Soome         {
6021c65ebfc7SToomas Soome             // Scan the list of active interfaces
6022c65ebfc7SToomas Soome             NetworkInterfaceInfo *intf;
6023c65ebfc7SToomas Soome             for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6024c65ebfc7SToomas Soome             {
6025c65ebfc7SToomas Soome                 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6026c65ebfc7SToomas Soome                 {
6027c65ebfc7SToomas Soome                     // Disallow sleep if this interface doesn't support NetWake
6028c65ebfc7SToomas Soome                     if (!intf->NetWake)
6029c65ebfc7SToomas Soome                     {
6030c65ebfc7SToomas Soome                         allowSleep = mDNSfalse;
6031c65ebfc7SToomas Soome                         mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
6032c65ebfc7SToomas Soome                         LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
6033c65ebfc7SToomas Soome                         break;
6034c65ebfc7SToomas Soome                     }
6035c65ebfc7SToomas Soome 
6036c65ebfc7SToomas Soome                     // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
6037c65ebfc7SToomas Soome                     // that will be offloaded. If not, we should prevent sleep.
6038c65ebfc7SToomas Soome                     // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
6039c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
6040c65ebfc7SToomas Soome                     if (!SupportsInNICProxy(intf))
6041c65ebfc7SToomas Soome #endif
6042c65ebfc7SToomas Soome                     {
6043c65ebfc7SToomas Soome                         // Disallow sleep if there is no sleep proxy server
6044c65ebfc7SToomas Soome                         const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
6045c65ebfc7SToomas Soome                         if ( cr == mDNSNULL)
6046c65ebfc7SToomas Soome                         {
6047c65ebfc7SToomas Soome                             allowSleep = mDNSfalse;
6048c65ebfc7SToomas Soome                             mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
6049c65ebfc7SToomas Soome                             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
6050c65ebfc7SToomas Soome                             break;
6051c65ebfc7SToomas Soome                         }
6052c65ebfc7SToomas Soome                         else if (m->SPSType != 0)
6053c65ebfc7SToomas Soome                         {
6054c65ebfc7SToomas Soome                             mDNSu32 mymetric = LocalSPSMetric(m);
6055c65ebfc7SToomas Soome                             mDNSu32 metric   = SPSMetric(cr->resrec.rdata->u.name.c);
6056c65ebfc7SToomas Soome                             if (metric >= mymetric)
6057c65ebfc7SToomas Soome                             {
6058c65ebfc7SToomas Soome                                 allowSleep = mDNSfalse;
6059c65ebfc7SToomas Soome                                 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
6060c65ebfc7SToomas Soome                                 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
6061c65ebfc7SToomas Soome                                 break;
6062c65ebfc7SToomas Soome                             }
6063c65ebfc7SToomas Soome                         }
6064c65ebfc7SToomas Soome                     }
6065c65ebfc7SToomas Soome                 }
6066c65ebfc7SToomas Soome             }
6067c65ebfc7SToomas Soome         }
6068c65ebfc7SToomas Soome     }
6069c65ebfc7SToomas Soome 
6070c65ebfc7SToomas Soome     // Call the platform code to enable/disable sleep
6071c65ebfc7SToomas Soome     mDNSPlatformSetAllowSleep(allowSleep, reason);
6072c65ebfc7SToomas Soome #else
6073c65ebfc7SToomas Soome     (void) m;
6074c65ebfc7SToomas Soome #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6075c65ebfc7SToomas Soome }
6076c65ebfc7SToomas Soome 
mDNSUpdateOkToSend(mDNS * const m,AuthRecord * rr,NetworkInterfaceInfo * const intf,mDNSu32 scopeid)6077c65ebfc7SToomas Soome mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
6078c65ebfc7SToomas Soome {
6079c65ebfc7SToomas Soome     // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6080c65ebfc7SToomas Soome     // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6081c65ebfc7SToomas Soome     // to send.
6082c65ebfc7SToomas Soome     if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
6083c65ebfc7SToomas Soome         m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
6084c65ebfc7SToomas Soome     {
6085c65ebfc7SToomas Soome         return mDNSfalse;
6086c65ebfc7SToomas Soome     }
6087c65ebfc7SToomas Soome 
6088c65ebfc7SToomas Soome     // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6089c65ebfc7SToomas Soome     // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6090c65ebfc7SToomas Soome     // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6091c65ebfc7SToomas Soome     // updateid and we should have returned from above.
6092c65ebfc7SToomas Soome     //
6093c65ebfc7SToomas Soome     // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6094c65ebfc7SToomas Soome     // platform function to extract the value from "intf" every time.
6095c65ebfc7SToomas Soome 
6096c65ebfc7SToomas Soome     if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6097c65ebfc7SToomas Soome         (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6098c65ebfc7SToomas Soome         return mDNStrue;
6099c65ebfc7SToomas Soome 
6100c65ebfc7SToomas Soome     return mDNSfalse;
6101c65ebfc7SToomas Soome }
6102c65ebfc7SToomas Soome 
UpdateRMAC(mDNS * const m,void * context)6103c65ebfc7SToomas Soome mDNSexport void UpdateRMAC(mDNS *const m, void *context)
6104c65ebfc7SToomas Soome {
6105c65ebfc7SToomas Soome     IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
6106c65ebfc7SToomas Soome     m->CurrentRecord = m->ResourceRecords;
6107c65ebfc7SToomas Soome 
6108c65ebfc7SToomas Soome     if (!addrmap)
6109c65ebfc7SToomas Soome     {
6110c65ebfc7SToomas Soome         LogMsg("UpdateRMAC: Address mapping is NULL");
6111c65ebfc7SToomas Soome         return;
6112c65ebfc7SToomas Soome     }
6113c65ebfc7SToomas Soome 
6114c65ebfc7SToomas Soome     while (m->CurrentRecord)
6115c65ebfc7SToomas Soome     {
6116c65ebfc7SToomas Soome         AuthRecord *rr = m->CurrentRecord;
6117c65ebfc7SToomas Soome         // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6118c65ebfc7SToomas Soome         if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
6119c65ebfc7SToomas Soome         {
6120c65ebfc7SToomas Soome             mDNSAddr raddr;
6121c65ebfc7SToomas Soome             getKeepaliveRaddr(m, rr, &raddr);
6122c65ebfc7SToomas Soome             if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
6123c65ebfc7SToomas Soome             {
6124c65ebfc7SToomas Soome                 // Update the MAC address only if it is not a zero MAC address
6125c65ebfc7SToomas Soome                 mDNSEthAddr macAddr;
6126c65ebfc7SToomas Soome                 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
6127c65ebfc7SToomas Soome                 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
6128c65ebfc7SToomas Soome                 {
6129c65ebfc7SToomas Soome                     UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
6130c65ebfc7SToomas Soome                 }
6131c65ebfc7SToomas Soome             }
6132c65ebfc7SToomas Soome         }
6133c65ebfc7SToomas Soome         m->CurrentRecord = rr->next;
6134c65ebfc7SToomas Soome     }
6135c65ebfc7SToomas Soome 
6136c65ebfc7SToomas Soome     if (addrmap)
6137c65ebfc7SToomas Soome         mDNSPlatformMemFree(addrmap);
6138c65ebfc7SToomas Soome 
6139c65ebfc7SToomas Soome }
6140c65ebfc7SToomas Soome 
UpdateKeepaliveRData(mDNS * const m,AuthRecord * rr,NetworkInterfaceInfo * const intf,mDNSBool updateMac,char * ethAddr)6141c65ebfc7SToomas Soome mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
6142c65ebfc7SToomas Soome {
6143c65ebfc7SToomas Soome     mDNSu16 newrdlength;
6144c65ebfc7SToomas Soome     mDNSAddr laddr = zeroAddr;
6145c65ebfc7SToomas Soome     mDNSAddr raddr = zeroAddr;
6146c65ebfc7SToomas Soome     mDNSEthAddr eth = zeroEthAddr;
6147c65ebfc7SToomas Soome     mDNSIPPort lport = zeroIPPort;
6148c65ebfc7SToomas Soome     mDNSIPPort rport = zeroIPPort;
6149c65ebfc7SToomas Soome     mDNSu32 timeout = 0;
6150c65ebfc7SToomas Soome     mDNSu32 seq = 0;
6151c65ebfc7SToomas Soome     mDNSu32 ack = 0;
6152c65ebfc7SToomas Soome     mDNSu16 win = 0;
6153c65ebfc7SToomas Soome     UTF8str255 txt;
6154c65ebfc7SToomas Soome     int rdsize;
6155c65ebfc7SToomas Soome     RData *newrd;
6156c65ebfc7SToomas Soome     mDNSTCPInfo mti;
6157c65ebfc7SToomas Soome     mStatus ret;
6158c65ebfc7SToomas Soome 
6159c65ebfc7SToomas Soome     // Note: If we fail to update the  DNS NULL  record with additional information in this function, it will be registered
6160c65ebfc7SToomas Soome     // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6161c65ebfc7SToomas Soome     mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
6162c65ebfc7SToomas Soome     if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
6163c65ebfc7SToomas Soome     {
6164c65ebfc7SToomas Soome         LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
6165c65ebfc7SToomas Soome         return mStatus_UnknownErr;
6166c65ebfc7SToomas Soome     }
6167c65ebfc7SToomas Soome 
6168c65ebfc7SToomas Soome     if (updateMac)
6169c65ebfc7SToomas Soome     {
6170c65ebfc7SToomas Soome         if (laddr.type == mDNSAddrType_IPv4)
6171c65ebfc7SToomas Soome             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);
6172c65ebfc7SToomas Soome         else
6173c65ebfc7SToomas Soome             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);
6174c65ebfc7SToomas Soome 
6175c65ebfc7SToomas Soome     }
6176c65ebfc7SToomas Soome     else
6177c65ebfc7SToomas Soome     {
6178c65ebfc7SToomas Soome         // If this keepalive packet would be sent on a different interface than the current one that we are processing
6179c65ebfc7SToomas Soome         // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6180c65ebfc7SToomas Soome         // this DNS NULL record, it does not send any keepalives as it does not have all the information
6181c65ebfc7SToomas Soome         mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
6182c65ebfc7SToomas Soome         ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti);
6183c65ebfc7SToomas Soome         if (ret != mStatus_NoError)
6184c65ebfc7SToomas Soome         {
6185c65ebfc7SToomas Soome             LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
6186c65ebfc7SToomas Soome             return ret;
6187c65ebfc7SToomas Soome         }
6188c65ebfc7SToomas Soome         if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
6189c65ebfc7SToomas Soome         {
6190c65ebfc7SToomas Soome             LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p",  mti.IntfId, intf->InterfaceID);
6191c65ebfc7SToomas Soome             return mStatus_BadParamErr;
6192c65ebfc7SToomas Soome         }
6193c65ebfc7SToomas Soome 
6194c65ebfc7SToomas Soome         if (laddr.type == mDNSAddrType_IPv4)
6195c65ebfc7SToomas Soome             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);
6196c65ebfc7SToomas Soome         else
6197c65ebfc7SToomas Soome             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);
6198c65ebfc7SToomas Soome     }
6199c65ebfc7SToomas Soome 
6200c65ebfc7SToomas Soome     // Did we insert a null byte at the end ?
6201c65ebfc7SToomas Soome     if (newrdlength == (sizeof(txt.c) - 1))
6202c65ebfc7SToomas Soome     {
6203c65ebfc7SToomas Soome         LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
6204c65ebfc7SToomas Soome         return mStatus_NoMemoryErr;
6205c65ebfc7SToomas Soome     }
6206c65ebfc7SToomas Soome 
6207c65ebfc7SToomas Soome     // Include the length for the null byte at the end
6208c65ebfc7SToomas Soome     txt.c[0] = newrdlength + 1;
6209c65ebfc7SToomas Soome     // Account for the first length byte and the null byte at the end
6210c65ebfc7SToomas Soome     newrdlength += 2;
6211c65ebfc7SToomas Soome 
6212c65ebfc7SToomas Soome     rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
6213*472cd20dSToomas Soome     newrd = (RData *) mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
6214c65ebfc7SToomas Soome     if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
6215c65ebfc7SToomas Soome 
6216c65ebfc7SToomas Soome     newrd->MaxRDLength = (mDNSu16) rdsize;
6217c65ebfc7SToomas Soome     mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
6218c65ebfc7SToomas Soome 
6219c65ebfc7SToomas Soome     //  If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6220c65ebfc7SToomas Soome     //  was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6221c65ebfc7SToomas Soome     //  If the resource record has data that we allocated in a previous pass (to update MAC address),
6222c65ebfc7SToomas Soome     //  free that memory here before copying in the new data.
6223c65ebfc7SToomas Soome     if ( rr->resrec.rdata != &rr->rdatastorage)
6224c65ebfc7SToomas Soome     {
6225c65ebfc7SToomas Soome         LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
6226c65ebfc7SToomas Soome         mDNSPlatformMemFree(rr->resrec.rdata);
6227c65ebfc7SToomas Soome     }
6228c65ebfc7SToomas Soome     SetNewRData(&rr->resrec, newrd, newrdlength);    // Update our rdata
6229c65ebfc7SToomas Soome 
6230c65ebfc7SToomas Soome     LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
6231c65ebfc7SToomas Soome     return mStatus_NoError;
6232c65ebfc7SToomas Soome }
6233c65ebfc7SToomas Soome 
SendSPSRegistrationForOwner(mDNS * const m,NetworkInterfaceInfo * const intf,const mDNSOpaque16 id,const OwnerOptData * const owner)6234c65ebfc7SToomas Soome mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
6235c65ebfc7SToomas Soome {
6236c65ebfc7SToomas Soome     const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
6237c65ebfc7SToomas Soome     const int sps = intf->NextSPSAttempt / 3;
6238c65ebfc7SToomas Soome     AuthRecord *rr;
6239c65ebfc7SToomas Soome     mDNSOpaque16 msgid;
6240c65ebfc7SToomas Soome     mDNSu32 scopeid;
6241c65ebfc7SToomas Soome 
6242c65ebfc7SToomas Soome     scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6243c65ebfc7SToomas Soome     if (!intf->SPSAddr[sps].type)
6244c65ebfc7SToomas Soome     {
6245c65ebfc7SToomas Soome         intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6246c65ebfc7SToomas Soome         if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6247c65ebfc7SToomas Soome             m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6248c65ebfc7SToomas Soome         LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
6249c65ebfc7SToomas Soome         goto exit;
6250c65ebfc7SToomas Soome     }
6251c65ebfc7SToomas Soome 
6252c65ebfc7SToomas Soome     // Mark our mDNS records (not unicast records) for transfer to SPS
6253c65ebfc7SToomas Soome     if (mDNSOpaque16IsZero(id))
6254c65ebfc7SToomas Soome     {
6255c65ebfc7SToomas Soome         // We may have to register this record over multiple interfaces and we don't want to
6256c65ebfc7SToomas Soome         // overwrite the id. We send the registration over interface X with id "IDX" and before
6257c65ebfc7SToomas Soome         // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6258c65ebfc7SToomas Soome         // for "IDX". Hence, we want to use the same ID across all interfaces.
6259c65ebfc7SToomas Soome         //
6260c65ebfc7SToomas Soome         // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6261c65ebfc7SToomas Soome         // option check below will set the same ID across the records from the same owner. Records
6262c65ebfc7SToomas Soome         // with different owner option gets different ID.
6263c65ebfc7SToomas Soome         msgid = mDNS_NewMessageID(m);
6264c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
6265c65ebfc7SToomas Soome         {
6266c65ebfc7SToomas Soome             if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
6267c65ebfc7SToomas Soome             {
6268c65ebfc7SToomas Soome                 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6269c65ebfc7SToomas Soome                 {
6270c65ebfc7SToomas Soome                     if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6271c65ebfc7SToomas Soome                     {
6272c65ebfc7SToomas Soome                         rr->SendRNow = mDNSInterfaceMark;   // mark it now
6273c65ebfc7SToomas Soome                         // When we are registering on the first interface, rr->updateid is zero in which case
6274c65ebfc7SToomas Soome                         // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6275c65ebfc7SToomas Soome                         // At the end, all the updates sent across all the interfaces with the same ID.
6276c65ebfc7SToomas Soome                         if (mDNSOpaque16IsZero(rr->updateid))
6277c65ebfc7SToomas Soome                             rr->updateid = msgid;
6278c65ebfc7SToomas Soome                         else
6279c65ebfc7SToomas Soome                             msgid = rr->updateid;
6280c65ebfc7SToomas Soome                     }
6281c65ebfc7SToomas Soome                 }
6282c65ebfc7SToomas Soome             }
6283c65ebfc7SToomas Soome         }
6284c65ebfc7SToomas Soome     }
6285c65ebfc7SToomas Soome     else
6286c65ebfc7SToomas Soome         msgid = id;
6287c65ebfc7SToomas Soome 
6288c65ebfc7SToomas Soome     while (1)
6289c65ebfc7SToomas Soome     {
6290c65ebfc7SToomas Soome         mDNSu8 *p = m->omsg.data;
6291c65ebfc7SToomas Soome         // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6292c65ebfc7SToomas Soome         // For now we follow that same logic for SPS registrations too.
6293c65ebfc7SToomas Soome         // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6294c65ebfc7SToomas Soome         // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6295c65ebfc7SToomas Soome         InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
6296c65ebfc7SToomas Soome 
6297c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
6298c65ebfc7SToomas Soome             if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
6299c65ebfc7SToomas Soome             {
6300c65ebfc7SToomas Soome                 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6301c65ebfc7SToomas Soome                 {
6302c65ebfc7SToomas Soome                     mDNSu8 *newptr;
6303c65ebfc7SToomas Soome                     const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
6304c65ebfc7SToomas Soome 
6305c65ebfc7SToomas Soome                     // If we can't update the keepalive record, don't send it
6306c65ebfc7SToomas Soome                     if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
6307c65ebfc7SToomas Soome                     {
6308c65ebfc7SToomas Soome                         if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
6309c65ebfc7SToomas Soome                         {
6310c65ebfc7SToomas Soome                             bit_clr_opaque64(rr->updateIntID, scopeid);
6311c65ebfc7SToomas Soome                         }
6312c65ebfc7SToomas Soome                         rr->SendRNow = mDNSNULL;
6313c65ebfc7SToomas Soome                         continue;
6314c65ebfc7SToomas Soome                     }
6315c65ebfc7SToomas Soome 
6316c65ebfc7SToomas Soome                     if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
6317c65ebfc7SToomas Soome                         rr->resrec.rrclass |= kDNSClass_UniqueRRSet;    // Temporarily set the 'unique' bit so PutResourceRecord will set it
6318c65ebfc7SToomas Soome                     newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
6319c65ebfc7SToomas Soome                     rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;       // Make sure to clear 'unique' bit back to normal state
6320c65ebfc7SToomas Soome                     if (!newptr)
6321c65ebfc7SToomas Soome                         LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
6322c65ebfc7SToomas Soome                     else
6323c65ebfc7SToomas Soome                     {
6324c65ebfc7SToomas Soome                         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));
6325c65ebfc7SToomas Soome                         rr->SendRNow       = mDNSNULL;
6326c65ebfc7SToomas Soome                         rr->ThisAPInterval = mDNSPlatformOneSecond;
6327c65ebfc7SToomas Soome                         rr->LastAPTime     = m->timenow;
6328c65ebfc7SToomas Soome                         // should be initialized above
6329c65ebfc7SToomas Soome                         if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
6330c65ebfc7SToomas Soome                         if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6331c65ebfc7SToomas Soome                             m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
6332c65ebfc7SToomas Soome                         p = newptr;
6333c65ebfc7SToomas Soome                     }
6334c65ebfc7SToomas Soome                 }
6335c65ebfc7SToomas Soome             }
6336c65ebfc7SToomas Soome 
6337c65ebfc7SToomas Soome         if (!m->omsg.h.mDNS_numUpdates) break;
6338c65ebfc7SToomas Soome         else
6339c65ebfc7SToomas Soome         {
6340c65ebfc7SToomas Soome             AuthRecord opt;
6341c65ebfc7SToomas Soome             mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
6342c65ebfc7SToomas Soome             opt.resrec.rrclass    = NormalMaxDNSMessageData;
6343c65ebfc7SToomas Soome             opt.resrec.rdlength   = sizeof(rdataOPT) * 2;   // Two options in this OPT record
6344c65ebfc7SToomas Soome             opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
6345c65ebfc7SToomas Soome             opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
6346c65ebfc7SToomas Soome             opt.resrec.rdata->u.opt[0].optlen        = DNSOpt_LeaseData_Space - 4;
6347c65ebfc7SToomas Soome             opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
6348c65ebfc7SToomas Soome             if (!owner->HMAC.l[0])                                          // If no owner data,
6349c65ebfc7SToomas Soome                 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]);        // use our own interface information
6350c65ebfc7SToomas Soome             else                                                            // otherwise, use the owner data we were given
6351c65ebfc7SToomas Soome             {
6352c65ebfc7SToomas Soome                 opt.resrec.rdata->u.opt[1].u.owner = *owner;
6353c65ebfc7SToomas Soome                 opt.resrec.rdata->u.opt[1].opt     = kDNSOpt_Owner;
6354c65ebfc7SToomas Soome                 opt.resrec.rdata->u.opt[1].optlen  = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
6355c65ebfc7SToomas Soome             }
6356c65ebfc7SToomas Soome             LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
6357c65ebfc7SToomas Soome             p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6358c65ebfc7SToomas Soome             if (!p)
6359c65ebfc7SToomas Soome                 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
6360c65ebfc7SToomas Soome             else
6361c65ebfc7SToomas Soome             {
6362c65ebfc7SToomas Soome                 mStatus err;
6363c65ebfc7SToomas Soome 
6364c65ebfc7SToomas Soome                 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
6365c65ebfc7SToomas Soome                        mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
6366c65ebfc7SToomas Soome                 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID;  // For simulating packet loss
6367*472cd20dSToomas Soome                 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSfalse);
6368c65ebfc7SToomas Soome                 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
6369c65ebfc7SToomas Soome                 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
6370c65ebfc7SToomas Soome                 {
6371c65ebfc7SToomas Soome                     LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
6372c65ebfc7SToomas Soome                     intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
6373c65ebfc7SToomas Soome                     mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
6374c65ebfc7SToomas Soome                     return;
6375c65ebfc7SToomas Soome                 }
6376c65ebfc7SToomas Soome             }
6377c65ebfc7SToomas Soome         }
6378c65ebfc7SToomas Soome     }
6379c65ebfc7SToomas Soome 
6380c65ebfc7SToomas Soome     intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10;     // If successful, update NextSPSAttemptTime
6381c65ebfc7SToomas Soome 
6382c65ebfc7SToomas Soome exit:
6383c65ebfc7SToomas Soome     if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
6384c65ebfc7SToomas Soome }
6385c65ebfc7SToomas Soome 
RecordIsFirstOccurrenceOfOwner(mDNS * const m,const AuthRecord * const rr)6386c65ebfc7SToomas Soome mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
6387c65ebfc7SToomas Soome {
6388c65ebfc7SToomas Soome     AuthRecord *ar;
6389c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
6390c65ebfc7SToomas Soome         if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
6391c65ebfc7SToomas Soome     return mDNStrue;
6392c65ebfc7SToomas Soome }
6393c65ebfc7SToomas Soome 
mDNSCoreStoreProxyRR(mDNS * const m,const mDNSInterfaceID InterfaceID,AuthRecord * const rr)6394c65ebfc7SToomas Soome mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6395c65ebfc7SToomas Soome {
6396*472cd20dSToomas Soome     AuthRecord *newRR = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(*newRR));
6397c65ebfc7SToomas Soome     if (newRR == mDNSNULL)
6398c65ebfc7SToomas Soome     {
6399c65ebfc7SToomas Soome         LogSPS("%s : could not allocate memory for new resource record", __func__);
6400c65ebfc7SToomas Soome         return;
6401c65ebfc7SToomas Soome     }
6402c65ebfc7SToomas Soome 
6403c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6404c65ebfc7SToomas Soome                              rr->resrec.rroriginalttl, rr->resrec.RecordType,
6405c65ebfc7SToomas Soome                              rr->ARType, mDNSNULL, mDNSNULL);
6406c65ebfc7SToomas Soome 
6407c65ebfc7SToomas Soome     AssignDomainName(&newRR->namestorage, &rr->namestorage);
6408c65ebfc7SToomas Soome     newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6409c65ebfc7SToomas Soome     newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6410c65ebfc7SToomas Soome     newRR->resrec.rrclass  = rr->resrec.rrclass;
6411c65ebfc7SToomas Soome 
6412c65ebfc7SToomas Soome     if (rr->resrec.rrtype == kDNSType_A)
6413c65ebfc7SToomas Soome     {
6414c65ebfc7SToomas Soome         newRR->resrec.rdata->u.ipv4 =  rr->resrec.rdata->u.ipv4;
6415c65ebfc7SToomas Soome     }
6416c65ebfc7SToomas Soome     else if (rr->resrec.rrtype == kDNSType_AAAA)
6417c65ebfc7SToomas Soome     {
6418c65ebfc7SToomas Soome         newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6419c65ebfc7SToomas Soome     }
6420c65ebfc7SToomas Soome     SetNewRData(&newRR->resrec, mDNSNULL, 0);
6421c65ebfc7SToomas Soome 
6422c65ebfc7SToomas Soome     // Insert the new node at the head of the list.
6423c65ebfc7SToomas Soome     newRR->next        = m->SPSRRSet;
6424c65ebfc7SToomas Soome     m->SPSRRSet        = newRR;
6425c65ebfc7SToomas Soome     LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6426c65ebfc7SToomas Soome }
6427c65ebfc7SToomas Soome 
6428c65ebfc7SToomas Soome // Some records are interface specific and some are not. The ones that are supposed to be registered
6429c65ebfc7SToomas Soome // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6430c65ebfc7SToomas Soome // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6431c65ebfc7SToomas Soome // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6432c65ebfc7SToomas Soome // registration on all the interfaces
SPSInitRecordsBeforeUpdate(mDNS * const m,mDNSOpaque64 updateIntID,mDNSBool * WakeOnlyService)6433c65ebfc7SToomas Soome mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6434c65ebfc7SToomas Soome {
6435c65ebfc7SToomas Soome     AuthRecord *ar;
6436c65ebfc7SToomas Soome     LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6437c65ebfc7SToomas Soome 
6438c65ebfc7SToomas Soome     *WakeOnlyService = mDNSfalse;
6439c65ebfc7SToomas Soome 
6440c65ebfc7SToomas Soome     // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6441c65ebfc7SToomas Soome     // make sure that the old sleep proxy records are removed.
6442c65ebfc7SToomas Soome     mDNSCoreFreeProxyRR(m);
6443c65ebfc7SToomas Soome 
6444c65ebfc7SToomas Soome     // For records that are registered only on a specific interface, mark only that bit as it will
6445c65ebfc7SToomas Soome     // never be registered on any other interface. For others, it should be sent on all interfaces.
6446c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar; ar=ar->next)
6447c65ebfc7SToomas Soome     {
6448c65ebfc7SToomas Soome         ar->updateIntID = zeroOpaque64;
6449c65ebfc7SToomas Soome         ar->updateid    = zeroID;
6450c65ebfc7SToomas Soome         if (AuthRecord_uDNS(ar))
6451c65ebfc7SToomas Soome         {
6452c65ebfc7SToomas Soome             continue;
6453c65ebfc7SToomas Soome         }
6454c65ebfc7SToomas Soome         if (ar->AuthFlags & AuthFlagsWakeOnly)
6455c65ebfc7SToomas Soome         {
6456c65ebfc7SToomas Soome             if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6457c65ebfc7SToomas Soome             {
6458c65ebfc7SToomas Soome                 ar->ImmedAnswer = mDNSInterfaceMark;
6459c65ebfc7SToomas Soome                 *WakeOnlyService = mDNStrue;
6460c65ebfc7SToomas Soome                 continue;
6461c65ebfc7SToomas Soome             }
6462c65ebfc7SToomas Soome         }
6463c65ebfc7SToomas Soome         if (!ar->resrec.InterfaceID)
6464c65ebfc7SToomas Soome         {
6465c65ebfc7SToomas Soome             LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6466c65ebfc7SToomas Soome             ar->updateIntID = updateIntID;
6467c65ebfc7SToomas Soome         }
6468c65ebfc7SToomas Soome         else
6469c65ebfc7SToomas Soome         {
6470c65ebfc7SToomas Soome             // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6471c65ebfc7SToomas Soome             // exactly this.
6472c65ebfc7SToomas Soome             mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6473c65ebfc7SToomas Soome             if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6474c65ebfc7SToomas Soome             {
6475c65ebfc7SToomas Soome                 bit_set_opaque64(ar->updateIntID, scopeid);
6476c65ebfc7SToomas Soome                 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6477c65ebfc7SToomas Soome                     ar->updateIntID.l[0], ARDisplayString(m, ar));
6478c65ebfc7SToomas Soome             }
6479c65ebfc7SToomas Soome             else
6480c65ebfc7SToomas Soome             {
6481c65ebfc7SToomas Soome                 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6482c65ebfc7SToomas Soome             }
6483c65ebfc7SToomas Soome         }
6484c65ebfc7SToomas Soome         // Store the A and AAAA records that we registered with the sleep proxy.
6485c65ebfc7SToomas Soome         // We will use this to prevent spurious name conflicts that may occur when we wake up
6486c65ebfc7SToomas Soome         if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6487c65ebfc7SToomas Soome         {
6488c65ebfc7SToomas Soome             mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6489c65ebfc7SToomas Soome         }
6490c65ebfc7SToomas Soome     }
6491c65ebfc7SToomas Soome }
6492c65ebfc7SToomas Soome 
SendSPSRegistration(mDNS * const m,NetworkInterfaceInfo * const intf,const mDNSOpaque16 id)6493c65ebfc7SToomas Soome mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6494c65ebfc7SToomas Soome {
6495c65ebfc7SToomas Soome     AuthRecord *ar;
6496c65ebfc7SToomas Soome     OwnerOptData owner = zeroOwner;
6497c65ebfc7SToomas Soome 
6498c65ebfc7SToomas Soome     SendSPSRegistrationForOwner(m, intf, id, &owner);
6499c65ebfc7SToomas Soome 
6500c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar; ar=ar->next)
6501c65ebfc7SToomas Soome     {
6502c65ebfc7SToomas Soome         if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6503c65ebfc7SToomas Soome         {
6504c65ebfc7SToomas Soome             owner = ar->WakeUp;
6505c65ebfc7SToomas Soome             SendSPSRegistrationForOwner(m, intf, id, &owner);
6506c65ebfc7SToomas Soome         }
6507c65ebfc7SToomas Soome     }
6508c65ebfc7SToomas Soome }
6509c65ebfc7SToomas Soome 
6510c65ebfc7SToomas Soome // RetrySPSRegistrations is called from SendResponses, with the lock held
RetrySPSRegistrations(mDNS * const m)6511c65ebfc7SToomas Soome mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6512c65ebfc7SToomas Soome {
6513c65ebfc7SToomas Soome     AuthRecord *rr;
6514c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
6515c65ebfc7SToomas Soome 
6516c65ebfc7SToomas Soome     // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6517c65ebfc7SToomas Soome     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6518c65ebfc7SToomas Soome         if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6519c65ebfc7SToomas Soome             intf->NextSPSAttemptTime++;
6520c65ebfc7SToomas Soome 
6521c65ebfc7SToomas Soome     // Retry any record registrations that are due
6522c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
6523c65ebfc7SToomas Soome         if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6524c65ebfc7SToomas Soome         {
6525c65ebfc7SToomas Soome             for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6526c65ebfc7SToomas Soome             {
6527c65ebfc7SToomas Soome                 // If we still have registrations pending on this interface, send it now
6528c65ebfc7SToomas Soome                 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6529c65ebfc7SToomas Soome                 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6530c65ebfc7SToomas Soome                     (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6531c65ebfc7SToomas Soome                 {
6532c65ebfc7SToomas Soome                     LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6533c65ebfc7SToomas Soome                     SendSPSRegistration(m, intf, rr->updateid);
6534c65ebfc7SToomas Soome                 }
6535c65ebfc7SToomas Soome             }
6536c65ebfc7SToomas Soome         }
6537c65ebfc7SToomas Soome 
6538c65ebfc7SToomas Soome     // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6539c65ebfc7SToomas Soome     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6540c65ebfc7SToomas Soome         if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6541c65ebfc7SToomas Soome             intf->NextSPSAttempt++;
6542c65ebfc7SToomas Soome }
6543c65ebfc7SToomas Soome 
NetWakeResolve(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)6544c65ebfc7SToomas Soome mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6545c65ebfc7SToomas Soome {
6546c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6547c65ebfc7SToomas Soome     int sps = (int)(question - intf->NetWakeResolve);
6548c65ebfc7SToomas Soome     (void)m;            // Unused
6549c65ebfc7SToomas Soome     LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6550c65ebfc7SToomas Soome 
6551c65ebfc7SToomas Soome     if (!AddRecord) return;                                             // Don't care about REMOVE events
6552c65ebfc7SToomas Soome     if (answer->rrtype != question->qtype) return;                      // Don't care about CNAMEs
6553c65ebfc7SToomas Soome 
6554c65ebfc7SToomas Soome     // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6555c65ebfc7SToomas Soome 
6556c65ebfc7SToomas Soome     if (answer->rrtype == kDNSType_SRV)
6557c65ebfc7SToomas Soome     {
6558c65ebfc7SToomas Soome         // 1. Got the SRV record; now look up the target host's IP address
6559c65ebfc7SToomas Soome         mDNS_StopQuery(m, question);
6560c65ebfc7SToomas Soome         intf->SPSPort[sps] = answer->rdata->u.srv.port;
6561c65ebfc7SToomas Soome         AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6562c65ebfc7SToomas Soome         question->qtype = kDNSType_A;
6563c65ebfc7SToomas Soome         mDNS_StartQuery(m, question);
6564c65ebfc7SToomas Soome     }
6565c65ebfc7SToomas Soome     else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6566c65ebfc7SToomas Soome     {
6567c65ebfc7SToomas Soome         // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6568c65ebfc7SToomas Soome         mDNS_StopQuery(m, question);
6569c65ebfc7SToomas Soome         question->ThisQInterval = -1;
6570c65ebfc7SToomas Soome         intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6571c65ebfc7SToomas Soome         intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6572c65ebfc7SToomas Soome         mDNS_Lock(m);
6573c65ebfc7SToomas Soome         if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);    // If we're ready for this result, use it now
6574c65ebfc7SToomas Soome         mDNS_Unlock(m);
6575c65ebfc7SToomas Soome     }
6576c65ebfc7SToomas Soome     else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6577c65ebfc7SToomas Soome     {
6578c65ebfc7SToomas Soome         // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6579c65ebfc7SToomas Soome         mDNS_StopQuery(m, question);
6580c65ebfc7SToomas Soome         LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6581c65ebfc7SToomas Soome         question->qtype = kDNSType_AAAA;
6582c65ebfc7SToomas Soome         mDNS_StartQuery(m, question);
6583c65ebfc7SToomas Soome     }
6584c65ebfc7SToomas Soome     else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6585c65ebfc7SToomas Soome     {
6586c65ebfc7SToomas Soome         // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6587c65ebfc7SToomas Soome         mDNS_StopQuery(m, question);
6588c65ebfc7SToomas Soome         question->ThisQInterval = -1;
6589c65ebfc7SToomas Soome         intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6590c65ebfc7SToomas Soome         intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6591c65ebfc7SToomas Soome         mDNS_Lock(m);
6592c65ebfc7SToomas Soome         if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);    // If we're ready for this result, use it now
6593c65ebfc7SToomas Soome         mDNS_Unlock(m);
6594c65ebfc7SToomas Soome     }
6595c65ebfc7SToomas Soome }
6596c65ebfc7SToomas Soome 
mDNSCoreHaveAdvertisedMulticastServices(mDNS * const m)6597c65ebfc7SToomas Soome mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6598c65ebfc7SToomas Soome {
6599c65ebfc7SToomas Soome     AuthRecord *rr;
6600c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
6601c65ebfc7SToomas Soome         if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6602c65ebfc7SToomas Soome             return mDNStrue;
6603c65ebfc7SToomas Soome     return mDNSfalse;
6604c65ebfc7SToomas Soome }
6605c65ebfc7SToomas Soome 
6606c65ebfc7SToomas Soome #define WAKE_ONLY_SERVICE 1
6607c65ebfc7SToomas Soome #define AC_ONLY_SERVICE   2
6608c65ebfc7SToomas Soome 
6609c65ebfc7SToomas Soome #ifdef APPLE_OSX_mDNSResponder
SendGoodbyesForSelectServices(mDNS * const m,mDNSBool * servicePresent,mDNSu32 serviceType)6610c65ebfc7SToomas Soome mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6611c65ebfc7SToomas Soome {
6612c65ebfc7SToomas Soome     AuthRecord *rr;
6613c65ebfc7SToomas Soome     *servicePresent = mDNSfalse;
6614c65ebfc7SToomas Soome 
6615c65ebfc7SToomas Soome     // Mark all the records we need to deregister and send them
6616c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
6617c65ebfc7SToomas Soome     {
6618c65ebfc7SToomas Soome         // If the service type is wake only service and the auth flags match and requires a goodbye
6619c65ebfc7SToomas Soome         // OR if the service type is AC only and it is not a keepalive record,
6620c65ebfc7SToomas Soome         // mark the records we need to deregister and send them
6621c65ebfc7SToomas Soome         if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6622c65ebfc7SToomas Soome                 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6623c65ebfc7SToomas Soome             (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6624c65ebfc7SToomas Soome         {
6625c65ebfc7SToomas Soome             rr->ImmedAnswer = mDNSInterfaceMark;
6626c65ebfc7SToomas Soome             *servicePresent = mDNStrue;
6627c65ebfc7SToomas Soome         }
6628c65ebfc7SToomas Soome     }
6629c65ebfc7SToomas Soome }
6630c65ebfc7SToomas Soome #endif
6631c65ebfc7SToomas Soome 
6632c65ebfc7SToomas Soome #ifdef APPLE_OSX_mDNSResponder
6633c65ebfc7SToomas Soome // This function is used only in the case of local NIC proxy. For external
6634c65ebfc7SToomas Soome // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6635c65ebfc7SToomas Soome // walk the resource records.
SendGoodbyesForWakeOnlyService(mDNS * const m,mDNSBool * WakeOnlyService)6636c65ebfc7SToomas Soome mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6637c65ebfc7SToomas Soome {
6638c65ebfc7SToomas Soome     return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6639c65ebfc7SToomas Soome }
6640c65ebfc7SToomas Soome #endif // APPLE_OSX_mDNSResponder
6641c65ebfc7SToomas Soome 
6642c65ebfc7SToomas Soome 
SendSleepGoodbyes(mDNS * const m,mDNSBool AllInterfaces,mDNSBool unicast)6643c65ebfc7SToomas Soome mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6644c65ebfc7SToomas Soome {
6645c65ebfc7SToomas Soome     AuthRecord *rr;
6646c65ebfc7SToomas Soome     m->SleepState = SleepState_Sleeping;
6647c65ebfc7SToomas Soome 
6648c65ebfc7SToomas Soome     // If AllInterfaces is not set, the caller has already marked it appropriately
6649c65ebfc7SToomas Soome     // on which interfaces this should be sent.
6650c65ebfc7SToomas Soome     if (AllInterfaces)
6651c65ebfc7SToomas Soome     {
6652c65ebfc7SToomas Soome         NetworkInterfaceInfo *intf;
6653c65ebfc7SToomas Soome         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6654c65ebfc7SToomas Soome         {
6655c65ebfc7SToomas Soome             intf->SendGoodbyes = 1;
6656c65ebfc7SToomas Soome         }
6657c65ebfc7SToomas Soome     }
6658c65ebfc7SToomas Soome     if (unicast)
6659c65ebfc7SToomas Soome     {
6660c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
6661c65ebfc7SToomas Soome         SleepRecordRegistrations(m);    // If we have no SPS, need to deregister our uDNS records
6662c65ebfc7SToomas Soome #endif /* UNICAST_DISABLED */
6663c65ebfc7SToomas Soome     }
6664c65ebfc7SToomas Soome 
6665c65ebfc7SToomas Soome     // Mark all the records we need to deregister and send them
6666c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
6667c65ebfc7SToomas Soome         if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6668c65ebfc7SToomas Soome             rr->ImmedAnswer = mDNSInterfaceMark;
6669c65ebfc7SToomas Soome     SendResponses(m);
6670c65ebfc7SToomas Soome }
6671c65ebfc7SToomas Soome 
6672c65ebfc7SToomas Soome /*
6673c65ebfc7SToomas Soome  * This function attempts to detect if multiple interfaces are on the same subnet.
6674c65ebfc7SToomas Soome  * It makes this determination based only on the IPv4 Addresses and subnet masks.
6675c65ebfc7SToomas Soome  * IPv6 link local addresses that are configured by default on all interfaces make
6676c65ebfc7SToomas Soome  * it hard to make this determination
6677c65ebfc7SToomas Soome  *
6678c65ebfc7SToomas Soome  * The 'real' fix for this would be to send out multicast packets over one interface
6679c65ebfc7SToomas Soome  * and conclude that multiple interfaces are on the same subnet only if these packets
6680c65ebfc7SToomas Soome  * are seen on other interfaces on the same system
6681c65ebfc7SToomas Soome  */
skipSameSubnetRegistration(mDNS * const m,mDNSInterfaceID * regID,mDNSu32 count,mDNSInterfaceID intfid)6682c65ebfc7SToomas Soome mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6683c65ebfc7SToomas Soome {
6684c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
6685c65ebfc7SToomas Soome     NetworkInterfaceInfo *newIntf;
6686c65ebfc7SToomas Soome     mDNSu32 i;
6687c65ebfc7SToomas Soome 
6688c65ebfc7SToomas Soome     for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6689c65ebfc7SToomas Soome     {
6690c65ebfc7SToomas Soome         if ((newIntf->InterfaceID != intfid) ||
6691c65ebfc7SToomas Soome             (newIntf->ip.type     != mDNSAddrType_IPv4))
6692c65ebfc7SToomas Soome         {
6693c65ebfc7SToomas Soome             continue;
6694c65ebfc7SToomas Soome         }
6695c65ebfc7SToomas Soome         for ( i = 0; i < count; i++)
6696c65ebfc7SToomas Soome         {
6697c65ebfc7SToomas Soome             for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6698c65ebfc7SToomas Soome             {
6699c65ebfc7SToomas Soome                 if ((intf->InterfaceID != regID[i]) ||
6700c65ebfc7SToomas Soome                     (intf->ip.type     != mDNSAddrType_IPv4))
6701c65ebfc7SToomas Soome                 {
6702c65ebfc7SToomas Soome                     continue;
6703c65ebfc7SToomas Soome                 }
6704c65ebfc7SToomas Soome                 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6705c65ebfc7SToomas Soome                 {
6706c65ebfc7SToomas Soome                     LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6707c65ebfc7SToomas Soome                     return (mDNStrue);
6708c65ebfc7SToomas Soome                 }
6709c65ebfc7SToomas Soome             }
6710c65ebfc7SToomas Soome         }
6711c65ebfc7SToomas Soome     }
6712c65ebfc7SToomas Soome     return (mDNSfalse);
6713c65ebfc7SToomas Soome }
6714c65ebfc7SToomas Soome 
DoKeepaliveCallbacks(mDNS * m)6715c65ebfc7SToomas Soome mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6716c65ebfc7SToomas Soome {
6717c65ebfc7SToomas Soome     // Loop through the keepalive records and callback with an error
6718c65ebfc7SToomas Soome     m->CurrentRecord = m->ResourceRecords;
6719c65ebfc7SToomas Soome     while (m->CurrentRecord)
6720c65ebfc7SToomas Soome     {
6721c65ebfc7SToomas Soome         AuthRecord *const rr = m->CurrentRecord;
6722c65ebfc7SToomas Soome         if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6723c65ebfc7SToomas Soome         {
6724c65ebfc7SToomas Soome             LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6725c65ebfc7SToomas Soome             if (rr->RecordCallback)
6726c65ebfc7SToomas Soome                 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6727c65ebfc7SToomas Soome         }
6728c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6729c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
6730c65ebfc7SToomas Soome     }
6731c65ebfc7SToomas Soome }
6732c65ebfc7SToomas Soome 
6733c65ebfc7SToomas Soome // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
BeginSleepProcessing(mDNS * const m)6734c65ebfc7SToomas Soome mDNSlocal void BeginSleepProcessing(mDNS *const m)
6735c65ebfc7SToomas Soome {
6736c65ebfc7SToomas Soome     mDNSBool SendGoodbyes = mDNStrue;
6737c65ebfc7SToomas Soome     mDNSBool WakeOnlyService  = mDNSfalse;
6738c65ebfc7SToomas Soome     mDNSBool invokeKACallback = mDNStrue;
6739c65ebfc7SToomas Soome     const CacheRecord *sps[3] = { mDNSNULL };
6740c65ebfc7SToomas Soome     mDNSOpaque64 updateIntID = zeroOpaque64;
6741c65ebfc7SToomas Soome     mDNSInterfaceID registeredIntfIDS[128] = { 0 };
6742c65ebfc7SToomas Soome     mDNSu32 registeredCount = 0;
6743c65ebfc7SToomas Soome     int skippedRegistrations = 0;
6744c65ebfc7SToomas Soome 
6745c65ebfc7SToomas Soome     m->NextScheduledSPRetry = m->timenow;
6746c65ebfc7SToomas Soome 
6747c65ebfc7SToomas Soome     // Clear out the SCDynamic entry that stores the external SPS information
6748c65ebfc7SToomas Soome     mDNSPlatformClearSPSData();
6749c65ebfc7SToomas Soome 
6750c65ebfc7SToomas Soome     if      (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6751c65ebfc7SToomas Soome     else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6752c65ebfc7SToomas Soome     else    // If we have at least one advertised service
6753c65ebfc7SToomas Soome     {
6754c65ebfc7SToomas Soome         NetworkInterfaceInfo *intf;
6755c65ebfc7SToomas Soome         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6756c65ebfc7SToomas Soome         {
67573b436d06SToomas Soome             mDNSBool skipFullSleepProxyRegistration = mDNSfalse;
6758c65ebfc7SToomas Soome             // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6759c65ebfc7SToomas Soome             intf->SendGoodbyes = 0;
6760c65ebfc7SToomas Soome 
6761c65ebfc7SToomas Soome             // If it is not multicast capable, we could not have possibly discovered sleep proxy
6762c65ebfc7SToomas Soome             // servers.
6763c65ebfc7SToomas Soome             if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6764c65ebfc7SToomas Soome             {
6765c65ebfc7SToomas Soome                 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6766c65ebfc7SToomas Soome                 continue;
6767c65ebfc7SToomas Soome             }
6768c65ebfc7SToomas Soome 
6769c65ebfc7SToomas Soome             // If we are not capable of WOMP, then don't register with sleep proxy.
6770c65ebfc7SToomas Soome             //
6771c65ebfc7SToomas Soome             // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6772c65ebfc7SToomas Soome             // We might find sleep proxy servers in the cache and start a resolve on them.
6773c65ebfc7SToomas Soome             // But then if the interface goes away, we won't stop these questions because
6774c65ebfc7SToomas Soome             // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6775c65ebfc7SToomas Soome             // to stop both the browse and resolve questions.
6776c65ebfc7SToomas Soome             if (!intf->NetWake)
6777c65ebfc7SToomas Soome             {
6778c65ebfc7SToomas Soome                 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6779c65ebfc7SToomas Soome                 intf->SendGoodbyes = 1;
6780c65ebfc7SToomas Soome                 skippedRegistrations++;
6781c65ebfc7SToomas Soome                 continue;
6782c65ebfc7SToomas Soome             }
6783c65ebfc7SToomas Soome 
67843b436d06SToomas Soome             // Check if we have already registered with a sleep proxy for this subnet.
67853b436d06SToomas Soome             // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
67863b436d06SToomas Soome             // to the interface.
6787c65ebfc7SToomas Soome             if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6788c65ebfc7SToomas Soome             {
67893b436d06SToomas Soome                 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname);
67903b436d06SToomas Soome                 skipFullSleepProxyRegistration = mDNStrue;
6791c65ebfc7SToomas Soome             }
6792c65ebfc7SToomas Soome 
6793c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
67943b436d06SToomas Soome             if (SupportsInNICProxy(intf))
6795c65ebfc7SToomas Soome             {
6796c65ebfc7SToomas Soome                 mDNSBool keepaliveOnly = mDNSfalse;
67973b436d06SToomas Soome                 const mStatus err = ActivateLocalProxy(intf, skipFullSleepProxyRegistration, &keepaliveOnly);
67983b436d06SToomas Soome                 if (!skipFullSleepProxyRegistration && !err)
6799c65ebfc7SToomas Soome                 {
6800c65ebfc7SToomas Soome                     SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6801c65ebfc7SToomas Soome 
6802c65ebfc7SToomas Soome                     // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6803c65ebfc7SToomas Soome                     SendGoodbyes     = (keepaliveOnly) ? mDNStrue: mDNSfalse;
6804c65ebfc7SToomas Soome                     invokeKACallback = mDNSfalse;
6805c65ebfc7SToomas Soome                     LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6806c65ebfc7SToomas Soome                     // This will leave m->SleepState set to SleepState_Transferring,
6807c65ebfc7SToomas Soome                     // which is okay because with no outstanding resolves, or updates in flight,
6808c65ebfc7SToomas Soome                     // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6809c65ebfc7SToomas Soome 
6810c65ebfc7SToomas Soome                     registeredIntfIDS[registeredCount] = intf->InterfaceID;
6811c65ebfc7SToomas Soome                     registeredCount++;
6812c65ebfc7SToomas Soome                 }
68133b436d06SToomas Soome                 continue;
6814c65ebfc7SToomas Soome             }
6815c65ebfc7SToomas Soome #endif // APPLE_OSX_mDNSResponder
68163b436d06SToomas Soome             if (!skipFullSleepProxyRegistration)
6817c65ebfc7SToomas Soome             {
6818c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
6819c65ebfc7SToomas Soome                 // If on battery, do not attempt to offload to external sleep proxies
6820c65ebfc7SToomas Soome                 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6821c65ebfc7SToomas Soome                 {
6822c65ebfc7SToomas Soome                     LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6823c65ebfc7SToomas Soome                     return;
6824c65ebfc7SToomas Soome                 }
6825c65ebfc7SToomas Soome #endif // APPLE_OSX_mDNSResponder
6826c65ebfc7SToomas Soome                 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6827c65ebfc7SToomas Soome                 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6828c65ebfc7SToomas Soome                                     intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6829c65ebfc7SToomas Soome                 else
6830c65ebfc7SToomas Soome                 {
6831c65ebfc7SToomas Soome                     int i;
6832c65ebfc7SToomas Soome                     mDNSu32 scopeid;
6833c65ebfc7SToomas Soome                     SendGoodbyes = mDNSfalse;
6834c65ebfc7SToomas Soome                     intf->NextSPSAttempt = 0;
6835c65ebfc7SToomas Soome                     intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6836c65ebfc7SToomas Soome 
6837c65ebfc7SToomas Soome                     scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6838c65ebfc7SToomas Soome                     // Now we know for sure that we have to wait for registration to complete on this interface.
6839c65ebfc7SToomas Soome                     if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6840c65ebfc7SToomas Soome                         bit_set_opaque64(updateIntID, scopeid);
6841c65ebfc7SToomas Soome 
6842c65ebfc7SToomas Soome                     // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6843c65ebfc7SToomas Soome                     for (i=0; i<3; i++)
6844c65ebfc7SToomas Soome                     {
6845c65ebfc7SToomas Soome #if ForceAlerts
6846c65ebfc7SToomas Soome                         if (intf->SPSAddr[i].type)
6847c65ebfc7SToomas Soome                             LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6848c65ebfc7SToomas Soome                         if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6849c65ebfc7SToomas Soome                             LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6850c65ebfc7SToomas Soome #endif
6851c65ebfc7SToomas Soome                         intf->SPSAddr[i].type = mDNSAddrType_None;
6852c65ebfc7SToomas Soome                         if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6853c65ebfc7SToomas Soome                         intf->NetWakeResolve[i].ThisQInterval = -1;
6854c65ebfc7SToomas Soome                         if (sps[i])
6855c65ebfc7SToomas Soome                         {
6856c65ebfc7SToomas Soome                             LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6857c65ebfc7SToomas Soome                             mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6858c65ebfc7SToomas Soome                             intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6859c65ebfc7SToomas Soome                             mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6860c65ebfc7SToomas Soome 
6861c65ebfc7SToomas Soome                             // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6862c65ebfc7SToomas Soome                             registeredIntfIDS[registeredCount] = intf->InterfaceID;
6863c65ebfc7SToomas Soome                             registeredCount++;
6864c65ebfc7SToomas Soome                         }
6865c65ebfc7SToomas Soome                     }
6866c65ebfc7SToomas Soome                 }
6867c65ebfc7SToomas Soome             }
6868c65ebfc7SToomas Soome         }
6869c65ebfc7SToomas Soome     }
6870c65ebfc7SToomas Soome 
6871c65ebfc7SToomas Soome     // If we have at least one interface on which we are registering with an external sleep proxy,
6872c65ebfc7SToomas Soome     // initialize all the records appropriately.
6873c65ebfc7SToomas Soome     if (!mDNSOpaque64IsZero(&updateIntID))
6874c65ebfc7SToomas Soome         SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6875c65ebfc7SToomas Soome 
6876c65ebfc7SToomas Soome     // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6877c65ebfc7SToomas Soome     // the records to a sleep proxy.
6878c65ebfc7SToomas Soome     if (invokeKACallback)
6879c65ebfc7SToomas Soome     {
6880c65ebfc7SToomas Soome         LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6881c65ebfc7SToomas Soome         DoKeepaliveCallbacks(m);
6882c65ebfc7SToomas Soome     }
6883c65ebfc7SToomas Soome 
6884c65ebfc7SToomas Soome     // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6885c65ebfc7SToomas Soome     // interfaces and also deregister unicast registrations.
6886c65ebfc7SToomas Soome     //
6887c65ebfc7SToomas Soome     // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6888c65ebfc7SToomas Soome     //   for both multicast and unicast.
6889c65ebfc7SToomas Soome     //
6890c65ebfc7SToomas Soome     // - If we skipped registrations on some interfaces, then we have already marked
6891c65ebfc7SToomas Soome     //   them appropriately above. We don't need to send goodbyes for unicast as
6892c65ebfc7SToomas Soome     //   we have registered with at least one sleep proxy.
6893c65ebfc7SToomas Soome     //
6894c65ebfc7SToomas Soome     // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6895c65ebfc7SToomas Soome     //
6896c65ebfc7SToomas Soome     // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6897c65ebfc7SToomas Soome     // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6898c65ebfc7SToomas Soome     // at WakeOnlyServices first.
6899c65ebfc7SToomas Soome     if (SendGoodbyes)
6900c65ebfc7SToomas Soome     {
6901c65ebfc7SToomas Soome         LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6902c65ebfc7SToomas Soome         SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6903c65ebfc7SToomas Soome     }
6904c65ebfc7SToomas Soome     else if (skippedRegistrations)
6905c65ebfc7SToomas Soome     {
6906c65ebfc7SToomas Soome         LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6907c65ebfc7SToomas Soome         SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6908c65ebfc7SToomas Soome     }
6909c65ebfc7SToomas Soome     else if (WakeOnlyService)
6910c65ebfc7SToomas Soome     {
6911c65ebfc7SToomas Soome         // If we saw WakeOnly service above, send the goodbyes now.
6912c65ebfc7SToomas Soome         LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6913c65ebfc7SToomas Soome         SendResponses(m);
6914c65ebfc7SToomas Soome     }
6915c65ebfc7SToomas Soome }
6916c65ebfc7SToomas Soome 
6917c65ebfc7SToomas Soome // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6918c65ebfc7SToomas Soome // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6919c65ebfc7SToomas Soome // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
mDNSCoreMachineSleep(mDNS * const m,mDNSBool sleep)6920c65ebfc7SToomas Soome mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6921c65ebfc7SToomas Soome {
6922c65ebfc7SToomas Soome     AuthRecord *rr;
6923c65ebfc7SToomas Soome 
6924*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_INFO,
6925*472cd20dSToomas Soome         PUB_S " (old state %d) at %d", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6926c65ebfc7SToomas Soome 
6927c65ebfc7SToomas Soome     if (sleep && !m->SleepState)        // Going to sleep
6928c65ebfc7SToomas Soome     {
6929c65ebfc7SToomas Soome         mDNS_Lock(m);
6930c65ebfc7SToomas Soome         // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6931c65ebfc7SToomas Soome         if (m->SPSSocket)
6932c65ebfc7SToomas Soome         {
6933c65ebfc7SToomas Soome             mDNSu8 oldstate = m->SPSState;
6934c65ebfc7SToomas Soome             mDNS_DropLockBeforeCallback();      // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6935c65ebfc7SToomas Soome             m->SPSState = 2;
6936c65ebfc7SToomas Soome #ifndef SPC_DISABLED
6937c65ebfc7SToomas Soome             if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6938c65ebfc7SToomas Soome #else
6939c65ebfc7SToomas Soome             (void)oldstate;
6940c65ebfc7SToomas Soome #endif
6941c65ebfc7SToomas Soome             mDNS_ReclaimLockAfterCallback();
6942c65ebfc7SToomas Soome         }
69433b436d06SToomas Soome #ifdef _LEGACY_NAT_TRAVERSAL_
69443b436d06SToomas Soome         if (m->SSDPSocket)
69453b436d06SToomas Soome         {
69463b436d06SToomas Soome             mDNSPlatformUDPClose(m->SSDPSocket);
69473b436d06SToomas Soome             m->SSDPSocket = mDNSNULL;
69483b436d06SToomas Soome         }
69493b436d06SToomas Soome #endif
6950c65ebfc7SToomas Soome         m->SleepState = SleepState_Transferring;
6951c65ebfc7SToomas Soome         if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6952c65ebfc7SToomas Soome         {
6953c65ebfc7SToomas Soome             // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6954*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
6955*472cd20dSToomas Soome                       "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6956c65ebfc7SToomas Soome             m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6957c65ebfc7SToomas Soome         }
6958c65ebfc7SToomas Soome         else
6959c65ebfc7SToomas Soome         {
6960c65ebfc7SToomas Soome             m->DelaySleep = 0;
6961c65ebfc7SToomas Soome             m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6962c65ebfc7SToomas Soome             m->mDNSStats.Sleeps++;
6963*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
6964*472cd20dSToomas Soome             Querier_HandleSleep();
6965*472cd20dSToomas Soome #endif
6966c65ebfc7SToomas Soome             BeginSleepProcessing(m);
6967c65ebfc7SToomas Soome         }
6968c65ebfc7SToomas Soome 
6969c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
6970c65ebfc7SToomas Soome         SuspendLLQs(m);
6971c65ebfc7SToomas Soome #endif
6972*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S ") seq %d",
6973*472cd20dSToomas Soome                   m->SleepState,
6974c65ebfc7SToomas Soome                   m->SleepState == SleepState_Transferring ? "Transferring" :
6975c65ebfc7SToomas Soome                   m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?", m->SleepSeqNum);
6976c65ebfc7SToomas Soome         mDNS_Unlock(m);
6977c65ebfc7SToomas Soome     }
6978c65ebfc7SToomas Soome     else if (!sleep)        // Waking up
6979c65ebfc7SToomas Soome     {
6980c65ebfc7SToomas Soome         mDNSu32 slot;
6981c65ebfc7SToomas Soome         CacheGroup *cg;
6982c65ebfc7SToomas Soome         CacheRecord *cr;
6983c65ebfc7SToomas Soome         NetworkInterfaceInfo *intf;
6984c65ebfc7SToomas Soome         mDNSs32 currtime, diff;
6985c65ebfc7SToomas Soome 
6986c65ebfc7SToomas Soome         mDNS_Lock(m);
6987c65ebfc7SToomas Soome         // Reset SleepLimit back to 0 now that we're awake again.
6988c65ebfc7SToomas Soome         m->SleepLimit = 0;
6989c65ebfc7SToomas Soome 
6990c65ebfc7SToomas Soome         // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6991c65ebfc7SToomas Soome         if (m->SleepState != SleepState_Awake)
6992c65ebfc7SToomas Soome         {
6993c65ebfc7SToomas Soome             m->SleepState = SleepState_Awake;
6994c65ebfc7SToomas Soome             m->SleepSeqNum++;
6995c65ebfc7SToomas Soome             // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6996c65ebfc7SToomas Soome             // then we enforce a minimum delay of five seconds before we begin sleep processing.
6997c65ebfc7SToomas Soome             // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6998c65ebfc7SToomas Soome             // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6999c65ebfc7SToomas Soome             m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep);
7000c65ebfc7SToomas Soome         }
7001c65ebfc7SToomas Soome 
7002c65ebfc7SToomas Soome         if (m->SPSState == 3)
7003c65ebfc7SToomas Soome         {
7004c65ebfc7SToomas Soome             m->SPSState = 0;
7005c65ebfc7SToomas Soome             mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
7006c65ebfc7SToomas Soome         }
7007c65ebfc7SToomas Soome         m->mDNSStats.Wakes++;
7008c65ebfc7SToomas Soome         // ... and the same for NextSPSAttempt
7009c65ebfc7SToomas Soome         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
7010c65ebfc7SToomas Soome 
7011*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7012*472cd20dSToomas Soome         Querier_HandleWake();
7013*472cd20dSToomas Soome #endif
7014c65ebfc7SToomas Soome         // Restart unicast and multicast queries
7015c65ebfc7SToomas Soome         mDNSCoreRestartQueries(m);
7016c65ebfc7SToomas Soome 
7017c65ebfc7SToomas Soome         // and reactivtate service registrations
7018c65ebfc7SToomas Soome         m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7019*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7020*472cd20dSToomas Soome                   "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
7021c65ebfc7SToomas Soome 
7022c65ebfc7SToomas Soome         // 2. Re-validate our cache records
7023c65ebfc7SToomas Soome         currtime = mDNSPlatformUTC();
7024c65ebfc7SToomas Soome 
7025c65ebfc7SToomas Soome         diff = currtime - m->TimeSlept;
7026c65ebfc7SToomas Soome         FORALL_CACHERECORDS(slot, cg, cr)
7027c65ebfc7SToomas Soome         {
7028c65ebfc7SToomas Soome             // Temporary fix: For unicast cache records, look at how much time we slept.
7029c65ebfc7SToomas Soome             // Adjust the RecvTime by the amount of time we slept so that we age the
7030c65ebfc7SToomas Soome             // cache record appropriately. If it is expired already, purge. If there
7031c65ebfc7SToomas Soome             // is a network change that happens after the wakeup, we might purge the
7032c65ebfc7SToomas Soome             // cache anyways and this helps only in the case where there are no network
7033c65ebfc7SToomas Soome             // changes across sleep/wakeup transition.
7034c65ebfc7SToomas Soome             //
7035c65ebfc7SToomas Soome             // Note: If there is a network/DNS server change that already happened and
7036c65ebfc7SToomas Soome             // these cache entries are already refreshed and we are getting a delayed
7037c65ebfc7SToomas Soome             // wake up notification, we might adjust the TimeRcvd based on the time slept
7038c65ebfc7SToomas Soome             // now which can cause the cache to purge pre-maturely. As this is not a very
7039c65ebfc7SToomas Soome             // common case, this should happen rarely.
7040c65ebfc7SToomas Soome             if (!cr->resrec.InterfaceID)
7041c65ebfc7SToomas Soome             {
7042c65ebfc7SToomas Soome                 if (diff > 0)
7043c65ebfc7SToomas Soome                 {
7044c65ebfc7SToomas Soome                     mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
7045c65ebfc7SToomas Soome                     const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
7046c65ebfc7SToomas Soome 
7047c65ebfc7SToomas Soome                     // -if we have slept longer than the remaining TTL, purge and start fresh.
7048c65ebfc7SToomas Soome                     // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
7049c65ebfc7SToomas Soome                     //  a sufficiently big value which could cause the value to go into the future
7050c65ebfc7SToomas Soome                     //  because of the signed comparison of time. For this to happen, we should have been
7051c65ebfc7SToomas Soome                     //  sleeping really long (~24 days). For now, we want to be conservative and flush even
7052c65ebfc7SToomas Soome                     //  if we have slept for more than two days.
7053c65ebfc7SToomas Soome 
7054c65ebfc7SToomas Soome                     if (diff >= remain || diff > (2 * 24 * 3600))
7055c65ebfc7SToomas Soome                     {
7056*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7057*472cd20dSToomas Soome                                   "mDNSCoreMachineSleep: " PRI_S ": Purging cache entry SleptTime %d, Remaining TTL %d",
7058c65ebfc7SToomas Soome                                   CRDisplayString(m, cr), diff, remain);
7059c65ebfc7SToomas Soome                         mDNS_PurgeCacheResourceRecord(m, cr);
7060c65ebfc7SToomas Soome                         continue;
7061c65ebfc7SToomas Soome                     }
7062c65ebfc7SToomas Soome                     cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
7063c65ebfc7SToomas Soome                     if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
7064c65ebfc7SToomas Soome                     {
7065*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7066*472cd20dSToomas Soome                                   "mDNSCoreMachineSleep: " PRI_S ": Purging after adjusting the remaining TTL %d by %d seconds",
7067c65ebfc7SToomas Soome                                   CRDisplayString(m, cr), remain, diff);
7068c65ebfc7SToomas Soome                         mDNS_PurgeCacheResourceRecord(m, cr);
7069c65ebfc7SToomas Soome                     }
7070c65ebfc7SToomas Soome                     else
7071c65ebfc7SToomas Soome                     {
7072*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7073*472cd20dSToomas Soome                                   "mDNSCoreMachineSleep: " PRI_S ": Adjusted the remain ttl %u by %d seconds",
7074*472cd20dSToomas Soome                                   CRDisplayString(m, cr), remain, diff);
7075c65ebfc7SToomas Soome                     }
7076c65ebfc7SToomas Soome                 }
7077c65ebfc7SToomas Soome             }
7078c65ebfc7SToomas Soome             else
7079c65ebfc7SToomas Soome             {
7080c65ebfc7SToomas Soome                 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
7081c65ebfc7SToomas Soome             }
7082c65ebfc7SToomas Soome         }
7083c65ebfc7SToomas Soome 
7084c65ebfc7SToomas Soome         // 3. Retrigger probing and announcing for all our authoritative records
7085c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
7086c65ebfc7SToomas Soome         {
7087c65ebfc7SToomas Soome             if (AuthRecord_uDNS(rr))
7088c65ebfc7SToomas Soome             {
7089c65ebfc7SToomas Soome                 ActivateUnicastRegistration(m, rr);
7090c65ebfc7SToomas Soome             }
7091c65ebfc7SToomas Soome             else
7092c65ebfc7SToomas Soome             {
7093c65ebfc7SToomas Soome                 mDNSCoreRestartRegistration(m, rr, -1);
7094c65ebfc7SToomas Soome             }
7095c65ebfc7SToomas Soome         }
7096c65ebfc7SToomas Soome 
7097c65ebfc7SToomas Soome         // 4. Refresh NAT mappings
7098c65ebfc7SToomas Soome         // We don't want to have to assume that all hardware can necessarily keep accurate
7099c65ebfc7SToomas Soome         // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7100c65ebfc7SToomas Soome         // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7101c65ebfc7SToomas Soome         // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7102c65ebfc7SToomas Soome         // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7103c65ebfc7SToomas Soome         // than five seconds from now.
7104*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7105c65ebfc7SToomas Soome         RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
7106c65ebfc7SToomas Soome         mDNS_Unlock(m);
7107c65ebfc7SToomas Soome     }
7108c65ebfc7SToomas Soome }
7109c65ebfc7SToomas Soome 
mDNSCoreReadyForSleep(mDNS * m,mDNSs32 now)7110c65ebfc7SToomas Soome mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
7111c65ebfc7SToomas Soome {
7112c65ebfc7SToomas Soome     DNSQuestion *q;
7113c65ebfc7SToomas Soome     AuthRecord *rr;
7114c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
7115c65ebfc7SToomas Soome 
7116c65ebfc7SToomas Soome     mDNS_Lock(m);
7117c65ebfc7SToomas Soome 
7118c65ebfc7SToomas Soome     if (m->DelaySleep) goto notready;
7119c65ebfc7SToomas Soome 
7120c65ebfc7SToomas Soome     // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7121c65ebfc7SToomas Soome     if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
7122c65ebfc7SToomas Soome 
7123c65ebfc7SToomas Soome     m->NextScheduledSPRetry = now + 0x40000000UL;
7124c65ebfc7SToomas Soome 
7125c65ebfc7SToomas Soome     // See if we might need to retransmit any lost Sleep Proxy Registrations
7126c65ebfc7SToomas Soome     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7127c65ebfc7SToomas Soome         if (intf->NextSPSAttempt >= 0)
7128c65ebfc7SToomas Soome         {
7129c65ebfc7SToomas Soome             if (now - intf->NextSPSAttemptTime >= 0)
7130c65ebfc7SToomas Soome             {
7131c65ebfc7SToomas Soome                 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7132c65ebfc7SToomas Soome                        intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
7133c65ebfc7SToomas Soome                 SendSPSRegistration(m, intf, zeroID);
7134c65ebfc7SToomas Soome                 // Don't need to "goto notready" here, because if we do still have record registrations
7135c65ebfc7SToomas Soome                 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7136c65ebfc7SToomas Soome             }
7137c65ebfc7SToomas Soome             else
7138c65ebfc7SToomas Soome             if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
7139c65ebfc7SToomas Soome                 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
7140c65ebfc7SToomas Soome         }
7141c65ebfc7SToomas Soome 
7142c65ebfc7SToomas Soome     // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7143c65ebfc7SToomas Soome     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7144c65ebfc7SToomas Soome     {
7145c65ebfc7SToomas Soome         int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
7146c65ebfc7SToomas Soome         if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
7147c65ebfc7SToomas Soome         {
7148c65ebfc7SToomas Soome             LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7149c65ebfc7SToomas Soome                    intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
7150c65ebfc7SToomas Soome             goto spsnotready;
7151c65ebfc7SToomas Soome         }
7152c65ebfc7SToomas Soome     }
7153c65ebfc7SToomas Soome 
7154c65ebfc7SToomas Soome     // Scan list of registered records
7155c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr = rr->next)
7156c65ebfc7SToomas Soome         if (!AuthRecord_uDNS(rr))
7157c65ebfc7SToomas Soome             if (!mDNSOpaque64IsZero(&rr->updateIntID))
7158c65ebfc7SToomas Soome             { 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; }
7159c65ebfc7SToomas Soome 
7160c65ebfc7SToomas Soome     // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7161c65ebfc7SToomas Soome     for (q = m->Questions; q; q = q->next)
7162c65ebfc7SToomas Soome         if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
7163c65ebfc7SToomas Soome         {
7164c65ebfc7SToomas Soome             LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7165c65ebfc7SToomas Soome             goto notready;
7166c65ebfc7SToomas Soome         }
7167c65ebfc7SToomas Soome 
7168c65ebfc7SToomas Soome     // Scan list of registered records
7169c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr = rr->next)
7170c65ebfc7SToomas Soome         if (AuthRecord_uDNS(rr))
7171c65ebfc7SToomas Soome         {
7172c65ebfc7SToomas Soome             if (rr->state == regState_Refresh && rr->tcp)
7173c65ebfc7SToomas Soome             { 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; }
7174c65ebfc7SToomas Soome         }
7175c65ebfc7SToomas Soome 
7176c65ebfc7SToomas Soome     mDNS_Unlock(m);
7177c65ebfc7SToomas Soome     return mDNStrue;
7178c65ebfc7SToomas Soome 
7179c65ebfc7SToomas Soome spsnotready:
7180c65ebfc7SToomas Soome 
7181c65ebfc7SToomas Soome     // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7182c65ebfc7SToomas Soome     // and allow up to ten seconds more to complete wide-area deregistration instead
7183c65ebfc7SToomas Soome     if (now - m->SleepLimit >= 0)
7184c65ebfc7SToomas Soome     {
7185c65ebfc7SToomas Soome         LogMsg("Failed to register with SPS, now sending goodbyes");
7186c65ebfc7SToomas Soome 
7187c65ebfc7SToomas Soome         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7188c65ebfc7SToomas Soome             if (intf->NetWakeBrowse.ThisQInterval >= 0)
7189c65ebfc7SToomas Soome             {
7190c65ebfc7SToomas Soome                 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7191c65ebfc7SToomas Soome                        intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
7192c65ebfc7SToomas Soome                 mDNS_DeactivateNetWake_internal(m, intf);
7193c65ebfc7SToomas Soome             }
7194c65ebfc7SToomas Soome 
7195c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr = rr->next)
7196c65ebfc7SToomas Soome             if (!AuthRecord_uDNS(rr))
7197c65ebfc7SToomas Soome                 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7198c65ebfc7SToomas Soome                 {
7199c65ebfc7SToomas Soome                     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));
7200c65ebfc7SToomas Soome                     rr->updateIntID = zeroOpaque64;
7201c65ebfc7SToomas Soome                 }
7202c65ebfc7SToomas Soome 
7203c65ebfc7SToomas Soome         // We'd really like to allow up to ten seconds more here,
7204c65ebfc7SToomas Soome         // but if we don't respond to the sleep notification within 30 seconds
7205c65ebfc7SToomas Soome         // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7206c65ebfc7SToomas Soome         // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7207c65ebfc7SToomas Soome         // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7208c65ebfc7SToomas Soome         // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7209c65ebfc7SToomas Soome         m->SleepLimit = now + mDNSPlatformOneSecond * 1;
7210c65ebfc7SToomas Soome 
7211c65ebfc7SToomas Soome         SendSleepGoodbyes(m, mDNStrue, mDNStrue);
7212c65ebfc7SToomas Soome     }
7213c65ebfc7SToomas Soome 
7214c65ebfc7SToomas Soome notready:
7215c65ebfc7SToomas Soome     mDNS_Unlock(m);
7216c65ebfc7SToomas Soome     return mDNSfalse;
7217c65ebfc7SToomas Soome }
7218c65ebfc7SToomas Soome 
mDNSCoreIntervalToNextWake(mDNS * const m,mDNSs32 now,mDNSNextWakeReason * outReason)7219*472cd20dSToomas Soome mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now, mDNSNextWakeReason *outReason)
7220c65ebfc7SToomas Soome {
7221c65ebfc7SToomas Soome     AuthRecord *ar;
7222c65ebfc7SToomas Soome 
7223c65ebfc7SToomas Soome     // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7224c65ebfc7SToomas Soome     // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7225c65ebfc7SToomas Soome     // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7226c65ebfc7SToomas Soome     // and if that happens we don't want to just give up and go back to sleep and never try again.
7227c65ebfc7SToomas Soome     mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond);       // Sleep for at most 120 minutes
7228*472cd20dSToomas Soome     mDNSNextWakeReason reason = mDNSNextWakeReason_UpkeepWake;
7229c65ebfc7SToomas Soome 
7230c65ebfc7SToomas Soome     NATTraversalInfo *nat;
7231c65ebfc7SToomas Soome     for (nat = m->NATTraversals; nat; nat=nat->next)
7232*472cd20dSToomas Soome     {
7233c65ebfc7SToomas Soome         if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
7234c65ebfc7SToomas Soome         {
7235c65ebfc7SToomas Soome             mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10;     // Wake up when 90% of the way to the expiry time
7236*472cd20dSToomas Soome             if ((e - t) > 0)
7237*472cd20dSToomas Soome             {
7238*472cd20dSToomas Soome                 e = t;
7239*472cd20dSToomas Soome                 reason = mDNSNextWakeReason_NATPortMappingRenewal;
7240*472cd20dSToomas Soome             }
7241c65ebfc7SToomas Soome             LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7242c65ebfc7SToomas Soome                    nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
7243c65ebfc7SToomas Soome                    mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
7244c65ebfc7SToomas Soome                    nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
7245c65ebfc7SToomas Soome                    nat->retryInterval / mDNSPlatformOneSecond,
7246c65ebfc7SToomas Soome                    nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
7247c65ebfc7SToomas Soome                    (t - now) / mDNSPlatformOneSecond);
7248c65ebfc7SToomas Soome         }
7249*472cd20dSToomas Soome     }
7250c65ebfc7SToomas Soome     // This loop checks both the time we need to renew wide-area registrations,
7251c65ebfc7SToomas Soome     // and the time we need to renew Sleep Proxy registrations
7252c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar; ar = ar->next)
7253*472cd20dSToomas Soome     {
7254c65ebfc7SToomas Soome         if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
7255c65ebfc7SToomas Soome         {
7256c65ebfc7SToomas Soome             mDNSs32 t = ar->expire - (ar->expire - now) / 10;       // Wake up when 90% of the way to the expiry time
7257*472cd20dSToomas Soome             if ((e - t) > 0)
7258*472cd20dSToomas Soome             {
7259*472cd20dSToomas Soome                 e = t;
7260*472cd20dSToomas Soome                 reason = mDNSNextWakeReason_RecordRegistrationRenewal;
7261*472cd20dSToomas Soome             }
7262c65ebfc7SToomas Soome             LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7263c65ebfc7SToomas Soome                    ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
7264c65ebfc7SToomas Soome                    (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
7265c65ebfc7SToomas Soome                    ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
7266c65ebfc7SToomas Soome                    (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
7267c65ebfc7SToomas Soome         }
7268*472cd20dSToomas Soome     }
7269*472cd20dSToomas Soome     if (outReason)
7270*472cd20dSToomas Soome     {
7271*472cd20dSToomas Soome         *outReason = reason;
7272*472cd20dSToomas Soome     }
7273c65ebfc7SToomas Soome     return(e - now);
7274c65ebfc7SToomas Soome }
7275c65ebfc7SToomas Soome 
7276c65ebfc7SToomas Soome // ***************************************************************************
7277c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
7278c65ebfc7SToomas Soome #pragma mark -
7279c65ebfc7SToomas Soome #pragma mark - Packet Reception Functions
7280c65ebfc7SToomas Soome #endif
7281c65ebfc7SToomas Soome 
7282c65ebfc7SToomas Soome #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7283c65ebfc7SToomas Soome 
GenerateUnicastResponse(const DNSMessage * const query,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID,mDNSBool LegacyQuery,DNSMessage * const response,AuthRecord * ResponseRecords)7284c65ebfc7SToomas Soome mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
7285c65ebfc7SToomas Soome                                           const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
7286c65ebfc7SToomas Soome {
7287c65ebfc7SToomas Soome     mDNSu8          *responseptr     = response->data;
7288c65ebfc7SToomas Soome     const mDNSu8    *const limit     = response->data + sizeof(response->data);
7289c65ebfc7SToomas Soome     const mDNSu8    *ptr             = query->data;
7290c65ebfc7SToomas Soome     AuthRecord  *rr;
7291*472cd20dSToomas Soome     mDNSu32 maxttl = (!InterfaceID) ? mDNSMaximumUnicastTTLSeconds : mDNSMaximumMulticastTTLSeconds;
7292c65ebfc7SToomas Soome     int i;
7293c65ebfc7SToomas Soome 
7294c65ebfc7SToomas Soome     // Initialize the response fields so we can answer the questions
7295c65ebfc7SToomas Soome     InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
7296c65ebfc7SToomas Soome 
7297c65ebfc7SToomas Soome     // ***
7298c65ebfc7SToomas Soome     // *** 1. Write out the list of questions we are actually going to answer with this packet
7299c65ebfc7SToomas Soome     // ***
7300c65ebfc7SToomas Soome     if (LegacyQuery)
7301c65ebfc7SToomas Soome     {
7302c65ebfc7SToomas Soome         maxttl = kStaticCacheTTL;
7303c65ebfc7SToomas Soome         for (i=0; i<query->h.numQuestions; i++)                     // For each question...
7304c65ebfc7SToomas Soome         {
7305c65ebfc7SToomas Soome             DNSQuestion q;
7306c65ebfc7SToomas Soome             ptr = getQuestion(query, ptr, end, InterfaceID, &q);    // get the question...
7307c65ebfc7SToomas Soome             if (!ptr) return(mDNSNULL);
7308c65ebfc7SToomas Soome 
7309c65ebfc7SToomas Soome             for (rr=ResponseRecords; rr; rr=rr->NextResponse)       // and search our list of proposed answers
7310c65ebfc7SToomas Soome             {
7311c65ebfc7SToomas Soome                 if (rr->NR_AnswerTo == ptr)                         // If we're going to generate a record answering this question
7312c65ebfc7SToomas Soome                 {                                                   // then put the question in the question section
7313c65ebfc7SToomas Soome                     responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
7314c65ebfc7SToomas Soome                     if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
7315c65ebfc7SToomas Soome                     break;      // break out of the ResponseRecords loop, and go on to the next question
7316c65ebfc7SToomas Soome                 }
7317c65ebfc7SToomas Soome             }
7318c65ebfc7SToomas Soome         }
7319c65ebfc7SToomas Soome 
7320c65ebfc7SToomas Soome         if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
7321c65ebfc7SToomas Soome     }
7322c65ebfc7SToomas Soome 
7323c65ebfc7SToomas Soome     // ***
7324c65ebfc7SToomas Soome     // *** 2. Write Answers
7325c65ebfc7SToomas Soome     // ***
7326c65ebfc7SToomas Soome     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7327c65ebfc7SToomas Soome         if (rr->NR_AnswerTo)
7328c65ebfc7SToomas Soome         {
7329c65ebfc7SToomas Soome             mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
7330c65ebfc7SToomas Soome                                              maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7331c65ebfc7SToomas Soome             if (p) responseptr = p;
7332c65ebfc7SToomas Soome             else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
7333c65ebfc7SToomas Soome         }
7334c65ebfc7SToomas Soome 
7335c65ebfc7SToomas Soome     // ***
7336c65ebfc7SToomas Soome     // *** 3. Write Additionals
7337c65ebfc7SToomas Soome     // ***
7338c65ebfc7SToomas Soome     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7339c65ebfc7SToomas Soome         if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
7340c65ebfc7SToomas Soome         {
7341c65ebfc7SToomas Soome             mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
7342c65ebfc7SToomas Soome                                              maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7343c65ebfc7SToomas Soome             if (p) responseptr = p;
7344c65ebfc7SToomas Soome             else debugf("GenerateUnicastResponse: No more space for additionals");
7345c65ebfc7SToomas Soome         }
7346c65ebfc7SToomas Soome 
7347c65ebfc7SToomas Soome     return(responseptr);
7348c65ebfc7SToomas Soome }
7349c65ebfc7SToomas Soome 
7350c65ebfc7SToomas Soome // AuthRecord *our is our Resource Record
7351c65ebfc7SToomas Soome // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7352c65ebfc7SToomas Soome // Returns 0 if there is no conflict
7353c65ebfc7SToomas Soome // Returns +1 if there was a conflict and we won
7354c65ebfc7SToomas Soome // Returns -1 if there was a conflict and we lost and have to rename
CompareRData(const AuthRecord * const our,const CacheRecord * const pkt)7355c65ebfc7SToomas Soome mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
7356c65ebfc7SToomas Soome {
7357c65ebfc7SToomas Soome     mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
7358c65ebfc7SToomas Soome     mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
7359c65ebfc7SToomas Soome     if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7360c65ebfc7SToomas Soome     if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7361c65ebfc7SToomas Soome 
7362*472cd20dSToomas Soome #if defined(__clang_analyzer__)
7363*472cd20dSToomas Soome     // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7364*472cd20dSToomas Soome     // There are no clear indications from the analyzer of the cause of the supposed problem.
7365*472cd20dSToomas Soome     mDNSPlatformMemZero(ourdata, 1);
7366*472cd20dSToomas Soome     mDNSPlatformMemZero(pktdata, 1);
7367*472cd20dSToomas Soome #endif
7368c65ebfc7SToomas Soome     ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
7369c65ebfc7SToomas Soome     pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
7370c65ebfc7SToomas Soome     while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
7371c65ebfc7SToomas Soome     if (ourptr >= ourend && pktptr >= pktend) return(0);            // If data identical, not a conflict
7372c65ebfc7SToomas Soome 
7373c65ebfc7SToomas Soome     if (ourptr >= ourend) return(-1);                               // Our data ran out first; We lost
7374c65ebfc7SToomas Soome     if (pktptr >= pktend) return(+1);                               // Packet data ran out first; We won
7375c65ebfc7SToomas Soome     if (*pktptr > *ourptr) return(-1);                              // Our data is numerically lower; We lost
7376c65ebfc7SToomas Soome     if (*pktptr < *ourptr) return(+1);                              // Packet data is numerically lower; We won
7377c65ebfc7SToomas Soome 
7378c65ebfc7SToomas Soome     LogMsg("CompareRData ERROR: Invalid state");
7379c65ebfc7SToomas Soome     return(-1);
7380c65ebfc7SToomas Soome }
7381c65ebfc7SToomas Soome 
PacketRecordMatches(const AuthRecord * const rr,const CacheRecord * const pktrr,const AuthRecord * const master)7382*472cd20dSToomas Soome mDNSlocal mDNSBool PacketRecordMatches(const AuthRecord *const rr, const CacheRecord *const pktrr, const AuthRecord *const master)
7383*472cd20dSToomas Soome {
7384*472cd20dSToomas Soome     if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7385*472cd20dSToomas Soome     {
7386*472cd20dSToomas Soome         const AuthRecord *r2 = rr;
7387*472cd20dSToomas Soome         while (r2->DependentOn) r2 = r2->DependentOn;
7388*472cd20dSToomas Soome         if (r2 == master) return(mDNStrue);
7389*472cd20dSToomas Soome     }
7390*472cd20dSToomas Soome     return(mDNSfalse);
7391*472cd20dSToomas Soome }
7392*472cd20dSToomas Soome 
7393c65ebfc7SToomas Soome // See if we have an authoritative record that's identical to this packet record,
7394c65ebfc7SToomas Soome // whose canonical DependentOn record is the specified master record.
7395c65ebfc7SToomas Soome // The DependentOn pointer is typically used for the TXT record of service registrations
7396c65ebfc7SToomas Soome // It indicates that there is no inherent conflict detection for the TXT record
7397c65ebfc7SToomas Soome // -- it depends on the SRV record to resolve name conflicts
7398c65ebfc7SToomas Soome // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7399c65ebfc7SToomas Soome // pointer chain (if any) to make sure we reach the canonical DependentOn record
7400c65ebfc7SToomas Soome // If the record has no DependentOn, then just return that record's pointer
7401c65ebfc7SToomas Soome // Returns NULL if we don't have any local RRs that are identical to the one from the packet
MatchDependentOn(const mDNS * const m,const CacheRecord * const pktrr,const AuthRecord * const master)7402c65ebfc7SToomas Soome mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
7403c65ebfc7SToomas Soome {
7404c65ebfc7SToomas Soome     const AuthRecord *r1;
7405c65ebfc7SToomas Soome     for (r1 = m->ResourceRecords; r1; r1=r1->next)
7406c65ebfc7SToomas Soome     {
7407*472cd20dSToomas Soome         if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7408c65ebfc7SToomas Soome     }
7409c65ebfc7SToomas Soome     for (r1 = m->DuplicateRecords; r1; r1=r1->next)
7410c65ebfc7SToomas Soome     {
7411*472cd20dSToomas Soome         if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7412c65ebfc7SToomas Soome     }
7413c65ebfc7SToomas Soome     return(mDNSfalse);
7414c65ebfc7SToomas Soome }
7415c65ebfc7SToomas Soome 
7416c65ebfc7SToomas Soome // Find the canonical RRSet pointer for this RR received in a packet.
7417c65ebfc7SToomas Soome // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7418c65ebfc7SToomas Soome // pointers (if any) to make sure we return the canonical member of this name/type/class
7419c65ebfc7SToomas Soome // Returns NULL if we don't have any local RRs that are identical to the one from the packet
FindRRSet(const mDNS * const m,const CacheRecord * const pktrr)7420c65ebfc7SToomas Soome mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
7421c65ebfc7SToomas Soome {
7422c65ebfc7SToomas Soome     const AuthRecord *rr;
7423c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
7424c65ebfc7SToomas Soome     {
7425c65ebfc7SToomas Soome         if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7426c65ebfc7SToomas Soome         {
7427*472cd20dSToomas Soome             return(rr->RRSet ? rr->RRSet : rr);
7428c65ebfc7SToomas Soome         }
7429c65ebfc7SToomas Soome     }
7430c65ebfc7SToomas Soome     return(mDNSNULL);
7431c65ebfc7SToomas Soome }
7432c65ebfc7SToomas Soome 
7433c65ebfc7SToomas Soome // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7434c65ebfc7SToomas Soome // as one of our records (our) but different rdata.
7435c65ebfc7SToomas Soome // 1. If our record is not a type that's supposed to be unique, we don't care.
7436c65ebfc7SToomas Soome // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7437c65ebfc7SToomas Soome // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7438c65ebfc7SToomas Soome //     points to our record, ignore this conflict (e.g. the packet record matches one of our
7439c65ebfc7SToomas Soome //     TXT records, and that record is marked as dependent on 'our', its SRV record).
7440c65ebfc7SToomas Soome // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7441c65ebfc7SToomas Soome //    are members of the same RRSet, then this is not a conflict.
PacketRRConflict(const mDNS * const m,const AuthRecord * const our,const CacheRecord * const pktrr)7442c65ebfc7SToomas Soome mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7443c65ebfc7SToomas Soome {
7444c65ebfc7SToomas Soome     // If not supposed to be unique, not a conflict
7445c65ebfc7SToomas Soome     if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7446c65ebfc7SToomas Soome 
7447c65ebfc7SToomas Soome     // If a dependent record, not a conflict
7448c65ebfc7SToomas Soome     if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7449c65ebfc7SToomas Soome     else
7450c65ebfc7SToomas Soome     {
7451c65ebfc7SToomas Soome         // If the pktrr matches a member of ourset, not a conflict
7452c65ebfc7SToomas Soome         const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7453c65ebfc7SToomas Soome         const AuthRecord *pktset = FindRRSet(m, pktrr);
7454c65ebfc7SToomas Soome         if (pktset == ourset) return(mDNSfalse);
7455c65ebfc7SToomas Soome 
7456c65ebfc7SToomas Soome         // For records we're proxying, where we don't know the full
7457c65ebfc7SToomas Soome         // relationship between the records, having any matching record
7458c65ebfc7SToomas Soome         // in our AuthRecords list is sufficient evidence of non-conflict
7459c65ebfc7SToomas Soome         if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7460c65ebfc7SToomas Soome     }
7461c65ebfc7SToomas Soome 
7462c65ebfc7SToomas Soome     // Okay, this is a conflict
7463c65ebfc7SToomas Soome     return(mDNStrue);
7464c65ebfc7SToomas Soome }
7465c65ebfc7SToomas Soome 
7466c65ebfc7SToomas Soome // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7467c65ebfc7SToomas Soome // the record list and/or question list.
7468c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
ResolveSimultaneousProbe(mDNS * const m,const DNSMessage * const query,const mDNSu8 * const end,DNSQuestion * q,AuthRecord * our)7469c65ebfc7SToomas Soome mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7470c65ebfc7SToomas Soome                                         DNSQuestion *q, AuthRecord *our)
7471c65ebfc7SToomas Soome {
7472c65ebfc7SToomas Soome     int i;
7473c65ebfc7SToomas Soome     const mDNSu8 *ptr = LocateAuthorities(query, end);
7474c65ebfc7SToomas Soome     mDNSBool FoundUpdate = mDNSfalse;
7475c65ebfc7SToomas Soome 
7476c65ebfc7SToomas Soome     for (i = 0; i < query->h.numAuthorities; i++)
7477c65ebfc7SToomas Soome     {
7478c65ebfc7SToomas Soome         ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7479c65ebfc7SToomas Soome         if (!ptr) break;
7480*472cd20dSToomas Soome         if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && CacheRecordAnswersQuestion(&m->rec.r, q))
7481c65ebfc7SToomas Soome         {
7482c65ebfc7SToomas Soome             FoundUpdate = mDNStrue;
7483c65ebfc7SToomas Soome             if (PacketRRConflict(m, our, &m->rec.r))
7484c65ebfc7SToomas Soome             {
7485c65ebfc7SToomas Soome                 int result          = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7486c65ebfc7SToomas Soome                 if (!result) result = (int)our->resrec.rrtype  - (int)m->rec.r.resrec.rrtype;
7487c65ebfc7SToomas Soome                 if (!result) result = CompareRData(our, &m->rec.r);
7488c65ebfc7SToomas Soome                 if (result)
7489c65ebfc7SToomas Soome                 {
7490c65ebfc7SToomas Soome                     const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7491c65ebfc7SToomas Soome                     LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7492c65ebfc7SToomas Soome                     LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7493c65ebfc7SToomas Soome                 }
7494c65ebfc7SToomas Soome                 // 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.
7495c65ebfc7SToomas Soome                 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7496c65ebfc7SToomas Soome                 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7497c65ebfc7SToomas Soome                 if (result < 0)
7498c65ebfc7SToomas Soome                 {
7499c65ebfc7SToomas Soome                     m->SuppressProbes   = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7500c65ebfc7SToomas Soome                     our->ProbeCount     = DefaultProbeCountForTypeUnique;
7501c65ebfc7SToomas Soome                     our->AnnounceCount  = InitialAnnounceCount;
7502c65ebfc7SToomas Soome                     InitializeLastAPTime(m, our);
7503c65ebfc7SToomas Soome                     goto exit;
7504c65ebfc7SToomas Soome                 }
7505c65ebfc7SToomas Soome             }
7506c65ebfc7SToomas Soome #if 0
7507c65ebfc7SToomas Soome             else
7508c65ebfc7SToomas Soome             {
7509c65ebfc7SToomas Soome                 LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7510c65ebfc7SToomas Soome                 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign:  %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7511c65ebfc7SToomas Soome             }
7512c65ebfc7SToomas Soome #endif
7513c65ebfc7SToomas Soome         }
7514c65ebfc7SToomas Soome         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7515c65ebfc7SToomas Soome     }
7516c65ebfc7SToomas Soome     if (!FoundUpdate)
7517c65ebfc7SToomas Soome         LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7518c65ebfc7SToomas Soome exit:
7519c65ebfc7SToomas Soome     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7520c65ebfc7SToomas Soome }
7521c65ebfc7SToomas Soome 
FindIdenticalRecordInCache(const mDNS * const m,const ResourceRecord * const pktrr)7522c65ebfc7SToomas Soome mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7523c65ebfc7SToomas Soome {
7524c65ebfc7SToomas Soome     CacheGroup *cg = CacheGroupForRecord(m, pktrr);
7525c65ebfc7SToomas Soome     CacheRecord *rr;
7526c65ebfc7SToomas Soome     mDNSBool match;
7527c65ebfc7SToomas Soome     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7528c65ebfc7SToomas Soome     {
7529c65ebfc7SToomas Soome         if (!pktrr->InterfaceID)
7530c65ebfc7SToomas Soome         {
7531*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7532*472cd20dSToomas Soome             match = (pktrr->dnsservice == rr->resrec.dnsservice) ? mDNStrue : mDNSfalse;
7533*472cd20dSToomas Soome #else
7534*472cd20dSToomas Soome             const mDNSu32 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7535*472cd20dSToomas Soome             const mDNSu32 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7536c65ebfc7SToomas Soome             match = (id1 == id2);
7537*472cd20dSToomas Soome #endif
7538c65ebfc7SToomas Soome         }
7539c65ebfc7SToomas Soome         else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7540c65ebfc7SToomas Soome 
7541c65ebfc7SToomas Soome         if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7542c65ebfc7SToomas Soome     }
7543c65ebfc7SToomas Soome     return(rr);
7544c65ebfc7SToomas Soome }
DeregisterProxyRecord(mDNS * const m,AuthRecord * const rr)7545c65ebfc7SToomas Soome mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7546c65ebfc7SToomas Soome {
7547c65ebfc7SToomas Soome     rr->WakeUp.HMAC    = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7548c65ebfc7SToomas Soome     rr->RequireGoodbye = mDNSfalse;   // and we don't want to send goodbye for it
7549c65ebfc7SToomas Soome     mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7550c65ebfc7SToomas Soome     SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7551c65ebfc7SToomas Soome }
7552c65ebfc7SToomas Soome 
ClearKeepaliveProxyRecords(mDNS * const m,const OwnerOptData * const owner,AuthRecord * const thelist,const mDNSInterfaceID InterfaceID)7553c65ebfc7SToomas Soome mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7554c65ebfc7SToomas Soome {
7555c65ebfc7SToomas Soome     if (m->CurrentRecord)
7556c65ebfc7SToomas Soome         LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7557c65ebfc7SToomas Soome     m->CurrentRecord = thelist;
7558c65ebfc7SToomas Soome 
7559c65ebfc7SToomas Soome     // Normally, the RDATA of the keepalive record will be different each time and hence we always
7560c65ebfc7SToomas Soome     // clean up the keepalive record.
7561c65ebfc7SToomas Soome     while (m->CurrentRecord)
7562c65ebfc7SToomas Soome     {
7563c65ebfc7SToomas Soome         AuthRecord *const rr = m->CurrentRecord;
7564c65ebfc7SToomas Soome         if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7565c65ebfc7SToomas Soome         {
7566c65ebfc7SToomas Soome             if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7567c65ebfc7SToomas Soome             {
7568c65ebfc7SToomas Soome                 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7569c65ebfc7SToomas Soome                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7570c65ebfc7SToomas Soome                 DeregisterProxyRecord(m, rr);
7571c65ebfc7SToomas Soome             }
7572c65ebfc7SToomas Soome         }
7573c65ebfc7SToomas Soome         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7574c65ebfc7SToomas Soome         // new records could have been added to the end of the list as a result of that call.
7575c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7576c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
7577c65ebfc7SToomas Soome     }
7578c65ebfc7SToomas Soome }
7579c65ebfc7SToomas Soome 
7580c65ebfc7SToomas Soome // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7581c65ebfc7SToomas Soome // to check our lists and discard any stale duplicates of this record we already have
ClearIdenticalProxyRecords(mDNS * const m,const OwnerOptData * const owner,AuthRecord * const thelist)7582c65ebfc7SToomas Soome mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7583c65ebfc7SToomas Soome {
7584c65ebfc7SToomas Soome     if (m->CurrentRecord)
7585c65ebfc7SToomas Soome         LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7586c65ebfc7SToomas Soome     m->CurrentRecord = thelist;
7587c65ebfc7SToomas Soome     while (m->CurrentRecord)
7588c65ebfc7SToomas Soome     {
7589c65ebfc7SToomas Soome         AuthRecord *const rr = m->CurrentRecord;
7590c65ebfc7SToomas Soome         if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7591c65ebfc7SToomas Soome             if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7592c65ebfc7SToomas Soome             {
7593c65ebfc7SToomas Soome                 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7594c65ebfc7SToomas Soome                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7595c65ebfc7SToomas Soome                 DeregisterProxyRecord(m, rr);
7596c65ebfc7SToomas Soome             }
7597c65ebfc7SToomas Soome         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7598c65ebfc7SToomas Soome         // new records could have been added to the end of the list as a result of that call.
7599c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7600c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
7601c65ebfc7SToomas Soome     }
7602c65ebfc7SToomas Soome }
7603c65ebfc7SToomas Soome 
7604c65ebfc7SToomas Soome // Called from ProcessQuery when we get an mDNS packet with an owner record in it
ClearProxyRecords(mDNS * const m,const OwnerOptData * const owner,AuthRecord * const thelist)7605c65ebfc7SToomas Soome mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7606c65ebfc7SToomas Soome {
7607c65ebfc7SToomas Soome     if (m->CurrentRecord)
7608c65ebfc7SToomas Soome         LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7609c65ebfc7SToomas Soome     m->CurrentRecord = thelist;
7610c65ebfc7SToomas Soome     while (m->CurrentRecord)
7611c65ebfc7SToomas Soome     {
7612c65ebfc7SToomas Soome         AuthRecord *const rr = m->CurrentRecord;
7613c65ebfc7SToomas Soome         if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7614c65ebfc7SToomas Soome             if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7615c65ebfc7SToomas Soome             {
7616c65ebfc7SToomas Soome                 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7617c65ebfc7SToomas Soome                 {
7618c65ebfc7SToomas Soome                     // We don't do this here because we know that the host is waking up at this point, so we don't send
7619c65ebfc7SToomas Soome                     // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7620c65ebfc7SToomas Soome                     // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7621c65ebfc7SToomas Soome                     #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7622c65ebfc7SToomas Soome                     LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7623c65ebfc7SToomas Soome                            &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7624c65ebfc7SToomas Soome                     SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7625c65ebfc7SToomas Soome                     #endif
7626c65ebfc7SToomas Soome                 }
7627c65ebfc7SToomas Soome                 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7628c65ebfc7SToomas Soome                        m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7629c65ebfc7SToomas Soome                        &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7630c65ebfc7SToomas Soome                 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7631c65ebfc7SToomas Soome                 rr->WakeUp.HMAC = zeroEthAddr;  // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7632c65ebfc7SToomas Soome                 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7633c65ebfc7SToomas Soome                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7634c65ebfc7SToomas Soome                 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7635c65ebfc7SToomas Soome             }
7636c65ebfc7SToomas Soome         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7637c65ebfc7SToomas Soome         // new records could have been added to the end of the list as a result of that call.
7638c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7639c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
7640c65ebfc7SToomas Soome     }
7641c65ebfc7SToomas Soome }
7642c65ebfc7SToomas Soome 
7643c65ebfc7SToomas Soome // ProcessQuery examines a received query to see if we have any answers to give
ProcessQuery(mDNS * const m,const DNSMessage * const query,const mDNSu8 * const end,const mDNSAddr * srcaddr,const mDNSInterfaceID InterfaceID,mDNSBool LegacyQuery,mDNSBool QueryWasMulticast,mDNSBool QueryWasLocalUnicast,DNSMessage * const response)7644c65ebfc7SToomas Soome mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7645c65ebfc7SToomas Soome                                const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7646c65ebfc7SToomas Soome                                mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7647c65ebfc7SToomas Soome {
7648*472cd20dSToomas Soome     const mDNSBool FromLocalSubnet   = mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7649c65ebfc7SToomas Soome     AuthRecord   *ResponseRecords    = mDNSNULL;
7650c65ebfc7SToomas Soome     AuthRecord  **nrp                = &ResponseRecords;
7651c65ebfc7SToomas Soome 
7652c65ebfc7SToomas Soome #if POOF_ENABLED
76533b436d06SToomas Soome     mDNSBool    notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID);  // We don't run the POOF algorithm on D2D interfaces.
7654c65ebfc7SToomas Soome     CacheRecord  *ExpectedAnswers    = mDNSNULL;            // Records in our cache we expect to see updated
7655c65ebfc7SToomas Soome     CacheRecord **eap                = &ExpectedAnswers;
7656c65ebfc7SToomas Soome #endif // POOF_ENABLED
7657c65ebfc7SToomas Soome 
7658c65ebfc7SToomas Soome     DNSQuestion  *DupQuestions       = mDNSNULL;            // Our questions that are identical to questions in this packet
7659c65ebfc7SToomas Soome     DNSQuestion **dqp                = &DupQuestions;
7660c65ebfc7SToomas Soome     mDNSs32 delayresponse      = 0;
7661c65ebfc7SToomas Soome     mDNSBool SendLegacyResponse = mDNSfalse;
7662c65ebfc7SToomas Soome     const mDNSu8 *ptr;
7663c65ebfc7SToomas Soome     mDNSu8       *responseptr        = mDNSNULL;
7664c65ebfc7SToomas Soome     AuthRecord   *rr;
7665c65ebfc7SToomas Soome     int i;
7666c65ebfc7SToomas Soome 
7667c65ebfc7SToomas Soome     // ***
7668c65ebfc7SToomas Soome     // *** 1. Look in Additional Section for an OPT record
7669c65ebfc7SToomas Soome     // ***
7670c65ebfc7SToomas Soome     ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7671c65ebfc7SToomas Soome     if (ptr)
7672c65ebfc7SToomas Soome     {
7673c65ebfc7SToomas Soome         ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7674c65ebfc7SToomas Soome         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7675c65ebfc7SToomas Soome         {
7676c65ebfc7SToomas Soome             const rdataOPT *opt;
7677c65ebfc7SToomas Soome             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7678c65ebfc7SToomas Soome             // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7679c65ebfc7SToomas Soome             // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7680c65ebfc7SToomas Soome             for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7681c65ebfc7SToomas Soome                 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7682c65ebfc7SToomas Soome                 {
7683c65ebfc7SToomas Soome                     ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7684c65ebfc7SToomas Soome                     ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7685c65ebfc7SToomas Soome                 }
7686c65ebfc7SToomas Soome         }
7687c65ebfc7SToomas Soome         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7688c65ebfc7SToomas Soome     }
7689c65ebfc7SToomas Soome 
7690c65ebfc7SToomas Soome     // ***
7691c65ebfc7SToomas Soome     // *** 2. Parse Question Section and mark potential answers
7692c65ebfc7SToomas Soome     // ***
7693c65ebfc7SToomas Soome     ptr = query->data;
7694c65ebfc7SToomas Soome     for (i=0; i<query->h.numQuestions; i++)                     // For each question...
7695c65ebfc7SToomas Soome     {
7696c65ebfc7SToomas Soome         mDNSBool QuestionNeedsMulticastResponse;
7697c65ebfc7SToomas Soome         int NumAnswersForThisQuestion = 0;
7698c65ebfc7SToomas Soome         AuthRecord *NSECAnswer = mDNSNULL;
7699c65ebfc7SToomas Soome         DNSQuestion pktq, *q;
7700c65ebfc7SToomas Soome         ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7701c65ebfc7SToomas Soome         if (!ptr) goto exit;
7702c65ebfc7SToomas Soome 
7703c65ebfc7SToomas Soome         // The only queries that *need* a multicast response are:
7704c65ebfc7SToomas Soome         // * Queries sent via multicast
7705c65ebfc7SToomas Soome         // * from port 5353
7706c65ebfc7SToomas Soome         // * that don't have the kDNSQClass_UnicastResponse bit set
7707c65ebfc7SToomas Soome         // These queries need multicast responses because other clients will:
7708c65ebfc7SToomas Soome         // * suppress their own identical questions when they see these questions, and
7709c65ebfc7SToomas Soome         // * expire their cache records if they don't see the expected responses
7710c65ebfc7SToomas Soome         // For other queries, we may still choose to send the occasional multicast response anyway,
7711c65ebfc7SToomas Soome         // to keep our neighbours caches warm, and for ongoing conflict detection.
7712c65ebfc7SToomas Soome         QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7713c65ebfc7SToomas Soome 
7714c65ebfc7SToomas Soome         if (pktq.qclass & kDNSQClass_UnicastResponse)
7715c65ebfc7SToomas Soome             m->mDNSStats.UnicastBitInQueries++;
7716c65ebfc7SToomas Soome         else
7717c65ebfc7SToomas Soome             m->mDNSStats.NormalQueries++;
7718c65ebfc7SToomas Soome 
7719c65ebfc7SToomas Soome         // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7720c65ebfc7SToomas Soome         pktq.qclass &= ~kDNSQClass_UnicastResponse;
7721c65ebfc7SToomas Soome 
7722c65ebfc7SToomas Soome         // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7723c65ebfc7SToomas Soome         // can result in user callbacks which may change the record list and/or question list.
7724c65ebfc7SToomas Soome         // Also note: we just mark potential answer records here, without trying to build the
7725c65ebfc7SToomas Soome         // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7726c65ebfc7SToomas Soome         // from that list while we're in the middle of trying to build it.
7727c65ebfc7SToomas Soome         if (m->CurrentRecord)
7728c65ebfc7SToomas Soome             LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7729c65ebfc7SToomas Soome         m->CurrentRecord = m->ResourceRecords;
7730c65ebfc7SToomas Soome         while (m->CurrentRecord)
7731c65ebfc7SToomas Soome         {
7732c65ebfc7SToomas Soome             rr = m->CurrentRecord;
7733c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
7734*472cd20dSToomas Soome             if (AnyTypeRecordAnswersQuestion(rr, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7735c65ebfc7SToomas Soome             {
7736c65ebfc7SToomas Soome                 m->mDNSStats.MatchingAnswersForQueries++;
7737c65ebfc7SToomas Soome                 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7738c65ebfc7SToomas Soome                 {
7739c65ebfc7SToomas Soome                     if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7740c65ebfc7SToomas Soome                         ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7741c65ebfc7SToomas Soome                     else if (ResourceRecordIsValidAnswer(rr))
7742c65ebfc7SToomas Soome                     {
7743c65ebfc7SToomas Soome                         NumAnswersForThisQuestion++;
7744c65ebfc7SToomas Soome 
7745c65ebfc7SToomas Soome                         // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7746c65ebfc7SToomas Soome                         // unicast answer back to the source, because timeliness in answering probes is important.
7747c65ebfc7SToomas Soome 
7748c65ebfc7SToomas Soome                         // Notes:
7749c65ebfc7SToomas Soome                         // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7750c65ebfc7SToomas Soome                         // NR_AnswerTo == NR_AnswerUnicast   means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7751c65ebfc7SToomas Soome                         // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7752c65ebfc7SToomas Soome                         // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7753c65ebfc7SToomas Soome                         // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7754c65ebfc7SToomas Soome                         // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7755c65ebfc7SToomas Soome                         if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7756c65ebfc7SToomas Soome                         {
7757c65ebfc7SToomas Soome                             // We only mark this question for sending if it is at least one second since the last time we multicast it
7758c65ebfc7SToomas Soome                             // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7759c65ebfc7SToomas Soome                             // This is to guard against the case where someone blasts us with queries as fast as they can.
7760c65ebfc7SToomas Soome                             if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond ||
7761c65ebfc7SToomas Soome                                 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7762c65ebfc7SToomas Soome                                 rr->NR_AnswerTo = NR_AnswerMulticast;
7763c65ebfc7SToomas Soome                         }
7764c65ebfc7SToomas Soome                         else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7765c65ebfc7SToomas Soome                     }
7766c65ebfc7SToomas Soome                 }
7767c65ebfc7SToomas Soome                 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7768c65ebfc7SToomas Soome                 {
7769c65ebfc7SToomas Soome                     // If we don't have any answers for this question, but we do own another record with the same name,
7770c65ebfc7SToomas Soome                     // then we'll want to mark it to generate an NSEC record on this interface
7771c65ebfc7SToomas Soome                     if (!NSECAnswer) NSECAnswer = rr;
7772c65ebfc7SToomas Soome                 }
7773c65ebfc7SToomas Soome             }
7774c65ebfc7SToomas Soome         }
7775c65ebfc7SToomas Soome 
7776c65ebfc7SToomas Soome         if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7777c65ebfc7SToomas Soome         {
7778c65ebfc7SToomas Soome             NumAnswersForThisQuestion++;
7779c65ebfc7SToomas Soome             NSECAnswer->SendNSECNow = InterfaceID;
7780c65ebfc7SToomas Soome             m->NextScheduledResponse = m->timenow;
7781c65ebfc7SToomas Soome         }
7782c65ebfc7SToomas Soome 
7783c65ebfc7SToomas Soome         // If we couldn't answer this question, someone else might be able to,
7784c65ebfc7SToomas Soome         // so use random delay on response to reduce collisions
7785c65ebfc7SToomas Soome         if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond;  // Divided by 50 = 20ms
7786c65ebfc7SToomas Soome 
7787c65ebfc7SToomas Soome         if (query->h.flags.b[0] & kDNSFlag0_TC)
7788c65ebfc7SToomas Soome             m->mDNSStats.KnownAnswerMultiplePkts++;
7789c65ebfc7SToomas Soome         // We only do the following accelerated cache expiration and duplicate question suppression processing
7790c65ebfc7SToomas Soome         // for non-truncated multicast queries with multicast responses.
7791c65ebfc7SToomas Soome         // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7792c65ebfc7SToomas Soome         // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7793c65ebfc7SToomas Soome         // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7794c65ebfc7SToomas Soome         if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7795c65ebfc7SToomas Soome         {
7796c65ebfc7SToomas Soome #if POOF_ENABLED
77973b436d06SToomas Soome             if (notD2D)
77983b436d06SToomas Soome             {
7799c65ebfc7SToomas Soome                 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname);
7800c65ebfc7SToomas Soome                 CacheRecord *cr;
7801c65ebfc7SToomas Soome 
7802c65ebfc7SToomas Soome                 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7803c65ebfc7SToomas Soome                 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7804c65ebfc7SToomas Soome                 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7805*472cd20dSToomas Soome                 {
7806*472cd20dSToomas Soome                     if (SameNameCacheRecordAnswersQuestion(cr, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7807*472cd20dSToomas Soome                     {
7808c65ebfc7SToomas Soome                         if (!cr->NextInKAList && eap != &cr->NextInKAList)
7809c65ebfc7SToomas Soome                         {
7810c65ebfc7SToomas Soome                             *eap = cr;
7811c65ebfc7SToomas Soome                             eap = &cr->NextInKAList;
7812c65ebfc7SToomas Soome                         }
78133b436d06SToomas Soome                     }
7814*472cd20dSToomas Soome                 }
7815*472cd20dSToomas Soome             }
7816c65ebfc7SToomas Soome #endif // POOF_ENABLED
7817c65ebfc7SToomas Soome 
7818c65ebfc7SToomas Soome             // Check if this question is the same as any of mine.
7819c65ebfc7SToomas Soome             // We only do this for non-truncated queries. Right now it would be too complicated to try
7820c65ebfc7SToomas Soome             // to keep track of duplicate suppression state between multiple packets, especially when we
7821c65ebfc7SToomas Soome             // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7822c65ebfc7SToomas Soome             for (q = m->Questions; q; q=q->next)
7823*472cd20dSToomas Soome             {
7824*472cd20dSToomas Soome                 if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7825*472cd20dSToomas Soome                 {
7826c65ebfc7SToomas Soome                     if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7827*472cd20dSToomas Soome                     {
7828c65ebfc7SToomas Soome                         if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7829*472cd20dSToomas Soome                         {
7830c65ebfc7SToomas Soome                             if (q->qtype == pktq.qtype &&
7831c65ebfc7SToomas Soome                                 q->qclass == pktq.qclass &&
7832c65ebfc7SToomas Soome                                 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7833c65ebfc7SToomas Soome                             { *dqp = q; dqp = &q->NextInDQList; }
7834c65ebfc7SToomas Soome                         }
7835c65ebfc7SToomas Soome                     }
7836*472cd20dSToomas Soome                 }
7837*472cd20dSToomas Soome             }
7838c65ebfc7SToomas Soome         }
7839c65ebfc7SToomas Soome     }
7840c65ebfc7SToomas Soome 
7841c65ebfc7SToomas Soome     // ***
7842c65ebfc7SToomas Soome     // *** 3. Now we can safely build the list of marked answers
7843c65ebfc7SToomas Soome     // ***
7844c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)              // Now build our list of potential answers
7845c65ebfc7SToomas Soome         if (rr->NR_AnswerTo)                                    // If we marked the record...
7846c65ebfc7SToomas Soome             AddRecordToResponseList(&nrp, rr, mDNSNULL);        // ... add it to the list
7847c65ebfc7SToomas Soome 
7848c65ebfc7SToomas Soome     // ***
7849c65ebfc7SToomas Soome     // *** 4. Add additional records
7850c65ebfc7SToomas Soome     // ***
7851c65ebfc7SToomas Soome     AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7852c65ebfc7SToomas Soome 
7853c65ebfc7SToomas Soome     // ***
7854c65ebfc7SToomas Soome     // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7855c65ebfc7SToomas Soome     // ***
7856c65ebfc7SToomas Soome     for (i=0; i<query->h.numAnswers; i++)                       // For each record in the query's answer section...
7857c65ebfc7SToomas Soome     {
7858c65ebfc7SToomas Soome         // Get the record...
7859c65ebfc7SToomas Soome         CacheRecord *ourcacherr;
7860c65ebfc7SToomas Soome         ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7861c65ebfc7SToomas Soome         if (!ptr) goto exit;
7862c65ebfc7SToomas Soome         if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7863c65ebfc7SToomas Soome         {
7864c65ebfc7SToomas Soome             // See if this Known-Answer suppresses any of our currently planned answers
7865c65ebfc7SToomas Soome             for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7866c65ebfc7SToomas Soome             {
7867c65ebfc7SToomas Soome                 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7868c65ebfc7SToomas Soome                 {
7869c65ebfc7SToomas Soome                     m->mDNSStats.KnownAnswerSuppressions++;
7870c65ebfc7SToomas Soome                     rr->NR_AnswerTo = mDNSNULL;
7871c65ebfc7SToomas Soome                     rr->NR_AdditionalTo = mDNSNULL;
7872c65ebfc7SToomas Soome                 }
7873c65ebfc7SToomas Soome             }
7874c65ebfc7SToomas Soome 
7875c65ebfc7SToomas Soome             // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7876c65ebfc7SToomas Soome             for (rr=m->ResourceRecords; rr; rr=rr->next)
7877c65ebfc7SToomas Soome             {
7878c65ebfc7SToomas Soome                 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7879c65ebfc7SToomas Soome                 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7880c65ebfc7SToomas Soome                 {
7881c65ebfc7SToomas Soome                     if (srcaddr->type == mDNSAddrType_IPv4)
7882c65ebfc7SToomas Soome                     {
7883c65ebfc7SToomas Soome                         if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7884c65ebfc7SToomas Soome                     }
7885c65ebfc7SToomas Soome                     else if (srcaddr->type == mDNSAddrType_IPv6)
7886c65ebfc7SToomas Soome                     {
7887c65ebfc7SToomas Soome                         if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7888c65ebfc7SToomas Soome                     }
7889c65ebfc7SToomas Soome                     if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7890c65ebfc7SToomas Soome                     {
7891c65ebfc7SToomas Soome                         m->mDNSStats.KnownAnswerSuppressions++;
7892c65ebfc7SToomas Soome                         rr->ImmedAnswer  = mDNSNULL;
7893c65ebfc7SToomas Soome                         rr->ImmedUnicast = mDNSfalse;
7894c65ebfc7SToomas Soome     #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7895c65ebfc7SToomas Soome                         LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7896c65ebfc7SToomas Soome     #endif
7897c65ebfc7SToomas Soome                     }
7898c65ebfc7SToomas Soome                 }
7899c65ebfc7SToomas Soome             }
7900c65ebfc7SToomas Soome 
7901c65ebfc7SToomas Soome             ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7902c65ebfc7SToomas Soome 
7903c65ebfc7SToomas Soome #if POOF_ENABLED
79043b436d06SToomas Soome             if (notD2D)
79053b436d06SToomas Soome             {
7906c65ebfc7SToomas Soome                 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7907c65ebfc7SToomas Soome                 // any records that are suppressed by the Known Answer list in this packet.
7908c65ebfc7SToomas Soome                 eap = &ExpectedAnswers;
7909c65ebfc7SToomas Soome                 while (*eap)
7910c65ebfc7SToomas Soome                 {
7911c65ebfc7SToomas Soome                     CacheRecord *cr = *eap;
7912c65ebfc7SToomas Soome                     if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7913c65ebfc7SToomas Soome                     { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7914c65ebfc7SToomas Soome                     else eap = &cr->NextInKAList;
7915c65ebfc7SToomas Soome                 }
79163b436d06SToomas Soome             }
7917c65ebfc7SToomas Soome #endif // POOF_ENABLED
7918c65ebfc7SToomas Soome 
7919c65ebfc7SToomas Soome             // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7920c65ebfc7SToomas Soome             if (!ourcacherr)
7921c65ebfc7SToomas Soome             {
7922c65ebfc7SToomas Soome                 dqp = &DupQuestions;
7923c65ebfc7SToomas Soome                 while (*dqp)
7924c65ebfc7SToomas Soome                 {
7925c65ebfc7SToomas Soome                     DNSQuestion *q = *dqp;
7926*472cd20dSToomas Soome                     if (CacheRecordAnswersQuestion(&m->rec.r, q))
7927c65ebfc7SToomas Soome                     { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7928c65ebfc7SToomas Soome                     else dqp = &q->NextInDQList;
7929c65ebfc7SToomas Soome                 }
7930c65ebfc7SToomas Soome             }
7931c65ebfc7SToomas Soome         }
7932c65ebfc7SToomas Soome         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7933c65ebfc7SToomas Soome     }
7934c65ebfc7SToomas Soome 
7935c65ebfc7SToomas Soome     // ***
7936c65ebfc7SToomas Soome     // *** 6. Cancel any additionals that were added because of now-deleted records
7937c65ebfc7SToomas Soome     // ***
7938c65ebfc7SToomas Soome     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7939c65ebfc7SToomas Soome         if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7940c65ebfc7SToomas Soome         { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7941c65ebfc7SToomas Soome 
7942c65ebfc7SToomas Soome     // ***
7943c65ebfc7SToomas Soome     // *** 7. Mark the send flags on the records we plan to send
7944c65ebfc7SToomas Soome     // ***
7945c65ebfc7SToomas Soome     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7946c65ebfc7SToomas Soome     {
7947c65ebfc7SToomas Soome         if (rr->NR_AnswerTo)
7948c65ebfc7SToomas Soome         {
7949c65ebfc7SToomas Soome             mDNSBool SendMulticastResponse = mDNSfalse;     // Send modern multicast response
7950c65ebfc7SToomas Soome             mDNSBool SendUnicastResponse   = mDNSfalse;     // Send modern unicast response (not legacy unicast response)
7951c65ebfc7SToomas Soome 
7952c65ebfc7SToomas Soome             // If it's been one TTL/4 since we multicast this, then send a multicast response
7953c65ebfc7SToomas Soome             // for conflict detection, etc.
7954c65ebfc7SToomas Soome             if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4)
7955c65ebfc7SToomas Soome             {
7956c65ebfc7SToomas Soome                 SendMulticastResponse = mDNStrue;
7957c65ebfc7SToomas Soome                 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7958c65ebfc7SToomas Soome                 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7959c65ebfc7SToomas Soome                 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7960c65ebfc7SToomas Soome                 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7961c65ebfc7SToomas Soome                 {
7962c65ebfc7SToomas Soome                     m->mDNSStats.UnicastDemotedToMulticast++;
7963c65ebfc7SToomas Soome                     rr->NR_AnswerTo = NR_AnswerMulticast;
7964c65ebfc7SToomas Soome                 }
7965c65ebfc7SToomas Soome             }
7966c65ebfc7SToomas Soome 
7967c65ebfc7SToomas Soome             // If the client insists on a multicast response, then we'd better send one
7968c65ebfc7SToomas Soome             if      (rr->NR_AnswerTo == NR_AnswerMulticast)
7969c65ebfc7SToomas Soome             {
7970c65ebfc7SToomas Soome                 m->mDNSStats.MulticastResponses++;
7971c65ebfc7SToomas Soome                 SendMulticastResponse = mDNStrue;
7972c65ebfc7SToomas Soome             }
7973c65ebfc7SToomas Soome             else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7974c65ebfc7SToomas Soome             {
7975c65ebfc7SToomas Soome                 m->mDNSStats.UnicastResponses++;
7976c65ebfc7SToomas Soome                 SendUnicastResponse   = mDNStrue;
7977c65ebfc7SToomas Soome             }
7978c65ebfc7SToomas Soome             else if (rr->NR_AnswerTo)
7979c65ebfc7SToomas Soome             {
7980c65ebfc7SToomas Soome                 SendLegacyResponse    = mDNStrue;
7981c65ebfc7SToomas Soome             }
7982c65ebfc7SToomas Soome 
7983c65ebfc7SToomas Soome             if (SendMulticastResponse || SendUnicastResponse)
7984c65ebfc7SToomas Soome             {
7985c65ebfc7SToomas Soome #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7986c65ebfc7SToomas Soome                 rr->ImmedAnswerMarkTime = m->timenow;
7987c65ebfc7SToomas Soome #endif
7988c65ebfc7SToomas Soome                 m->NextScheduledResponse = m->timenow;
7989c65ebfc7SToomas Soome                 // If we're already planning to send this on another interface, just send it on all interfaces
7990c65ebfc7SToomas Soome                 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7991c65ebfc7SToomas Soome                     rr->ImmedAnswer = mDNSInterfaceMark;
7992c65ebfc7SToomas Soome                 else
7993c65ebfc7SToomas Soome                 {
7994c65ebfc7SToomas Soome                     rr->ImmedAnswer = InterfaceID;          // Record interface to send it on
7995c65ebfc7SToomas Soome                     if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7996c65ebfc7SToomas Soome                     if (srcaddr->type == mDNSAddrType_IPv4)
7997c65ebfc7SToomas Soome                     {
7998c65ebfc7SToomas Soome                         if      (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7999c65ebfc7SToomas Soome                         else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
8000c65ebfc7SToomas Soome                     }
8001c65ebfc7SToomas Soome                     else if (srcaddr->type == mDNSAddrType_IPv6)
8002c65ebfc7SToomas Soome                     {
8003c65ebfc7SToomas Soome                         if      (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
8004c65ebfc7SToomas Soome                         else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
8005c65ebfc7SToomas Soome                     }
8006c65ebfc7SToomas Soome                 }
8007c65ebfc7SToomas Soome             }
8008c65ebfc7SToomas Soome             // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
8009c65ebfc7SToomas Soome             // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
8010c65ebfc7SToomas Soome             // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
8011c65ebfc7SToomas Soome             // else, for a simple unique record reply, we can reply immediately; no need for delay
8012c65ebfc7SToomas Soome             if      (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20;            // Divided by 50 = 400ms
8013c65ebfc7SToomas Soome             else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond;      // Divided by 50 = 20ms
8014c65ebfc7SToomas Soome         }
8015c65ebfc7SToomas Soome         else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
8016c65ebfc7SToomas Soome         {
8017c65ebfc7SToomas Soome             // Since additional records are an optimization anyway, we only ever send them on one interface at a time
8018c65ebfc7SToomas Soome             // If two clients on different interfaces do queries that invoke the same optional additional answer,
8019c65ebfc7SToomas Soome             // then the earlier client is out of luck
8020c65ebfc7SToomas Soome             rr->ImmedAdditional = InterfaceID;
8021c65ebfc7SToomas Soome             // No need to set m->NextScheduledResponse here
8022c65ebfc7SToomas Soome             // We'll send these additional records when we send them, or not, as the case may be
8023c65ebfc7SToomas Soome         }
8024c65ebfc7SToomas Soome     }
8025c65ebfc7SToomas Soome 
8026c65ebfc7SToomas Soome     // ***
8027c65ebfc7SToomas Soome     // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
8028c65ebfc7SToomas Soome     // ***
8029c65ebfc7SToomas Soome     if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
8030c65ebfc7SToomas Soome     {
8031c65ebfc7SToomas Soome #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8032c65ebfc7SToomas Soome         mDNSs32 oldss = m->SuppressSending;
8033c65ebfc7SToomas Soome         if (oldss && delayresponse)
8034c65ebfc7SToomas Soome             LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
8035c65ebfc7SToomas Soome #endif
8036c65ebfc7SToomas Soome         // Pick a random delay:
8037c65ebfc7SToomas Soome         // We start with the base delay chosen above (typically either 1 second or 20 seconds),
8038c65ebfc7SToomas Soome         // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
8039c65ebfc7SToomas Soome         // This is an integer value, with resolution determined by the platform clock rate.
8040c65ebfc7SToomas Soome         // We then divide that by 50 to get the delay value in ticks. We defer the division until last
8041c65ebfc7SToomas Soome         // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
8042c65ebfc7SToomas Soome         // The +49 before dividing is to ensure we round up, not down, to ensure that even
8043c65ebfc7SToomas Soome         // on platforms where the native clock rate is less than fifty ticks per second,
8044c65ebfc7SToomas Soome         // we still guarantee that the final calculated delay is at least one platform tick.
8045c65ebfc7SToomas Soome         // We want to make sure we don't ever allow the delay to be zero ticks,
8046c65ebfc7SToomas Soome         // because if that happens we'll fail the Bonjour Conformance Test.
8047c65ebfc7SToomas Soome         // Our final computed delay is 20-120ms for normal delayed replies,
8048c65ebfc7SToomas Soome         // or 400-500ms in the case of multi-packet known-answer lists.
8049c65ebfc7SToomas Soome         m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
8050c65ebfc7SToomas Soome         if (m->SuppressSending == 0) m->SuppressSending = 1;
8051c65ebfc7SToomas Soome #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8052c65ebfc7SToomas Soome         if (oldss && delayresponse)
8053c65ebfc7SToomas Soome             LogMsg("Set     SuppressSending to   %5ld", m->SuppressSending - m->timenow);
8054c65ebfc7SToomas Soome #endif
8055c65ebfc7SToomas Soome     }
8056c65ebfc7SToomas Soome 
8057c65ebfc7SToomas Soome     // ***
8058c65ebfc7SToomas Soome     // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
8059c65ebfc7SToomas Soome     // ***
8060c65ebfc7SToomas Soome     if (SendLegacyResponse)
8061c65ebfc7SToomas Soome         responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
8062c65ebfc7SToomas Soome 
8063c65ebfc7SToomas Soome exit:
8064c65ebfc7SToomas Soome     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8065c65ebfc7SToomas Soome 
8066c65ebfc7SToomas Soome     // ***
8067c65ebfc7SToomas Soome     // *** 10. Finally, clear our link chains ready for use next time
8068c65ebfc7SToomas Soome     // ***
8069c65ebfc7SToomas Soome     while (ResponseRecords)
8070c65ebfc7SToomas Soome     {
8071c65ebfc7SToomas Soome         rr = ResponseRecords;
8072c65ebfc7SToomas Soome         ResponseRecords = rr->NextResponse;
8073c65ebfc7SToomas Soome         rr->NextResponse    = mDNSNULL;
8074c65ebfc7SToomas Soome         rr->NR_AnswerTo     = mDNSNULL;
8075c65ebfc7SToomas Soome         rr->NR_AdditionalTo = mDNSNULL;
8076c65ebfc7SToomas Soome     }
8077c65ebfc7SToomas Soome 
8078c65ebfc7SToomas Soome #if POOF_ENABLED
80793b436d06SToomas Soome     while (ExpectedAnswers && notD2D)
8080c65ebfc7SToomas Soome     {
8081c65ebfc7SToomas Soome         CacheRecord *cr = ExpectedAnswers;
8082c65ebfc7SToomas Soome         ExpectedAnswers = cr->NextInKAList;
8083c65ebfc7SToomas Soome         cr->NextInKAList = mDNSNULL;
8084c65ebfc7SToomas Soome 
8085c65ebfc7SToomas Soome         // For non-truncated queries, we can definitively say that we should expect
8086c65ebfc7SToomas Soome         // to be seeing a response for any records still left in the ExpectedAnswers list
8087c65ebfc7SToomas Soome         if (!(query->h.flags.b[0] & kDNSFlag0_TC))
8088c65ebfc7SToomas Soome             if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4)
8089c65ebfc7SToomas Soome             {
8090c65ebfc7SToomas Soome                 cr->UnansweredQueries++;
8091c65ebfc7SToomas Soome                 cr->LastUnansweredTime = m->timenow;
8092c65ebfc7SToomas Soome                 if (cr->UnansweredQueries > 1)
8093c65ebfc7SToomas Soome                         debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr));
8094c65ebfc7SToomas Soome                 SetNextCacheCheckTimeForRecord(m, cr);
8095c65ebfc7SToomas Soome             }
8096c65ebfc7SToomas Soome 
8097c65ebfc7SToomas Soome         // If we've seen multiple unanswered queries for this record,
8098c65ebfc7SToomas Soome         // then mark it to expire in five seconds if we don't get a response by then.
8099c65ebfc7SToomas Soome         if (cr->UnansweredQueries >= MaxUnansweredQueries)
8100c65ebfc7SToomas Soome         {
8101c65ebfc7SToomas Soome             // Only show debugging message if this record was not about to expire anyway
8102c65ebfc7SToomas Soome             if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond)
8103c65ebfc7SToomas Soome                     LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8104c65ebfc7SToomas Soome                        cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr));
8105c65ebfc7SToomas Soome 
8106c65ebfc7SToomas Soome             m->mDNSStats.PoofCacheDeletions++;
8107c65ebfc7SToomas Soome             mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8108c65ebfc7SToomas Soome         }
8109c65ebfc7SToomas Soome     }
8110c65ebfc7SToomas Soome #endif // POOF_ENABLED
8111c65ebfc7SToomas Soome 
8112c65ebfc7SToomas Soome     while (DupQuestions)
8113c65ebfc7SToomas Soome     {
8114c65ebfc7SToomas Soome         DNSQuestion *q = DupQuestions;
8115c65ebfc7SToomas Soome         DupQuestions = q->NextInDQList;
8116c65ebfc7SToomas Soome         q->NextInDQList = mDNSNULL;
8117c65ebfc7SToomas Soome         RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
8118c65ebfc7SToomas Soome         debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
8119c65ebfc7SToomas Soome                srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
8120c65ebfc7SToomas Soome     }
8121c65ebfc7SToomas Soome     return(responseptr);
8122c65ebfc7SToomas Soome }
8123c65ebfc7SToomas Soome 
mDNSCoreReceiveQuery(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * const end,const mDNSAddr * srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,mDNSIPPort dstport,const mDNSInterfaceID InterfaceID)8124c65ebfc7SToomas Soome mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
8125c65ebfc7SToomas Soome                                     const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8126c65ebfc7SToomas Soome                                     const mDNSInterfaceID InterfaceID)
8127c65ebfc7SToomas Soome {
8128c65ebfc7SToomas Soome     mDNSu8    *responseend = mDNSNULL;
8129c65ebfc7SToomas Soome     mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
8130c65ebfc7SToomas Soome                                     !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8131c65ebfc7SToomas Soome 
8132c65ebfc7SToomas Soome     if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr)))
8133c65ebfc7SToomas Soome     {
8134c65ebfc7SToomas Soome         const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID";
8135c65ebfc7SToomas Soome         LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8136c65ebfc7SToomas Soome                "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8137c65ebfc7SToomas Soome                srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8138c65ebfc7SToomas Soome                msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
8139c65ebfc7SToomas Soome                msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
8140c65ebfc7SToomas Soome                msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
8141c65ebfc7SToomas Soome                msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data, reason);
8142c65ebfc7SToomas Soome         return;
8143c65ebfc7SToomas Soome     }
8144c65ebfc7SToomas Soome 
8145c65ebfc7SToomas Soome     verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8146c65ebfc7SToomas Soome                   "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8147c65ebfc7SToomas Soome                   srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8148c65ebfc7SToomas Soome                   msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
8149c65ebfc7SToomas Soome                   msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
8150c65ebfc7SToomas Soome                   msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
8151c65ebfc7SToomas Soome                   msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
8152c65ebfc7SToomas Soome 
8153c65ebfc7SToomas Soome     responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
8154c65ebfc7SToomas Soome                                !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
8155c65ebfc7SToomas Soome 
8156c65ebfc7SToomas Soome     if (responseend)    // If responseend is non-null, that means we built a unicast response packet
8157c65ebfc7SToomas Soome     {
8158c65ebfc7SToomas Soome         debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8159c65ebfc7SToomas Soome                m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
8160c65ebfc7SToomas Soome                m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
8161c65ebfc7SToomas Soome                m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
8162c65ebfc7SToomas Soome                srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
8163*472cd20dSToomas Soome         mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSfalse);
8164c65ebfc7SToomas Soome     }
8165c65ebfc7SToomas Soome }
8166c65ebfc7SToomas Soome 
8167c65ebfc7SToomas Soome #if 0
8168c65ebfc7SToomas Soome mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
8169c65ebfc7SToomas Soome {
8170c65ebfc7SToomas Soome     DNSServer *s;
8171c65ebfc7SToomas Soome     (void)m; // Unused
8172c65ebfc7SToomas Soome     (void)srcaddr; // Unused
8173c65ebfc7SToomas Soome     for (s = m->DNSServers; s; s = s->next)
8174c65ebfc7SToomas Soome         if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
8175c65ebfc7SToomas Soome     return(mDNSfalse);
8176c65ebfc7SToomas Soome }
8177c65ebfc7SToomas Soome #endif
8178c65ebfc7SToomas Soome 
8179c65ebfc7SToomas Soome struct UDPSocket_struct
8180c65ebfc7SToomas Soome {
8181c65ebfc7SToomas Soome     mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8182c65ebfc7SToomas Soome };
8183c65ebfc7SToomas Soome 
ExpectingUnicastResponseForQuestion(const mDNS * const m,const mDNSIPPort port,const mDNSOpaque16 id,const DNSQuestion * const question,mDNSBool tcp)8184*472cd20dSToomas Soome mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port,
8185*472cd20dSToomas Soome     const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
8186c65ebfc7SToomas Soome {
8187c65ebfc7SToomas Soome     DNSQuestion *q;
8188c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next)
8189c65ebfc7SToomas Soome     {
8190c65ebfc7SToomas Soome         if (!tcp && !q->LocalSocket) continue;
8191c65ebfc7SToomas Soome         if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port)       &&
8192c65ebfc7SToomas Soome             q->qtype                  == question->qtype     &&
8193c65ebfc7SToomas Soome             q->qclass                 == question->qclass    &&
8194c65ebfc7SToomas Soome             q->qnamehash              == question->qnamehash &&
8195c65ebfc7SToomas Soome             SameDomainName(&q->qname, &question->qname))
81963b436d06SToomas Soome         {
81973b436d06SToomas Soome             if (mDNSSameOpaque16(q->TargetQID, id)) return(q);
81983b436d06SToomas Soome             else
81993b436d06SToomas Soome             {
82003b436d06SToomas Soome                 return(mDNSNULL);
82013b436d06SToomas Soome             }
82023b436d06SToomas Soome         }
8203c65ebfc7SToomas Soome     }
8204c65ebfc7SToomas Soome     return(mDNSNULL);
8205c65ebfc7SToomas Soome }
8206c65ebfc7SToomas Soome 
8207c65ebfc7SToomas Soome // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8208c65ebfc7SToomas Soome // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
ExpectingUnicastResponseForRecord(mDNS * const m,const mDNSAddr * const srcaddr,const mDNSBool SrcLocal,const mDNSIPPort port,const mDNSOpaque16 id,const CacheRecord * const rr,mDNSBool tcp)8209c65ebfc7SToomas Soome mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
8210c65ebfc7SToomas Soome                                                          const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
8211c65ebfc7SToomas Soome {
8212c65ebfc7SToomas Soome     DNSQuestion *q;
8213c65ebfc7SToomas Soome     (void)id;
8214c65ebfc7SToomas Soome 
8215c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next)
8216c65ebfc7SToomas Soome     {
8217c65ebfc7SToomas Soome         if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
8218c65ebfc7SToomas Soome         {
8219c65ebfc7SToomas Soome             if (!mDNSOpaque16IsZero(q->TargetQID))
8220c65ebfc7SToomas Soome             {
8221c65ebfc7SToomas Soome                 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
8222c65ebfc7SToomas Soome 
8223c65ebfc7SToomas Soome                 if (mDNSSameOpaque16(q->TargetQID, id))
8224c65ebfc7SToomas Soome                 {
8225c65ebfc7SToomas Soome                     mDNSIPPort srcp;
8226c65ebfc7SToomas Soome                     if (!tcp)
8227c65ebfc7SToomas Soome                     {
82283b436d06SToomas Soome 			if (q->LocalSocket)
82293b436d06SToomas Soome                             srcp = q->LocalSocket->port;
82303b436d06SToomas Soome 			else
82313b436d06SToomas Soome                             srcp = zeroIPPort;
8232c65ebfc7SToomas Soome                     }
8233c65ebfc7SToomas Soome                     else
8234c65ebfc7SToomas Soome                     {
8235c65ebfc7SToomas Soome                         srcp = q->tcpSrcPort;
8236c65ebfc7SToomas Soome                     }
8237c65ebfc7SToomas Soome                     if (mDNSSameIPPort(srcp, port)) return(q);
8238c65ebfc7SToomas Soome 
8239c65ebfc7SToomas Soome                     //  if (mDNSSameAddress(srcaddr, &q->Target))                   return(mDNStrue);
8240c65ebfc7SToomas Soome                     //  if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8241c65ebfc7SToomas Soome                     //  if (TrustedSource(m, srcaddr))                              return(mDNStrue);
8242*472cd20dSToomas Soome                     LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8243*472cd20dSToomas Soome                             q->qname.c, DNSTypeName(q->qtype), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
8244c65ebfc7SToomas Soome                     return(mDNSNULL);
8245c65ebfc7SToomas Soome                 }
8246c65ebfc7SToomas Soome             }
8247c65ebfc7SToomas Soome             else
8248c65ebfc7SToomas Soome             {
8249c65ebfc7SToomas Soome                 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
8250c65ebfc7SToomas Soome                     return(q);
8251c65ebfc7SToomas Soome             }
8252c65ebfc7SToomas Soome         }
8253c65ebfc7SToomas Soome     }
8254c65ebfc7SToomas Soome     return(mDNSNULL);
8255c65ebfc7SToomas Soome }
8256c65ebfc7SToomas Soome 
8257c65ebfc7SToomas Soome // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8258c65ebfc7SToomas Soome // Currently this applies only to rdata types containing more than one domainname,
8259c65ebfc7SToomas Soome // or types where the domainname is not the last item in the structure.
GetRDLengthMem(const ResourceRecord * const rr)8260c65ebfc7SToomas Soome mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
8261c65ebfc7SToomas Soome {
8262c65ebfc7SToomas Soome     switch (rr->rrtype)
8263c65ebfc7SToomas Soome     {
8264c65ebfc7SToomas Soome     case kDNSType_SOA: return sizeof(rdataSOA);
8265c65ebfc7SToomas Soome     case kDNSType_RP:  return sizeof(rdataRP);
8266c65ebfc7SToomas Soome     case kDNSType_PX:  return sizeof(rdataPX);
8267c65ebfc7SToomas Soome     default:           return rr->rdlength;
8268c65ebfc7SToomas Soome     }
8269c65ebfc7SToomas Soome }
8270c65ebfc7SToomas Soome 
CreateNewCacheEntry(mDNS * const m,const mDNSu32 slot,CacheGroup * cg,mDNSs32 delay,mDNSBool Add,const mDNSAddr * sourceAddress)8271c65ebfc7SToomas Soome mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
8272c65ebfc7SToomas Soome {
8273c65ebfc7SToomas Soome     CacheRecord *rr = mDNSNULL;
8274c65ebfc7SToomas Soome     mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
8275c65ebfc7SToomas Soome 
8276c65ebfc7SToomas Soome     if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
8277c65ebfc7SToomas Soome 
8278c65ebfc7SToomas Soome     //if (RDLength > InlineCacheRDSize)
8279c65ebfc7SToomas Soome     //  LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8280c65ebfc7SToomas Soome 
8281c65ebfc7SToomas Soome     if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
8282c65ebfc7SToomas Soome     if (cg) rr = GetCacheRecord(m, cg, RDLength);   // Make a cache record, being careful not to recycle cg
8283c65ebfc7SToomas Soome     if (!rr) NoCacheAnswer(m, &m->rec.r);
8284c65ebfc7SToomas Soome     else
8285c65ebfc7SToomas Soome     {
8286c65ebfc7SToomas Soome         RData *saveptr              = rr->resrec.rdata;     // Save the rr->resrec.rdata pointer
8287c65ebfc7SToomas Soome         *rr                         = m->rec.r;             // Block copy the CacheRecord object
8288*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8289*472cd20dSToomas Soome         mdns_retain_null_safe(rr->resrec.dnsservice);
8290*472cd20dSToomas Soome #endif
8291c65ebfc7SToomas Soome         rr->resrec.rdata            = saveptr;              // Restore rr->resrec.rdata after the structure assignment
8292c65ebfc7SToomas Soome         rr->resrec.name             = cg->name;             // And set rr->resrec.name to point into our CacheGroup header
82933b436d06SToomas Soome         rr->resrec.mortality        = Mortality_Mortal;
8294*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8295*472cd20dSToomas Soome         rr->resrec.dnssec_result    = dnssec_indeterminate; // Set the DNSSEC validation result of a record as "indeterminate" by default.
8296*472cd20dSToomas Soome #endif
8297c65ebfc7SToomas Soome 
8298c65ebfc7SToomas Soome         rr->DelayDelivery = delay;
8299c65ebfc7SToomas Soome 
8300c65ebfc7SToomas Soome         // If this is an oversized record with external storage allocated, copy rdata to external storage
8301c65ebfc7SToomas Soome         if      (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
8302c65ebfc7SToomas Soome             LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8303c65ebfc7SToomas Soome         else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
8304c65ebfc7SToomas Soome             LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8305c65ebfc7SToomas Soome         if (RDLength > InlineCacheRDSize)
8306c65ebfc7SToomas Soome             mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
8307c65ebfc7SToomas Soome 
8308c65ebfc7SToomas Soome         rr->next = mDNSNULL;                    // Clear 'next' pointer
8309c65ebfc7SToomas Soome         rr->soa  = mDNSNULL;
8310c65ebfc7SToomas Soome 
8311c65ebfc7SToomas Soome         if (sourceAddress)
8312c65ebfc7SToomas Soome             rr->sourceAddress = *sourceAddress;
8313c65ebfc7SToomas Soome 
8314c65ebfc7SToomas Soome         if (!rr->resrec.InterfaceID)
8315c65ebfc7SToomas Soome         {
8316c65ebfc7SToomas Soome             m->rrcache_totalused_unicast += rr->resrec.rdlength;
8317c65ebfc7SToomas Soome         }
8318c65ebfc7SToomas Soome 
8319*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8320*472cd20dSToomas Soome         if (rr != mDNSNULL)
8321*472cd20dSToomas Soome         {
8322*472cd20dSToomas Soome             rr->denial_of_existence_records = mDNSNULL;
8323*472cd20dSToomas Soome         }
8324*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8325*472cd20dSToomas Soome 
8326c65ebfc7SToomas Soome         if (Add)
8327c65ebfc7SToomas Soome         {
8328c65ebfc7SToomas Soome             *(cg->rrcache_tail) = rr;               // Append this record to tail of cache slot list
8329c65ebfc7SToomas Soome             cg->rrcache_tail = &(rr->next);         // Advance tail pointer
8330c65ebfc7SToomas Soome             CacheRecordAdd(m, rr);  // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8331c65ebfc7SToomas Soome         }
8332c65ebfc7SToomas Soome         else
8333c65ebfc7SToomas Soome         {
8334c65ebfc7SToomas Soome             // Can't use the "cg->name" if we are not adding to the cache as the
8335c65ebfc7SToomas Soome             // CacheGroup may be released anytime if it is empty
8336*472cd20dSToomas Soome             domainname *name = (domainname *) mDNSPlatformMemAllocate(DomainNameLength(cg->name));
8337c65ebfc7SToomas Soome             if (name)
8338c65ebfc7SToomas Soome             {
8339c65ebfc7SToomas Soome                 AssignDomainName(name, cg->name);
8340c65ebfc7SToomas Soome                 rr->resrec.name   = name;
8341c65ebfc7SToomas Soome             }
8342c65ebfc7SToomas Soome             else
8343c65ebfc7SToomas Soome             {
8344c65ebfc7SToomas Soome                 ReleaseCacheRecord(m, rr);
8345c65ebfc7SToomas Soome                 NoCacheAnswer(m, &m->rec.r);
8346c65ebfc7SToomas Soome                 rr = mDNSNULL;
8347c65ebfc7SToomas Soome             }
8348c65ebfc7SToomas Soome         }
8349c65ebfc7SToomas Soome     }
8350c65ebfc7SToomas Soome     return(rr);
8351c65ebfc7SToomas Soome }
8352c65ebfc7SToomas Soome 
RefreshCacheRecordCacheGroupOrder(CacheGroup * cg,CacheRecord * cr)8353*472cd20dSToomas Soome mDNSlocal void RefreshCacheRecordCacheGroupOrder(CacheGroup *cg, CacheRecord *cr)
8354*472cd20dSToomas Soome {   //  Move the cache record to the tail of the cache group to maintain a fresh ordering
8355*472cd20dSToomas Soome     if (cg->rrcache_tail != &cr->next)          // If not already at the tail
8356*472cd20dSToomas Soome     {
8357*472cd20dSToomas Soome         CacheRecord **rp;
8358*472cd20dSToomas Soome         for (rp = &cg->members; *rp; rp = &(*rp)->next)
8359*472cd20dSToomas Soome         {
8360*472cd20dSToomas Soome             if (*rp == cr)                      // This item points to this record
8361*472cd20dSToomas Soome             {
8362*472cd20dSToomas Soome                 *rp = cr->next;                 // Remove this record
8363*472cd20dSToomas Soome                 break;
8364*472cd20dSToomas Soome             }
8365*472cd20dSToomas Soome         }
8366*472cd20dSToomas Soome         cr->next = mDNSNULL;                    // This record is now last
8367*472cd20dSToomas Soome         *(cg->rrcache_tail) = cr;               // Append this record to tail of cache group
8368*472cd20dSToomas Soome         cg->rrcache_tail = &(cr->next);         // Advance tail pointer
8369*472cd20dSToomas Soome     }
8370*472cd20dSToomas Soome }
8371*472cd20dSToomas Soome 
RefreshCacheRecord(mDNS * const m,CacheRecord * rr,mDNSu32 ttl)8372c65ebfc7SToomas Soome mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8373c65ebfc7SToomas Soome {
8374c65ebfc7SToomas Soome     rr->TimeRcvd             = m->timenow;
8375c65ebfc7SToomas Soome     rr->resrec.rroriginalttl = ttl;
8376c65ebfc7SToomas Soome     rr->UnansweredQueries = 0;
83773b436d06SToomas Soome     if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal;
8378c65ebfc7SToomas Soome     SetNextCacheCheckTimeForRecord(m, rr);
8379c65ebfc7SToomas Soome }
8380c65ebfc7SToomas Soome 
GrantCacheExtensions(mDNS * const m,DNSQuestion * q,mDNSu32 lease)8381c65ebfc7SToomas Soome mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8382c65ebfc7SToomas Soome {
8383c65ebfc7SToomas Soome     CacheRecord *rr;
8384c65ebfc7SToomas Soome     CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname);
8385c65ebfc7SToomas Soome     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8386c65ebfc7SToomas Soome         if (rr->CRActiveQuestion == q)
8387c65ebfc7SToomas Soome         {
8388c65ebfc7SToomas Soome             //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8389c65ebfc7SToomas Soome             RefreshCacheRecord(m, rr, lease);
8390c65ebfc7SToomas Soome         }
8391c65ebfc7SToomas Soome }
8392c65ebfc7SToomas Soome 
GetEffectiveTTL(const uDNS_LLQType LLQType,mDNSu32 ttl)8393c65ebfc7SToomas Soome mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl)      // TTL in seconds
8394c65ebfc7SToomas Soome {
8395c65ebfc7SToomas Soome     if      (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8396c65ebfc7SToomas Soome     else if (LLQType == uDNS_LLQ_Events)
8397c65ebfc7SToomas Soome     {
8398c65ebfc7SToomas Soome         // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8399c65ebfc7SToomas Soome         if (ttl == 0xFFFFFFFF) ttl = 0;
8400c65ebfc7SToomas Soome         else ttl = kLLQ_DefLease;
8401c65ebfc7SToomas Soome     }
8402c65ebfc7SToomas Soome     else    // else not LLQ (standard uDNS response)
8403c65ebfc7SToomas Soome     {
8404c65ebfc7SToomas Soome         // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8405c65ebfc7SToomas Soome         // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8406c65ebfc7SToomas Soome         if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8407c65ebfc7SToomas Soome 
8408c65ebfc7SToomas Soome         ttl = RRAdjustTTL(ttl);
8409c65ebfc7SToomas Soome 
8410c65ebfc7SToomas Soome         // For mDNS, TTL zero means "delete this record"
8411c65ebfc7SToomas Soome         // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8412c65ebfc7SToomas Soome         // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8413c65ebfc7SToomas Soome         // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8414c65ebfc7SToomas Soome         // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8415c65ebfc7SToomas Soome         // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8416c65ebfc7SToomas Soome         // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8417c65ebfc7SToomas Soome         // (with the current code) result in the server having even less than three seconds to respond
8418c65ebfc7SToomas Soome         // before we deleted the record and reported a "remove" event to any active questions.
8419c65ebfc7SToomas Soome         // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8420c65ebfc7SToomas Soome         // then things really break (e.g. we end up making a negative cache entry).
8421c65ebfc7SToomas Soome         // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8422c65ebfc7SToomas Soome         if (ttl < 15) ttl = 15;
8423c65ebfc7SToomas Soome     }
8424c65ebfc7SToomas Soome 
8425c65ebfc7SToomas Soome     return ttl;
8426c65ebfc7SToomas Soome }
8427c65ebfc7SToomas Soome 
8428c65ebfc7SToomas Soome // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8429c65ebfc7SToomas Soome // in m->rec.
IsResponseAcceptable(mDNS * const m,const CacheRecord * crlist)8430*472cd20dSToomas Soome mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist)
8431c65ebfc7SToomas Soome {
8432c65ebfc7SToomas Soome     CacheRecord *const newcr = &m->rec.r;
8433c65ebfc7SToomas Soome     ResourceRecord *rr = &newcr->resrec;
8434c65ebfc7SToomas Soome     const CacheRecord *cr;
8435c65ebfc7SToomas Soome 
8436c65ebfc7SToomas Soome     for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8437c65ebfc7SToomas Soome     {
8438c65ebfc7SToomas Soome         domainname *target = GetRRDomainNameTarget(&cr->resrec);
8439c65ebfc7SToomas Soome         // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8440c65ebfc7SToomas Soome         // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8441c65ebfc7SToomas Soome         // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8442c65ebfc7SToomas Soome         // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8443c65ebfc7SToomas Soome         // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8444c65ebfc7SToomas Soome 
8445c65ebfc7SToomas Soome         if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8446c65ebfc7SToomas Soome         {
84473b436d06SToomas Soome             LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8448c65ebfc7SToomas Soome             return (mDNStrue);
8449c65ebfc7SToomas Soome         }
8450c65ebfc7SToomas Soome     }
8451c65ebfc7SToomas Soome     return mDNSfalse;
8452c65ebfc7SToomas Soome }
8453c65ebfc7SToomas Soome 
mDNSCoreReceiveNoUnicastAnswers(mDNS * const m,const DNSMessage * const response,const mDNSu8 * end,const mDNSAddr * dstaddr,const mDNSIPPort dstport,const mDNSInterfaceID InterfaceID,const mdns_querier_t querier,const mdns_dns_service_t uDNSService,denial_of_existence_records_t ** denial_of_existence_records_ptr,const uDNS_LLQType LLQType)8454*472cd20dSToomas Soome mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8455*472cd20dSToomas Soome     const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID,
8456*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8457*472cd20dSToomas Soome     const mdns_querier_t querier, const mdns_dns_service_t uDNSService,
8458*472cd20dSToomas Soome #endif
8459*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8460*472cd20dSToomas Soome     denial_of_existence_records_t **denial_of_existence_records_ptr,
8461*472cd20dSToomas Soome #endif
8462*472cd20dSToomas Soome     const uDNS_LLQType LLQType)
8463c65ebfc7SToomas Soome {
8464c65ebfc7SToomas Soome     int i;
8465c65ebfc7SToomas Soome     const mDNSu8 *ptr   = response->data;
8466c65ebfc7SToomas Soome     CacheRecord *SOARecord = mDNSNULL;
8467c65ebfc7SToomas Soome 
8468c65ebfc7SToomas Soome     for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8469c65ebfc7SToomas Soome     {
8470c65ebfc7SToomas Soome         DNSQuestion q;
8471c65ebfc7SToomas Soome         ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8472*472cd20dSToomas Soome         if (ptr)
8473c65ebfc7SToomas Soome         {
8474*472cd20dSToomas Soome             DNSQuestion *qptr;
8475*472cd20dSToomas Soome             CacheRecord *cr, *neg = mDNSNULL;
8476*472cd20dSToomas Soome             CacheGroup *cg;
8477*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8478*472cd20dSToomas Soome             if (querier)
8479*472cd20dSToomas Soome             {
8480*472cd20dSToomas Soome                 qptr = Querier_GetDNSQuestion(querier);
8481*472cd20dSToomas Soome             }
8482*472cd20dSToomas Soome             else
8483*472cd20dSToomas Soome #endif
8484*472cd20dSToomas Soome             {
8485*472cd20dSToomas Soome                 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr);
8486*472cd20dSToomas Soome                 if (!qptr)
8487*472cd20dSToomas Soome                 {
8488*472cd20dSToomas Soome                     continue;
8489*472cd20dSToomas Soome                 }
8490*472cd20dSToomas Soome             }
8491*472cd20dSToomas Soome             cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8492*472cd20dSToomas Soome             for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8493*472cd20dSToomas Soome             {
8494*472cd20dSToomas Soome                 mDNSBool isAnswer;
8495*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8496*472cd20dSToomas Soome                 if (querier)
8497*472cd20dSToomas Soome                 {
8498*472cd20dSToomas Soome                     isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier);
8499*472cd20dSToomas Soome                 }
8500*472cd20dSToomas Soome                 else
8501*472cd20dSToomas Soome #endif
8502*472cd20dSToomas Soome                 {
8503*472cd20dSToomas Soome                     isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr);
8504*472cd20dSToomas Soome                 }
8505*472cd20dSToomas Soome                 if (isAnswer)
8506c65ebfc7SToomas Soome                 {
8507c65ebfc7SToomas Soome                     // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8508*472cd20dSToomas Soome                     if (RRExpireTime(cr) - m->timenow > 0) break;
8509c65ebfc7SToomas Soome                     // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8510*472cd20dSToomas Soome                     if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = cr;
8511*472cd20dSToomas Soome                     else if (cr->resrec.mortality == Mortality_Ghost)
8512*472cd20dSToomas Soome                     {
8513*472cd20dSToomas Soome                         // 3. If the existing entry is expired, mark it to be purged
8514*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8515*472cd20dSToomas Soome                             "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Removing expired record" PRI_S,
8516*472cd20dSToomas Soome                             q.request_id, mDNSVal16(q.TargetQID), CRDisplayString(m, cr));
8517*472cd20dSToomas Soome                         mDNS_PurgeCacheResourceRecord(m, cr);
8518*472cd20dSToomas Soome                    }
8519*472cd20dSToomas Soome                 }
8520c65ebfc7SToomas Soome             }
8521c65ebfc7SToomas Soome             // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8522c65ebfc7SToomas Soome             // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8523c65ebfc7SToomas Soome             // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8524c65ebfc7SToomas Soome             // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8525c65ebfc7SToomas Soome             // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8526c65ebfc7SToomas Soome             // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8527c65ebfc7SToomas Soome             // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8528c65ebfc7SToomas Soome             // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8529c65ebfc7SToomas Soome             // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8530c65ebfc7SToomas Soome             // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8531c65ebfc7SToomas Soome             //
8532c65ebfc7SToomas Soome             // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8533c65ebfc7SToomas Soome             // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8534c65ebfc7SToomas Soome             // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8535c65ebfc7SToomas Soome             // case without creating the negative cache entries, we generate a negative response and let the layer above us
8536c65ebfc7SToomas Soome             // do the appropriate thing. This negative response is also needed for appending new search domains.
8537c65ebfc7SToomas Soome             if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8538c65ebfc7SToomas Soome             {
8539*472cd20dSToomas Soome                 if (!cr)
8540c65ebfc7SToomas Soome                 {
8541*472cd20dSToomas Soome                     if (qptr)
8542*472cd20dSToomas Soome                     {
8543*472cd20dSToomas Soome                         const mDNSBool noData = ((response->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr) ? mDNStrue : mDNSfalse;
8544*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8545*472cd20dSToomas Soome                             "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME " (" PUB_S ")",
8546*472cd20dSToomas Soome                             q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
8547c65ebfc7SToomas Soome                         m->CurrentQuestion = qptr;
8548c65ebfc7SToomas Soome                         // We are not creating a cache record in this case, we need to pass back
8549c65ebfc7SToomas Soome                         // the error we got so that the proxy code can return the right one to
8550c65ebfc7SToomas Soome                         // the application
8551c65ebfc7SToomas Soome                         if (qptr->ProxyQuestion)
8552c65ebfc7SToomas Soome                             qptr->responseFlags = response->h.flags;
8553*472cd20dSToomas Soome                         GenerateNegativeResponseEx(m, mDNSInterface_Any, QC_forceresponse, noData);
8554c65ebfc7SToomas Soome                         m->CurrentQuestion = mDNSNULL;
8555c65ebfc7SToomas Soome                     }
8556*472cd20dSToomas Soome                 }
8557c65ebfc7SToomas Soome                 else
8558c65ebfc7SToomas Soome                 {
8559*472cd20dSToomas Soome                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8560*472cd20dSToomas Soome                         "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME " (" PUB_S ")",
8561*472cd20dSToomas Soome                         q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
8562c65ebfc7SToomas Soome                 }
8563c65ebfc7SToomas Soome             }
8564c65ebfc7SToomas Soome             else
8565c65ebfc7SToomas Soome             {
8566*472cd20dSToomas Soome                 if (!cr)
8567c65ebfc7SToomas Soome                 {
8568c65ebfc7SToomas Soome                     // We start off assuming a negative caching TTL of 60 seconds
8569c65ebfc7SToomas Soome                     // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8570c65ebfc7SToomas Soome                     mDNSu32 negttl = 60;
8571c65ebfc7SToomas Soome                     int repeat = 0;
8572c65ebfc7SToomas Soome                     const domainname *name = &q.qname;
8573c65ebfc7SToomas Soome                     mDNSu32 hash = q.qnamehash;
8574c65ebfc7SToomas Soome 
8575c65ebfc7SToomas Soome                     // Special case for our special Microsoft Active Directory "local SOA" check.
8576c65ebfc7SToomas Soome                     // Some cheap home gateways don't include an SOA record in the authority section when
8577c65ebfc7SToomas Soome                     // they send negative responses, so we don't know how long to cache the negative result.
8578c65ebfc7SToomas Soome                     // Because we don't want to keep hitting the root name servers with our query to find
8579c65ebfc7SToomas Soome                     // if we're on a network using Microsoft Active Directory using "local" as a private
8580c65ebfc7SToomas Soome                     // internal top-level domain, we make sure to cache the negative result for at least one day.
8581c65ebfc7SToomas Soome                     if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8582c65ebfc7SToomas Soome 
8583c65ebfc7SToomas Soome                     // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8584c65ebfc7SToomas Soome                     if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8585c65ebfc7SToomas Soome                     {
8586c65ebfc7SToomas Soome                         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8587c65ebfc7SToomas Soome                         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8588c65ebfc7SToomas Soome                         {
8589c65ebfc7SToomas Soome                             CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec);
8590c65ebfc7SToomas Soome                             const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8591c65ebfc7SToomas Soome                             mDNSu32 ttl_s = soa->min;
8592c65ebfc7SToomas Soome                             // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8593c65ebfc7SToomas Soome                             // for the SOA record for ".", where the record is reported as non-cacheable
8594c65ebfc7SToomas Soome                             // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8595c65ebfc7SToomas Soome                             if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8596c65ebfc7SToomas Soome                                 ttl_s = m->rec.r.resrec.rroriginalttl;
8597c65ebfc7SToomas Soome                             if (negttl < ttl_s) negttl = ttl_s;
8598c65ebfc7SToomas Soome 
8599c65ebfc7SToomas Soome                             // Create the SOA record as we may have to return this to the questions
8600c65ebfc7SToomas Soome                             // that we are acting as a proxy for currently or in the future.
8601c65ebfc7SToomas Soome                             SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL);
8602c65ebfc7SToomas Soome 
8603c65ebfc7SToomas Soome                             // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8604c65ebfc7SToomas Soome                             // with an Authority Section SOA record for d.com, then this is a hint that the authority
8605c65ebfc7SToomas Soome                             // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8606c65ebfc7SToomas Soome                             // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8607c65ebfc7SToomas Soome                             //
8608c65ebfc7SToomas Soome                             // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8609c65ebfc7SToomas Soome                             // along with the negative cache record. For simplicity, we don't create the additional records.
8610*472cd20dSToomas Soome                             if ((!qptr || !qptr->ProxyQuestion) && (q.qtype == kDNSType_SOA))
8611c65ebfc7SToomas Soome                             {
8612c65ebfc7SToomas Soome                                 int qcount = CountLabels(&q.qname);
8613c65ebfc7SToomas Soome                                 int scount = CountLabels(m->rec.r.resrec.name);
8614c65ebfc7SToomas Soome                                 if (qcount - 1 > scount)
8615c65ebfc7SToomas Soome                                     if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8616c65ebfc7SToomas Soome                                         repeat = qcount - 1 - scount;
8617c65ebfc7SToomas Soome                             }
8618c65ebfc7SToomas Soome                         }
8619c65ebfc7SToomas Soome                         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8620c65ebfc7SToomas Soome                     }
8621c65ebfc7SToomas Soome 
8622c65ebfc7SToomas Soome                     // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8623c65ebfc7SToomas Soome                     // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8624c65ebfc7SToomas Soome                     // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8625c65ebfc7SToomas Soome                     // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8626c65ebfc7SToomas Soome                     // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8627c65ebfc7SToomas Soome                     // so that we back off our polling rate and don't keep hitting the server continually.
8628c65ebfc7SToomas Soome                     if (neg)
8629c65ebfc7SToomas Soome                     {
8630c65ebfc7SToomas Soome                         if (negttl < neg->resrec.rroriginalttl * 2)
8631c65ebfc7SToomas Soome                             negttl = neg->resrec.rroriginalttl * 2;
8632c65ebfc7SToomas Soome                         if (negttl > 3600)
8633c65ebfc7SToomas Soome                             negttl = 3600;
8634c65ebfc7SToomas Soome                     }
8635c65ebfc7SToomas Soome 
8636c65ebfc7SToomas Soome                     negttl = GetEffectiveTTL(LLQType, negttl);  // Add 25% grace period if necessary
8637c65ebfc7SToomas Soome 
8638c65ebfc7SToomas Soome                     // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8639c65ebfc7SToomas Soome                     if (neg)
8640c65ebfc7SToomas Soome                     {
8641*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8642*472cd20dSToomas Soome                             "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S,
8643*472cd20dSToomas Soome                             q.request_id, mDNSVal16(q.TargetQID), neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8644c65ebfc7SToomas Soome                         RefreshCacheRecord(m, neg, negttl);
8645*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8646*472cd20dSToomas Soome                         // replace the old records with the new ones
8647*472cd20dSToomas Soome                         // If qptr is NULL, it means the question is no longer active, and we do not process the record
8648*472cd20dSToomas Soome                         // for DNSSEC.
8649*472cd20dSToomas Soome                         if ((qptr != mDNSNULL) && qptr->DNSSECStatus.enable_dnssec)
8650*472cd20dSToomas Soome                         {
8651*472cd20dSToomas Soome                             update_denial_records_in_cache_record(neg, denial_of_existence_records_ptr);
8652*472cd20dSToomas Soome                         }
8653*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8654c65ebfc7SToomas Soome                         // When we created the cache for the first time and answered the question, the question's
8655c65ebfc7SToomas Soome                         // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8656c65ebfc7SToomas Soome                         // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8657c65ebfc7SToomas Soome                         // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8658c65ebfc7SToomas Soome                         // we should reset its question interval here to MaxQuestionInterval.
8659*472cd20dSToomas Soome                         if (qptr)
8660*472cd20dSToomas Soome                         {
8661c65ebfc7SToomas Soome                             ResetQuestionState(m, qptr);
8662c65ebfc7SToomas Soome                         }
8663c65ebfc7SToomas Soome                         if (SOARecord)
8664c65ebfc7SToomas Soome                         {
8665c65ebfc7SToomas Soome                             if (neg->soa)
8666c65ebfc7SToomas Soome                                 ReleaseCacheRecord(m, neg->soa);
8667c65ebfc7SToomas Soome                             neg->soa = SOARecord;
8668c65ebfc7SToomas Soome                             SOARecord = mDNSNULL;
8669c65ebfc7SToomas Soome                         }
8670c65ebfc7SToomas Soome                     }
8671c65ebfc7SToomas Soome                     else while (1)
8672c65ebfc7SToomas Soome                         {
8673c65ebfc7SToomas Soome                             CacheRecord *negcr;
8674c65ebfc7SToomas Soome                             debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8675*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8676*472cd20dSToomas Soome                             MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, uDNSService);
8677*472cd20dSToomas Soome #else
8678c65ebfc7SToomas Soome                             MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8679*472cd20dSToomas Soome #endif
8680c65ebfc7SToomas Soome                             m->rec.r.responseFlags = response->h.flags;
8681c65ebfc7SToomas Soome                             // We create SOA records above which might create new cache groups. Earlier
8682c65ebfc7SToomas Soome                             // in the function we looked up the cache group for the name and it could have
8683c65ebfc7SToomas Soome                             // been NULL. If we pass NULL cg to new cache entries that we create below,
8684c65ebfc7SToomas Soome                             // it will create additional cache groups for the same name. To avoid that,
8685c65ebfc7SToomas Soome                             // look up the cache group again to re-initialize cg again.
8686c65ebfc7SToomas Soome                             cg = CacheGroupForName(m, hash, name);
8687c65ebfc7SToomas Soome                             // Need to add with a delay so that we can tag the SOA record
8688c65ebfc7SToomas Soome                             negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8689*472cd20dSToomas Soome 
8690c65ebfc7SToomas Soome                             if (negcr)
8691c65ebfc7SToomas Soome                             {
8692*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8693*472cd20dSToomas Soome                                 // If qptr is NULL, it means the question is no longer active, and we do not process the
8694*472cd20dSToomas Soome                                 // record for DNSSEC.
8695*472cd20dSToomas Soome                                 if (qptr != mDNSNULL && qptr->DNSSECStatus.enable_dnssec)
8696*472cd20dSToomas Soome                                 {
8697*472cd20dSToomas Soome                                     update_denial_records_in_cache_record(negcr, denial_of_existence_records_ptr);
8698*472cd20dSToomas Soome                                 }
8699*472cd20dSToomas Soome #endif
8700c65ebfc7SToomas Soome                                 negcr->DelayDelivery = 0;
8701c65ebfc7SToomas Soome 
8702c65ebfc7SToomas Soome                                 if (SOARecord)
8703c65ebfc7SToomas Soome                                 {
8704c65ebfc7SToomas Soome                                     if (negcr->soa)
8705c65ebfc7SToomas Soome                                         ReleaseCacheRecord(m, negcr->soa);
8706c65ebfc7SToomas Soome                                     negcr->soa = SOARecord;
8707c65ebfc7SToomas Soome                                     SOARecord = mDNSNULL;
8708c65ebfc7SToomas Soome                                 }
8709c65ebfc7SToomas Soome                                 CacheRecordDeferredAdd(m, negcr);
8710c65ebfc7SToomas Soome                             }
8711c65ebfc7SToomas Soome                             m->rec.r.responseFlags = zeroID;
8712c65ebfc7SToomas Soome                             m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8713c65ebfc7SToomas Soome                             if (!repeat) break;
8714c65ebfc7SToomas Soome                             repeat--;
8715c65ebfc7SToomas Soome                             name = (const domainname *)(name->c + 1 + name->c[0]);
8716c65ebfc7SToomas Soome                             hash = DomainNameHashValue(name);
8717c65ebfc7SToomas Soome                         }
8718c65ebfc7SToomas Soome                 }
8719c65ebfc7SToomas Soome             }
8720c65ebfc7SToomas Soome         }
8721c65ebfc7SToomas Soome     }
8722*472cd20dSToomas Soome     if (SOARecord)
8723*472cd20dSToomas Soome     {
8724*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8725*472cd20dSToomas Soome         ReleaseCacheRecord(m, SOARecord);
8726*472cd20dSToomas Soome     }
8727c65ebfc7SToomas Soome }
8728c65ebfc7SToomas Soome 
mDNSCorePrintStoredProxyRecords(mDNS * const m)8729c65ebfc7SToomas Soome mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8730c65ebfc7SToomas Soome {
8731c65ebfc7SToomas Soome     AuthRecord *rrPtr = mDNSNULL;
8732*472cd20dSToomas Soome     if (!m->SPSRRSet) return;
8733c65ebfc7SToomas Soome     LogSPS("Stored Proxy records :");
8734c65ebfc7SToomas Soome     for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8735c65ebfc7SToomas Soome     {
8736c65ebfc7SToomas Soome         LogSPS("%s", ARDisplayString(m, rrPtr));
8737c65ebfc7SToomas Soome     }
8738c65ebfc7SToomas Soome }
8739c65ebfc7SToomas Soome 
mDNSCoreRegisteredProxyRecord(mDNS * const m,AuthRecord * rr)8740c65ebfc7SToomas Soome mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8741c65ebfc7SToomas Soome {
8742c65ebfc7SToomas Soome     AuthRecord *rrPtr = mDNSNULL;
8743c65ebfc7SToomas Soome 
8744c65ebfc7SToomas Soome     for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8745c65ebfc7SToomas Soome     {
8746c65ebfc7SToomas Soome         if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8747c65ebfc7SToomas Soome         {
8748c65ebfc7SToomas Soome             LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8749c65ebfc7SToomas Soome             return mDNStrue;
8750c65ebfc7SToomas Soome         }
8751c65ebfc7SToomas Soome     }
8752c65ebfc7SToomas Soome     mDNSCorePrintStoredProxyRecords(m);
8753c65ebfc7SToomas Soome     return mDNSfalse;
8754c65ebfc7SToomas Soome }
8755c65ebfc7SToomas Soome 
mDNSCoreReceiveCacheCheck(mDNS * const m,const DNSMessage * const response,uDNS_LLQType LLQType,const mDNSu32 slot,CacheGroup * cg,CacheRecord *** cfp,mDNSInterfaceID InterfaceID)8756*472cd20dSToomas Soome mDNSexport CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8757*472cd20dSToomas Soome     const mDNSu32 slot, CacheGroup *cg, CacheRecord ***cfp, mDNSInterfaceID InterfaceID)
8758c65ebfc7SToomas Soome {
8759*472cd20dSToomas Soome     CacheRecord *cr;
8760c65ebfc7SToomas Soome     CacheRecord **cflocal = *cfp;
8761c65ebfc7SToomas Soome 
8762*472cd20dSToomas Soome     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8763c65ebfc7SToomas Soome     {
8764c65ebfc7SToomas Soome         mDNSBool match;
8765c65ebfc7SToomas Soome         // Resource record received via unicast, the resGroupID should match ?
8766c65ebfc7SToomas Soome         if (!InterfaceID)
8767c65ebfc7SToomas Soome         {
8768*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8769*472cd20dSToomas Soome             match = (cr->resrec.dnsservice == m->rec.r.resrec.dnsservice) ? mDNStrue : mDNSfalse;
8770*472cd20dSToomas Soome #else
8771*472cd20dSToomas Soome             const mDNSu32 id1 = (cr->resrec.rDNSServer ? cr->resrec.rDNSServer->resGroupID : 0);
8772*472cd20dSToomas Soome             const mDNSu32 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8773c65ebfc7SToomas Soome             match = (id1 == id2);
8774*472cd20dSToomas Soome #endif
8775c65ebfc7SToomas Soome         }
8776c65ebfc7SToomas Soome         else
8777*472cd20dSToomas Soome             match = (cr->resrec.InterfaceID == InterfaceID);
8778c65ebfc7SToomas Soome         // If we found this exact resource record, refresh its TTL
8779*472cd20dSToomas Soome         if (match)
8780*472cd20dSToomas Soome         {
8781*472cd20dSToomas Soome             if (IdenticalSameNameRecord(&m->rec.r.resrec, &cr->resrec))
8782c65ebfc7SToomas Soome             {
8783c65ebfc7SToomas Soome                 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8784c65ebfc7SToomas Soome                     verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8785c65ebfc7SToomas Soome                                   m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8786c65ebfc7SToomas Soome 
8787c65ebfc7SToomas Soome                 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8788c65ebfc7SToomas Soome                 {
8789c65ebfc7SToomas Soome                     // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8790*472cd20dSToomas Soome                     if (cr->NextInCFList == mDNSNULL && *cfp != &cr->NextInCFList && LLQType != uDNS_LLQ_Events)
8791c65ebfc7SToomas Soome                     {
8792*472cd20dSToomas Soome                         *cflocal = cr;
8793*472cd20dSToomas Soome                         cflocal = &cr->NextInCFList;
8794c65ebfc7SToomas Soome                         *cflocal = (CacheRecord*)1;
8795*472cd20dSToomas Soome                         *cfp = &cr->NextInCFList;
8796c65ebfc7SToomas Soome                     }
8797c65ebfc7SToomas Soome 
8798c65ebfc7SToomas Soome                     // If this packet record is marked unique, and our previous cached copy was not, then fix it
8799*472cd20dSToomas Soome                     if (!(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8800c65ebfc7SToomas Soome                     {
8801c65ebfc7SToomas Soome                         DNSQuestion *q;
8802c65ebfc7SToomas Soome                         for (q = m->Questions; q; q=q->next)
8803c65ebfc7SToomas Soome                         {
8804*472cd20dSToomas Soome                             if (CacheRecordAnswersQuestion(cr, q))
8805c65ebfc7SToomas Soome                                 q->UniqueAnswers++;
8806c65ebfc7SToomas Soome                         }
8807*472cd20dSToomas Soome                         cr->resrec.RecordType = m->rec.r.resrec.RecordType;
8808c65ebfc7SToomas Soome                     }
8809c65ebfc7SToomas Soome                 }
8810c65ebfc7SToomas Soome 
8811*472cd20dSToomas Soome                 if (!SameRDataBody(&m->rec.r.resrec, &cr->resrec.rdata->u, SameDomainNameCS))
8812c65ebfc7SToomas Soome                 {
8813c65ebfc7SToomas Soome                     // If the rdata of the packet record differs in name capitalization from the record in our cache
8814c65ebfc7SToomas Soome                     // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8815c65ebfc7SToomas Soome                     // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8816c65ebfc7SToomas Soome                     // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8817*472cd20dSToomas Soome                     cr->resrec.rroriginalttl = 0;
8818*472cd20dSToomas Soome                     cr->TimeRcvd = m->timenow;
8819*472cd20dSToomas Soome                     cr->UnansweredQueries = MaxUnansweredQueries;
8820*472cd20dSToomas Soome                     SetNextCacheCheckTimeForRecord(m, cr);
8821*472cd20dSToomas Soome                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S, CRDisplayString(m, cr));
8822*472cd20dSToomas Soome                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S, CRDisplayString(m, &m->rec.r));
8823*472cd20dSToomas Soome                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8824*472cd20dSToomas Soome                               NextCacheCheckEvent(cr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8825c65ebfc7SToomas Soome                     // DO NOT break out here -- we want to continue as if we never found it
8826c65ebfc7SToomas Soome                 }
8827c65ebfc7SToomas Soome                 else if (m->rec.r.resrec.rroriginalttl > 0)
8828c65ebfc7SToomas Soome                 {
8829c65ebfc7SToomas Soome                     DNSQuestion *q;
8830c65ebfc7SToomas Soome 
8831c65ebfc7SToomas Soome                     m->mDNSStats.CacheRefreshed++;
8832c65ebfc7SToomas Soome 
8833*472cd20dSToomas Soome                     if ((cr->resrec.mortality == Mortality_Ghost) && !cr->DelayDelivery)
88343b436d06SToomas Soome                     {
8835*472cd20dSToomas Soome                         cr->DelayDelivery = NonZeroTime(m->timenow);
8836*472cd20dSToomas Soome                         debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(cr), CRDisplayString(m, cr));
88373b436d06SToomas Soome                     }
88383b436d06SToomas Soome 
8839*472cd20dSToomas Soome                     if (cr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, cr));
8840*472cd20dSToomas Soome                     RefreshCacheRecord(m, cr, m->rec.r.resrec.rroriginalttl);
8841*472cd20dSToomas Soome                     // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop.
8842*472cd20dSToomas Soome                     // It is safe to call because the else-if body will unconditionally break out of the for-loop now that it has found the entry to update.
8843*472cd20dSToomas Soome                     RefreshCacheRecordCacheGroupOrder(cg, cr);
8844*472cd20dSToomas Soome                     cr->responseFlags = response->h.flags;
8845c65ebfc7SToomas Soome 
8846c65ebfc7SToomas Soome                     // If we may have NSEC records returned with the answer (which we don't know yet as it
8847c65ebfc7SToomas Soome                     // has not been processed), we need to cache them along with the first cache
8848c65ebfc7SToomas Soome                     // record in the list that answers the question so that it can be used for validation
8849c65ebfc7SToomas Soome                     // later. The "type" check below is to make sure that we cache on the cache record
8850c65ebfc7SToomas Soome                     // that would answer the question. It is possible that we might cache additional things
8851c65ebfc7SToomas Soome                     // e.g., MX question might cache A records also, and we want to cache the NSEC on
8852c65ebfc7SToomas Soome                     // the record that answers the question.
8853*472cd20dSToomas Soome                     if (!InterfaceID)
8854c65ebfc7SToomas Soome                     {
8855*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S, CRDisplayString(m, cr));
8856c65ebfc7SToomas Soome                     }
8857c65ebfc7SToomas Soome                     // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8858c65ebfc7SToomas Soome                     // polling the network once we get a valid response back. For the first time when a new
8859c65ebfc7SToomas Soome                     // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8860c65ebfc7SToomas Soome                     // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8861c65ebfc7SToomas Soome                     // configuration changed, without flushing the cache, we reset the question interval here.
8862c65ebfc7SToomas Soome                     // Currently, we do this for for both multicast and unicast questions as long as the record
8863c65ebfc7SToomas Soome                     // type is unique. For unicast, resource record is always unique and for multicast it is
8864c65ebfc7SToomas Soome                     // true for records like A etc. but not for PTR.
8865*472cd20dSToomas Soome                     if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8866c65ebfc7SToomas Soome                     {
8867c65ebfc7SToomas Soome                         for (q = m->Questions; q; q=q->next)
8868c65ebfc7SToomas Soome                         {
8869c65ebfc7SToomas Soome                             if (!q->DuplicateOf && !q->LongLived &&
8870*472cd20dSToomas Soome                                 ActiveQuestion(q) && CacheRecordAnswersQuestion(cr, q))
8871c65ebfc7SToomas Soome                             {
8872c65ebfc7SToomas Soome                                 ResetQuestionState(m, q);
8873c65ebfc7SToomas Soome                                 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8874c65ebfc7SToomas Soome                                 break;      // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8875c65ebfc7SToomas Soome                             }
8876c65ebfc7SToomas Soome                         }
8877c65ebfc7SToomas Soome                     }
8878*472cd20dSToomas Soome                     break;  // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above)
8879c65ebfc7SToomas Soome                 }
8880c65ebfc7SToomas Soome                 else
8881c65ebfc7SToomas Soome                 {
8882c65ebfc7SToomas Soome                     // If the packet TTL is zero, that means we're deleting this record.
8883c65ebfc7SToomas Soome                     // To give other hosts on the network a chance to protest, we push the deletion
8884c65ebfc7SToomas Soome                     // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8885c65ebfc7SToomas Soome                     // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8886c65ebfc7SToomas Soome                     // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8887c65ebfc7SToomas Soome                     // If record's current expiry time is more than a second from now, we set it to expire in one second.
8888c65ebfc7SToomas Soome                     // If the record is already going to expire in less than one second anyway, we leave it alone --
8889c65ebfc7SToomas Soome                     // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8890*472cd20dSToomas Soome                     debugf("DE for %s", CRDisplayString(m, cr));
8891*472cd20dSToomas Soome                     if (RRExpireTime(cr) - m->timenow > mDNSPlatformOneSecond)
8892c65ebfc7SToomas Soome                     {
8893*472cd20dSToomas Soome                         cr->resrec.rroriginalttl = 1;
8894*472cd20dSToomas Soome                         cr->TimeRcvd = m->timenow;
8895*472cd20dSToomas Soome                         cr->UnansweredQueries = MaxUnansweredQueries;
8896*472cd20dSToomas Soome                         SetNextCacheCheckTimeForRecord(m, cr);
8897c65ebfc7SToomas Soome                     }
8898c65ebfc7SToomas Soome                     break;
8899c65ebfc7SToomas Soome                 }
8900c65ebfc7SToomas Soome             }
8901*472cd20dSToomas Soome             else if (cr->resrec.rroriginalttl != 0                  &&      // Not already marked for discarding
8902*472cd20dSToomas Soome                      m->rec.r.resrec.rrclass == cr->resrec.rrclass  &&
8903*472cd20dSToomas Soome                         (m->rec.r.resrec.rrtype != cr->resrec.rrtype    &&
8904*472cd20dSToomas Soome                          (m->rec.r.resrec.rrtype == kDNSType_CNAME || cr->resrec.rrtype == kDNSType_CNAME)))
8905c65ebfc7SToomas Soome             {
8906*472cd20dSToomas Soome                 // If the cache record rrtype doesn't match and one is a CNAME, then flush this record
8907*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding (%s) " PRI_S " rrtype change from (%s) to (%s)",
8908*472cd20dSToomas Soome                           MortalityDisplayString(cr->resrec.mortality), CRDisplayString(m, cr), DNSTypeName(cr->resrec.rrtype), DNSTypeName(m->rec.r.resrec.rrtype));
8909*472cd20dSToomas Soome                 mDNS_PurgeCacheResourceRecord(m, cr);
8910*472cd20dSToomas Soome                 // DO NOT break out here -- we want to continue iterating the cache entries
8911c65ebfc7SToomas Soome             }
8912c65ebfc7SToomas Soome         }
8913c65ebfc7SToomas Soome     }
8914*472cd20dSToomas Soome     return cr;
8915c65ebfc7SToomas Soome }
8916c65ebfc7SToomas Soome 
mDNSCoreResetRecord(mDNS * const m)8917c65ebfc7SToomas Soome mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8918c65ebfc7SToomas Soome {
8919c65ebfc7SToomas Soome     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8920c65ebfc7SToomas Soome }
8921c65ebfc7SToomas Soome 
8922c65ebfc7SToomas Soome // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8923c65ebfc7SToomas Soome // the record list and/or question list.
8924c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8925c65ebfc7SToomas Soome // InterfaceID non-NULL tells us the interface this multicast response was received on
8926c65ebfc7SToomas Soome // InterfaceID NULL tells us this was a unicast response
8927c65ebfc7SToomas Soome // dstaddr NULL tells us we received this over an outgoing TCP connection we made
mDNSCoreReceiveResponse(mDNS * const m,const DNSMessage * const response,const mDNSu8 * end,const mDNSAddr * srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,mDNSIPPort dstport,mdns_querier_t querier,mdns_dns_service_t uDNSService,const mDNSInterfaceID InterfaceID)8928*472cd20dSToomas Soome mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8929c65ebfc7SToomas Soome     const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8930*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8931*472cd20dSToomas Soome     mdns_querier_t querier, mdns_dns_service_t uDNSService,
8932*472cd20dSToomas Soome #endif
8933c65ebfc7SToomas Soome     const mDNSInterfaceID InterfaceID)
8934c65ebfc7SToomas Soome {
8935c65ebfc7SToomas Soome     int i;
8936*472cd20dSToomas Soome     const mDNSBool ResponseMCast    = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8937*472cd20dSToomas Soome     const mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8938c65ebfc7SToomas Soome     DNSQuestion *llqMatch = mDNSNULL;
8939c65ebfc7SToomas Soome     uDNS_LLQType LLQType      = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8940c65ebfc7SToomas Soome 
8941c65ebfc7SToomas Soome     // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8942c65ebfc7SToomas Soome     // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8943c65ebfc7SToomas Soome     // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8944c65ebfc7SToomas Soome     CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8945c65ebfc7SToomas Soome     CacheRecord **cfp = &CacheFlushRecords;
8946c65ebfc7SToomas Soome     NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8947c65ebfc7SToomas Soome     mDNSBool    recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8948c65ebfc7SToomas Soome 
8949c65ebfc7SToomas Soome     // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8950c65ebfc7SToomas Soome     // to guard against spoof responses, then the only credible protection against that is cryptographic
8951c65ebfc7SToomas Soome     // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8952c65ebfc7SToomas Soome     int firstauthority  =                   response->h.numAnswers;
8953c65ebfc7SToomas Soome     int firstadditional = firstauthority  + response->h.numAuthorities;
8954c65ebfc7SToomas Soome     int totalrecords    = firstadditional + response->h.numAdditionals;
8955c65ebfc7SToomas Soome     const mDNSu8 *ptr   = response->data;
8956*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8957c65ebfc7SToomas Soome     DNSServer *uDNSServer = mDNSNULL;
8958*472cd20dSToomas Soome #endif
8959*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8960*472cd20dSToomas Soome     denial_of_existence_records_t *denial_of_existence_records = mDNSNULL;
8961*472cd20dSToomas Soome     mDNSBool not_answer_but_required_for_dnssec = mDNSfalse;
8962*472cd20dSToomas Soome #endif
8963*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8964*472cd20dSToomas Soome     // Determine whether the response is mDNS, as opposed to DNS.
8965*472cd20dSToomas Soome     // Thus far, the code has assumed that responses with IDs set to zero are mDNS responses. However, this condition
8966*472cd20dSToomas Soome     // isn't sufficient because queriers, which are used exclusively for DNS queries, may set the IDs of their queries
8967*472cd20dSToomas Soome     // to zero. And consequently, their responses may have their IDs set to zero. Specifically, zero-valued IDs are used
8968*472cd20dSToomas Soome     // for DNS over HTTPs, as specified by <https://tools.ietf.org/html/rfc8484#section-4.1>.
8969*472cd20dSToomas Soome     const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id) && !querier;
8970*472cd20dSToomas Soome #else
8971*472cd20dSToomas Soome     const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id);
8972*472cd20dSToomas Soome #endif
8973c65ebfc7SToomas Soome 
8974c65ebfc7SToomas Soome     debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8975c65ebfc7SToomas Soome            "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8976c65ebfc7SToomas Soome            srcaddr, dstaddr, InterfaceID,
8977c65ebfc7SToomas Soome            response->h.numQuestions,   response->h.numQuestions   == 1 ? ", "   : "s,",
8978c65ebfc7SToomas Soome            response->h.numAnswers,     response->h.numAnswers     == 1 ? ", "   : "s,",
8979c65ebfc7SToomas Soome            response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
8980c65ebfc7SToomas Soome            response->h.numAdditionals, response->h.numAdditionals == 1 ? " "    : "s", end - response->data, LLQType);
8981c65ebfc7SToomas Soome 
8982*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
89833b436d06SToomas Soome     if (mDNSSameIPPort(srcport, UnicastDNSPort))
89843b436d06SToomas Soome     {
89853b436d06SToomas Soome         MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response));
89863b436d06SToomas Soome     }
89873b436d06SToomas Soome #endif
89883b436d06SToomas Soome 
8989c65ebfc7SToomas Soome     // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8990c65ebfc7SToomas Soome     //    When a DNS client receives a reply with TC
8991c65ebfc7SToomas Soome     //    set, it should ignore that response, and query again, using a
8992c65ebfc7SToomas Soome     //    mechanism, such as a TCP connection, that will permit larger replies.
8993c65ebfc7SToomas Soome     // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8994c65ebfc7SToomas Soome     // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8995c65ebfc7SToomas Soome     // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8996c65ebfc7SToomas Soome     // <rdar://problem/6690034> Can't bind to Active Directory
8997c65ebfc7SToomas Soome     // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8998c65ebfc7SToomas Soome     // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8999c65ebfc7SToomas Soome     // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
9000c65ebfc7SToomas Soome     // and not even do the TCP query.
90013b436d06SToomas Soome     // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
90023b436d06SToomas Soome     // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
90033b436d06SToomas Soome     // either the authority section or additional section, then that implies that truncation occurred beyond the answer
90043b436d06SToomas Soome     // section, and the answer section is therefore assumed to be complete.
90053b436d06SToomas Soome     //
90063b436d06SToomas Soome     // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
90073b436d06SToomas Soome     //    When a response is so long that truncation is required, the truncation
90083b436d06SToomas Soome     //    should start at the end of the response and work forward in the
90093b436d06SToomas Soome     //    datagram.  Thus if there is any data for the authority section, the
90103b436d06SToomas Soome     //    answer section is guaranteed to be unique.
9011*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9012*472cd20dSToomas Soome     if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && !querier &&
9013*472cd20dSToomas Soome #else
90143b436d06SToomas Soome     if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) &&
9015*472cd20dSToomas Soome #endif
90163b436d06SToomas Soome         ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return;
9017c65ebfc7SToomas Soome 
9018c65ebfc7SToomas Soome     if (LLQType == uDNS_LLQ_Ignore) return;
9019c65ebfc7SToomas Soome 
9020c65ebfc7SToomas Soome     // 1. We ignore questions (if any) in mDNS response packets
9021c65ebfc7SToomas Soome     // 2. If this is an LLQ response, we handle it much the same
9022c65ebfc7SToomas Soome     // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
90233b436d06SToomas Soome     if (ResponseMCast || LLQType == uDNS_LLQ_Events)
9024c65ebfc7SToomas Soome         ptr = LocateAnswers(response, end);
9025c65ebfc7SToomas Soome     // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9026c65ebfc7SToomas Soome     // in this response packet are immediately deemed to be invalid.
9027c65ebfc7SToomas Soome     else
9028c65ebfc7SToomas Soome     {
9029c65ebfc7SToomas Soome         mDNSBool failure, returnEarly;
9030*472cd20dSToomas Soome         const int rcode = response->h.flags.b[1] & kDNSFlag1_RC_Mask;
9031c65ebfc7SToomas Soome         failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
9032c65ebfc7SToomas Soome         returnEarly = mDNSfalse;
9033*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9034*472cd20dSToomas Soome         // When the QUERIER functionality is enabled, DNS transport is handled exclusively by querier objects. If this
9035*472cd20dSToomas Soome         // response was provided by a querier, but the RCODE is considered a failure, then set failure to false so that
9036*472cd20dSToomas Soome         // we don't return early. The logic of returning early was so that uDNS_CheckCurrentQuestion() could handle
9037*472cd20dSToomas Soome         // resending the query and generate a negative cache record if all servers were tried. If the querier provides a
9038*472cd20dSToomas Soome         // response, then it's the best response that it could provide. If the RCODE is considered a failure,
9039*472cd20dSToomas Soome         // mDNSCoreReceiveResponse() needs to create negative cache entries for the unanwered question, so totalrecords
9040*472cd20dSToomas Soome         // is set to 0 to ignore any records that the response may contain.
9041*472cd20dSToomas Soome         if (querier && failure)
9042*472cd20dSToomas Soome         {
9043*472cd20dSToomas Soome             totalrecords = 0;
9044*472cd20dSToomas Soome             failure = mDNSfalse;
9045*472cd20dSToomas Soome         }
9046*472cd20dSToomas Soome #endif
9047c65ebfc7SToomas Soome         // We could possibly combine this with the similar loop at the end of this function --
9048c65ebfc7SToomas Soome         // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9049c65ebfc7SToomas Soome         // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9050c65ebfc7SToomas Soome         // which it was received (or refreshed), and then at the end if we find any cache records which
9051c65ebfc7SToomas Soome         // answer questions in this packet's question section, but which aren't tagged with this packet's
9052c65ebfc7SToomas Soome         // packet number, then we deduce they are old and delete them
9053c65ebfc7SToomas Soome         for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
9054c65ebfc7SToomas Soome         {
9055*472cd20dSToomas Soome             DNSQuestion q;
9056*472cd20dSToomas Soome             DNSQuestion *qptr;
9057*472cd20dSToomas Soome             mDNSBool expectingResponse;
9058c65ebfc7SToomas Soome             ptr = getQuestion(response, ptr, end, InterfaceID, &q);
9059*472cd20dSToomas Soome             if (!ptr)
9060c65ebfc7SToomas Soome             {
9061*472cd20dSToomas Soome                 continue;
9062*472cd20dSToomas Soome             }
9063*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9064*472cd20dSToomas Soome             if (querier)
9065*472cd20dSToomas Soome             {
9066*472cd20dSToomas Soome                 expectingResponse = mDNStrue;
9067*472cd20dSToomas Soome                 qptr = mDNSNULL;
9068*472cd20dSToomas Soome             }
9069*472cd20dSToomas Soome             else
9070*472cd20dSToomas Soome #endif
9071*472cd20dSToomas Soome             {
9072*472cd20dSToomas Soome                 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr);
9073*472cd20dSToomas Soome                 expectingResponse = qptr ? mDNStrue : mDNSfalse;
9074*472cd20dSToomas Soome             }
9075*472cd20dSToomas Soome             if (!expectingResponse)
9076*472cd20dSToomas Soome             {
9077*472cd20dSToomas Soome                 continue;
9078*472cd20dSToomas Soome             }
9079c65ebfc7SToomas Soome             if (!failure)
9080c65ebfc7SToomas Soome             {
9081*472cd20dSToomas Soome                 CacheRecord *cr;
9082c65ebfc7SToomas Soome                 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
9083*472cd20dSToomas Soome                 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
9084c65ebfc7SToomas Soome                 {
9085*472cd20dSToomas Soome                     mDNSBool isAnswer;
9086*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9087*472cd20dSToomas Soome                     if (querier)
9088c65ebfc7SToomas Soome                     {
9089*472cd20dSToomas Soome                         isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier);
9090c65ebfc7SToomas Soome                     }
9091*472cd20dSToomas Soome                     else
9092*472cd20dSToomas Soome #endif
9093*472cd20dSToomas Soome                     {
9094*472cd20dSToomas Soome                         isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr);
9095c65ebfc7SToomas Soome                     }
9096*472cd20dSToomas Soome                     if (isAnswer)
9097c65ebfc7SToomas Soome                     {
9098c65ebfc7SToomas Soome                         debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
9099*472cd20dSToomas Soome                                cr->resrec.InterfaceID, CRDisplayString(m, cr));
9100c65ebfc7SToomas Soome                         // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9101*472cd20dSToomas Soome                         cr->TimeRcvd          = m->timenow - TicksTTL(cr) - 1;
9102*472cd20dSToomas Soome                         cr->UnansweredQueries = MaxUnansweredQueries;
9103c65ebfc7SToomas Soome                     }
9104c65ebfc7SToomas Soome                 }
9105c65ebfc7SToomas Soome             }
9106c65ebfc7SToomas Soome             else
9107c65ebfc7SToomas Soome             {
9108*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9109*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9110*472cd20dSToomas Soome                     "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME " (" PUB_S ")",
9111*472cd20dSToomas Soome                     qptr->request_id, mDNSVal16(qptr->TargetQID), qptr->qDNSServer, rcode,
9112*472cd20dSToomas Soome                     DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
9113c65ebfc7SToomas Soome                 PenalizeDNSServer(m, qptr, response->h.flags);
9114*472cd20dSToomas Soome #endif
9115c65ebfc7SToomas Soome                 returnEarly = mDNStrue;
9116c65ebfc7SToomas Soome             }
9117c65ebfc7SToomas Soome         }
9118c65ebfc7SToomas Soome         if (returnEarly)
9119c65ebfc7SToomas Soome         {
9120*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9121*472cd20dSToomas Soome                    "[Q%d] Ignoring %2d Answer" PUB_S " %2d Authorit" PUB_S " %2d Additional" PUB_S,
9122*472cd20dSToomas Soome                    mDNSVal16(response->h.id),
9123c65ebfc7SToomas Soome                    response->h.numAnswers,     response->h.numAnswers     == 1 ? ", " : "s,",
9124c65ebfc7SToomas Soome                    response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
9125c65ebfc7SToomas Soome                    response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
9126c65ebfc7SToomas Soome             // not goto exit because we won't have any CacheFlushRecords and we do not want to
9127c65ebfc7SToomas Soome             // generate negative cache entries (we want to query the next server)
9128c65ebfc7SToomas Soome             return;
9129c65ebfc7SToomas Soome         }
9130c65ebfc7SToomas Soome     }
9131c65ebfc7SToomas Soome 
9132c65ebfc7SToomas Soome     for (i = 0; i < totalrecords && ptr && ptr < end; i++)
9133c65ebfc7SToomas Soome     {
9134c65ebfc7SToomas Soome         // All responses sent via LL multicast are acceptable for caching
9135c65ebfc7SToomas Soome         // All responses received over our outbound TCP connections are acceptable for caching
9136c65ebfc7SToomas Soome         // We accept all records in a unicast response to a multicast query once we find one that
9137c65ebfc7SToomas Soome         // answers an active question.
9138*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9139*472cd20dSToomas Soome         mDNSBool AcceptableResponse = ResponseMCast || (!querier && !dstaddr) || LLQType || recordAcceptedInResponse;
9140*472cd20dSToomas Soome #else
9141c65ebfc7SToomas Soome         mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse;
9142*472cd20dSToomas Soome #endif
9143c65ebfc7SToomas Soome         // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9144c65ebfc7SToomas Soome         // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9145c65ebfc7SToomas Soome 
9146c65ebfc7SToomas Soome         const mDNSu8 RecordType =
9147c65ebfc7SToomas Soome             (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns  :
9148c65ebfc7SToomas Soome             (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
9149c65ebfc7SToomas Soome         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
9150c65ebfc7SToomas Soome         if (!ptr) goto exit;        // Break out of the loop and clean up our CacheFlushRecords list before exiting
9151c65ebfc7SToomas Soome 
9152c65ebfc7SToomas Soome         if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
9153c65ebfc7SToomas Soome         {
9154c65ebfc7SToomas Soome             mDNSCoreResetRecord(m);
9155c65ebfc7SToomas Soome             continue;
9156c65ebfc7SToomas Soome         }
9157c65ebfc7SToomas Soome 
9158c65ebfc7SToomas Soome         // Don't want to cache OPT or TSIG pseudo-RRs
9159c65ebfc7SToomas Soome         if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
9160c65ebfc7SToomas Soome         {
9161c65ebfc7SToomas Soome             mDNSCoreResetRecord(m);
9162c65ebfc7SToomas Soome             continue;
9163c65ebfc7SToomas Soome         }
9164c65ebfc7SToomas Soome         if (m->rec.r.resrec.rrtype == kDNSType_OPT)
9165c65ebfc7SToomas Soome         {
9166c65ebfc7SToomas Soome             const rdataOPT *opt;
9167c65ebfc7SToomas Soome             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9168c65ebfc7SToomas Soome             // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9169c65ebfc7SToomas Soome             // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9170c65ebfc7SToomas Soome             for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
9171c65ebfc7SToomas Soome                 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
9172c65ebfc7SToomas Soome                 {
9173c65ebfc7SToomas Soome                     ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
9174c65ebfc7SToomas Soome                     ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
9175c65ebfc7SToomas Soome                 }
9176c65ebfc7SToomas Soome             mDNSCoreResetRecord(m);
9177c65ebfc7SToomas Soome             continue;
9178c65ebfc7SToomas Soome         }
9179c65ebfc7SToomas Soome         // if a CNAME record points to itself, then don't add it to the cache
9180c65ebfc7SToomas Soome         if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
9181c65ebfc7SToomas Soome         {
9182c65ebfc7SToomas Soome             LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
9183c65ebfc7SToomas Soome             mDNSCoreResetRecord(m);
9184c65ebfc7SToomas Soome             continue;
9185c65ebfc7SToomas Soome         }
9186c65ebfc7SToomas Soome 
9187c65ebfc7SToomas Soome         // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9188c65ebfc7SToomas Soome         // In the case of active LLQs, we'll get remove events when the records actually do go away
9189c65ebfc7SToomas Soome         // In the case of polling LLQs, we assume the record remains valid until the next poll
9190*472cd20dSToomas Soome         if (!ResponseIsMDNS)
9191*472cd20dSToomas Soome         {
9192c65ebfc7SToomas Soome             m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
9193*472cd20dSToomas Soome         }
9194c65ebfc7SToomas Soome 
9195c65ebfc7SToomas Soome         // If response was not sent via LL multicast,
9196c65ebfc7SToomas Soome         // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9197c65ebfc7SToomas Soome         if (!ResponseMCast)
9198c65ebfc7SToomas Soome         {
9199c65ebfc7SToomas Soome             if (LLQType)
9200c65ebfc7SToomas Soome             {
9201c65ebfc7SToomas Soome                 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9202c65ebfc7SToomas Soome                 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9203c65ebfc7SToomas Soome                 // queries to get ADD/RMV events. To lookup the question, we can't use
9204c65ebfc7SToomas Soome                 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9205c65ebfc7SToomas Soome                 // has already matched the question using the 64 bit Id in the packet and we use that here.
9206c65ebfc7SToomas Soome 
9207*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9208*472cd20dSToomas Soome                 if (querier)
9209*472cd20dSToomas Soome                 {
9210*472cd20dSToomas Soome                     mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService);
9211*472cd20dSToomas Soome                 }
9212*472cd20dSToomas Soome #else
9213c65ebfc7SToomas Soome                 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
9214*472cd20dSToomas Soome #endif
9215c65ebfc7SToomas Soome             }
9216c65ebfc7SToomas Soome             else if (!AcceptableResponse || !dstaddr)
9217c65ebfc7SToomas Soome             {
9218c65ebfc7SToomas Soome                 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9219c65ebfc7SToomas Soome                 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9220c65ebfc7SToomas Soome                 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9221c65ebfc7SToomas Soome                 // we create.
9222*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9223*472cd20dSToomas Soome                 if (querier)
9224*472cd20dSToomas Soome                 {
9225*472cd20dSToomas Soome                     ResourceRecord *const rr = &m->rec.r.resrec;
9226*472cd20dSToomas Soome                     if (Querier_ResourceRecordIsAnswer(rr, querier))
9227*472cd20dSToomas Soome                     {
9228*472cd20dSToomas Soome                         const mdns_resolver_type_t resolver_type = mdns_querier_get_resolver_type(querier);
9229*472cd20dSToomas Soome                         if ((resolver_type == mdns_resolver_type_normal) &&
9230*472cd20dSToomas Soome                             (mdns_querier_get_over_tcp_reason(querier) != mdns_query_over_tcp_reason_null))
9231*472cd20dSToomas Soome                         {
9232*472cd20dSToomas Soome                             rr->protocol = mdns_resolver_type_tcp;
9233*472cd20dSToomas Soome                         }
9234*472cd20dSToomas Soome                         else
9235*472cd20dSToomas Soome                         {
9236*472cd20dSToomas Soome                             rr->protocol = resolver_type;
9237*472cd20dSToomas Soome                         }
9238*472cd20dSToomas Soome                         mdns_replace(&rr->dnsservice, uDNSService);
9239*472cd20dSToomas Soome                         AcceptableResponse = mDNStrue;
9240*472cd20dSToomas Soome                     }
9241*472cd20dSToomas Soome                 }
9242*472cd20dSToomas Soome                 else
9243*472cd20dSToomas Soome #endif
9244*472cd20dSToomas Soome                 {
9245*472cd20dSToomas Soome                     const DNSQuestion *q;
9246c65ebfc7SToomas Soome                     // Initialize the DNS server on the resource record which will now filter what questions we answer with
9247c65ebfc7SToomas Soome                     // this record.
9248c65ebfc7SToomas Soome                     //
9249c65ebfc7SToomas Soome                     // We could potentially lookup the DNS server based on the source address, but that may not work always
9250c65ebfc7SToomas Soome                     // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9251*472cd20dSToomas Soome                     // from the DNS server that queried. We follow the same logic here. If we can find a matching question based
9252c65ebfc7SToomas Soome                     // on the "id" and "source port", then this response answers the question and assume the response
9253c65ebfc7SToomas Soome                     // came from the same DNS server that we sent the query to.
9254*472cd20dSToomas Soome                     q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
9255c65ebfc7SToomas Soome                     if (q != mDNSNULL)
9256c65ebfc7SToomas Soome                     {
9257c65ebfc7SToomas Soome                         AcceptableResponse = mDNStrue;
9258c65ebfc7SToomas Soome                         if (!InterfaceID)
9259c65ebfc7SToomas Soome                         {
9260c65ebfc7SToomas Soome                             debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9261*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9262c65ebfc7SToomas Soome                             m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9263*472cd20dSToomas Soome #endif
9264c65ebfc7SToomas Soome                         }
9265c65ebfc7SToomas Soome                         else
9266c65ebfc7SToomas Soome                         {
9267c65ebfc7SToomas Soome                             // Accept all remaining records in this unicast response to an mDNS query.
9268c65ebfc7SToomas Soome                             recordAcceptedInResponse = mDNStrue;
9269*472cd20dSToomas Soome                             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9270*472cd20dSToomas Soome                                 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME " (" PUB_S ")",
9271*472cd20dSToomas Soome                                 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
9272c65ebfc7SToomas Soome                         }
9273c65ebfc7SToomas Soome                     }
9274c65ebfc7SToomas Soome                     else
9275c65ebfc7SToomas Soome                     {
9276c65ebfc7SToomas Soome                         // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9277c65ebfc7SToomas Soome                         // the question. The code below does that. So, make this record unacceptable for now
9278c65ebfc7SToomas Soome                         if (!InterfaceID)
9279c65ebfc7SToomas Soome                         {
9280c65ebfc7SToomas Soome                             debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9281c65ebfc7SToomas Soome                             AcceptableResponse = mDNSfalse;
9282c65ebfc7SToomas Soome                         }
9283c65ebfc7SToomas Soome                     }
9284c65ebfc7SToomas Soome                 }
9285c65ebfc7SToomas Soome             }
9286*472cd20dSToomas Soome         }
9287c65ebfc7SToomas Soome         else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9288c65ebfc7SToomas Soome         {
9289c65ebfc7SToomas Soome             // There are some routers (rare, thankfully) that generate bogus ARP responses for
9290c65ebfc7SToomas Soome             // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9291c65ebfc7SToomas Soome             // To work with these broken routers, client devices need to blacklist these broken
9292c65ebfc7SToomas Soome             // routers and ignore their bogus ARP responses. Some devices implement a technique
9293c65ebfc7SToomas Soome             // such as the one described in US Patent 7436783, which lets clients detect and
9294c65ebfc7SToomas Soome             // ignore these broken routers: <https://www.google.com/patents/US7436783>
9295c65ebfc7SToomas Soome 
9296c65ebfc7SToomas Soome             // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9297c65ebfc7SToomas Soome             // approach of just detecting these broken routers and completely disabling IPv4
9298c65ebfc7SToomas Soome             // link-local communication on interfaces where a broken router is detected.
9299c65ebfc7SToomas Soome             // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9300c65ebfc7SToomas Soome             // that are deemed “safe” for IPv4 link-local communication;
9301c65ebfc7SToomas Soome             // the flag is cleared on interfaces where a broken router is detected.
9302c65ebfc7SToomas Soome 
9303c65ebfc7SToomas Soome             // OS X and iOS will not even try to communicate with an IPv4
9304c65ebfc7SToomas Soome             // link-local destination on an interface without the IFEF_ARPLL flag set.
9305c65ebfc7SToomas Soome             // This can cause some badly written applications to freeze for a long time if they
9306c65ebfc7SToomas Soome             // attempt to connect to an IPv4 link-local destination address and then wait for
9307c65ebfc7SToomas Soome             // that connection attempt to time out before trying other candidate addresses.
9308c65ebfc7SToomas Soome 
9309c65ebfc7SToomas Soome             // To mask this client bug, we suppress acceptance of IPv4 link-local address
9310c65ebfc7SToomas Soome             // records on interfaces where we know the OS will be unwilling even to attempt
9311c65ebfc7SToomas Soome             // communication with those IPv4 link-local destination addresses.
9312c65ebfc7SToomas Soome             // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9313c65ebfc7SToomas Soome 
9314c65ebfc7SToomas Soome             const CacheRecord *const rr = &m->rec.r;
9315c65ebfc7SToomas Soome             const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9316c65ebfc7SToomas Soome             if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9317c65ebfc7SToomas Soome             {
9318c65ebfc7SToomas Soome                 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9319c65ebfc7SToomas Soome                 mDNSCoreResetRecord(m);
9320c65ebfc7SToomas Soome                 continue;
9321c65ebfc7SToomas Soome             }
9322c65ebfc7SToomas Soome         }
9323c65ebfc7SToomas Soome 
9324c65ebfc7SToomas Soome         // 1. Check that this packet resource record does not conflict with any of ours
9325*472cd20dSToomas Soome         if (ResponseIsMDNS && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9326c65ebfc7SToomas Soome         {
9327c65ebfc7SToomas Soome             if (m->CurrentRecord)
9328c65ebfc7SToomas Soome                 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9329c65ebfc7SToomas Soome             m->CurrentRecord = m->ResourceRecords;
9330c65ebfc7SToomas Soome             while (m->CurrentRecord)
9331c65ebfc7SToomas Soome             {
9332c65ebfc7SToomas Soome                 AuthRecord *rr = m->CurrentRecord;
9333c65ebfc7SToomas Soome                 m->CurrentRecord = rr->next;
9334c65ebfc7SToomas Soome                 // We accept all multicast responses, and unicast responses resulting from queries we issued
9335c65ebfc7SToomas Soome                 // For other unicast responses, this code accepts them only for responses with an
9336c65ebfc7SToomas Soome                 // (apparently) local source address that pertain to a record of our own that's in probing state
9337c65ebfc7SToomas Soome                 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9338c65ebfc7SToomas Soome 
9339c65ebfc7SToomas Soome                 if (PacketRRMatchesSignature(&m->rec.r, rr))        // If interface, name, type (if shared record) and class match...
9340c65ebfc7SToomas Soome                 {
9341c65ebfc7SToomas Soome                     // ... check to see if type and rdata are identical
9342c65ebfc7SToomas Soome                     if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9343c65ebfc7SToomas Soome                     {
9344c65ebfc7SToomas Soome                         // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9345c65ebfc7SToomas Soome                         if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9346c65ebfc7SToomas Soome                         {
9347c65ebfc7SToomas Soome                             // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9348c65ebfc7SToomas Soome                             if      (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9349c65ebfc7SToomas Soome                         }
9350c65ebfc7SToomas Soome                         else
9351c65ebfc7SToomas Soome                         {
9352c65ebfc7SToomas Soome                             if      (rr->ImmedAnswer == mDNSNULL)    { rr->ImmedAnswer = InterfaceID;       m->NextScheduledResponse = m->timenow; }
9353c65ebfc7SToomas Soome                             else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9354c65ebfc7SToomas Soome                         }
9355c65ebfc7SToomas Soome                     }
9356c65ebfc7SToomas Soome                     // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9357c65ebfc7SToomas Soome                     else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9358c65ebfc7SToomas Soome                     {
9359*472cd20dSToomas Soome                         LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9360*472cd20dSToomas Soome                             m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r), IIDPrintable(InterfaceID));
9361c65ebfc7SToomas Soome                         LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9362c65ebfc7SToomas Soome 
9363c65ebfc7SToomas Soome                         // If this record is marked DependentOn another record for conflict detection purposes,
9364c65ebfc7SToomas Soome                         // then *that* record has to be bumped back to probing state to resolve the conflict
9365c65ebfc7SToomas Soome                         if (rr->DependentOn)
9366c65ebfc7SToomas Soome                         {
9367c65ebfc7SToomas Soome                             while (rr->DependentOn) rr = rr->DependentOn;
9368c65ebfc7SToomas Soome                             LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9369c65ebfc7SToomas Soome                         }
9370c65ebfc7SToomas Soome 
9371c65ebfc7SToomas Soome                         // If we've just whacked this record's ProbeCount, don't need to do it again
9372c65ebfc7SToomas Soome                         if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9373c65ebfc7SToomas Soome                             LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9374c65ebfc7SToomas Soome                         else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9375c65ebfc7SToomas Soome                             LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9376c65ebfc7SToomas Soome                         else
9377c65ebfc7SToomas Soome                         {
9378c65ebfc7SToomas Soome                             LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9379c65ebfc7SToomas Soome                             // If we'd previously verified this record, put it back to probing state and try again
9380c65ebfc7SToomas Soome                             if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9381c65ebfc7SToomas Soome                             {
9382c65ebfc7SToomas Soome                                 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9383c65ebfc7SToomas Soome                                 rr->resrec.RecordType     = kDNSRecordTypeUnique;
9384c65ebfc7SToomas Soome                                 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9385c65ebfc7SToomas Soome                                 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9386c65ebfc7SToomas Soome                                 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9387c65ebfc7SToomas Soome                                 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9388c65ebfc7SToomas Soome                                 rr->ProbeCount     = DefaultProbeCountForTypeUnique + 1;
9389c65ebfc7SToomas Soome                                 rr->AnnounceCount  = InitialAnnounceCount;
9390c65ebfc7SToomas Soome                                 InitializeLastAPTime(m, rr);
9391c65ebfc7SToomas Soome                                 RecordProbeFailure(m, rr);  // Repeated late conflicts also cause us to back off to the slower probing rate
9392c65ebfc7SToomas Soome                             }
9393c65ebfc7SToomas Soome                             // If we're probing for this record, we just failed
9394c65ebfc7SToomas Soome                             else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9395c65ebfc7SToomas Soome                             {
9396c65ebfc7SToomas Soome 	                            // At this point in the code, we're probing for uniqueness.
9397c65ebfc7SToomas Soome 	                            // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9398c65ebfc7SToomas Soome 	                            // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9399c65ebfc7SToomas Soome                                 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9400c65ebfc7SToomas Soome                                 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9401c65ebfc7SToomas Soome                                 {
9402*472cd20dSToomas Soome                                     if ((rr->ProbingConflictCount == 0) || (m->MPktNum != rr->LastConflictPktNum))
9403c65ebfc7SToomas Soome                                     {
9404*472cd20dSToomas Soome                                         const NetworkInterfaceInfo *const intf = FirstInterfaceForID(m, InterfaceID);
9405*472cd20dSToomas Soome                                         rr->ProbingConflictCount++;
9406*472cd20dSToomas Soome                                         rr->LastConflictPktNum = m->MPktNum;
9407*472cd20dSToomas Soome                                         if (ResponseMCast && (!intf || intf->SupportsUnicastMDNSResponse) &&
9408*472cd20dSToomas Soome                                             (rr->ProbingConflictCount <= kMaxAllowedMCastProbingConflicts))
9409*472cd20dSToomas Soome                                         {
9410*472cd20dSToomas Soome                                             LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9411*472cd20dSToomas Soome                                                 "spurious multicast conflict (%d/%d) via interface %d for %s",
9412*472cd20dSToomas Soome                                                 rr->ProbeCount, kProbingConflictPauseDuration, rr->ProbingConflictCount,
9413*472cd20dSToomas Soome                                                 kMaxAllowedMCastProbingConflicts, IIDPrintable(InterfaceID), ARDisplayString(m, rr));
9414*472cd20dSToomas Soome                                             rr->ProbeCount = DefaultProbeCountForTypeUnique;
9415*472cd20dSToomas Soome                                             rr->LastAPTime = m->timenow + kProbingConflictPauseDuration - rr->ThisAPInterval;
9416*472cd20dSToomas Soome                                             SetNextAnnounceProbeTime(m, rr);
9417c65ebfc7SToomas Soome                                         }
9418c65ebfc7SToomas Soome                                         else
9419c65ebfc7SToomas Soome                                         {
9420*472cd20dSToomas Soome                                             LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9421*472cd20dSToomas Soome                                                 rr->ProbeCount, ARDisplayString(m, rr), ResponseMCast ? "multi" : "uni", IIDPrintable(InterfaceID));
9422c65ebfc7SToomas Soome                                             m->mDNSStats.NameConflicts++;
9423*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9424c65ebfc7SToomas Soome                                             // See if this record was also registered with any D2D plugins.
9425c65ebfc7SToomas Soome                                             D2D_stop_advertising_record(rr);
9426c65ebfc7SToomas Soome #endif
9427c65ebfc7SToomas Soome                                             mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9428c65ebfc7SToomas Soome                                         }
9429*472cd20dSToomas Soome                                     }
9430c65ebfc7SToomas Soome                                 }
9431c65ebfc7SToomas Soome                             }
9432c65ebfc7SToomas Soome                             // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9433c65ebfc7SToomas Soome                             // same machine giving different answers for the reverse mapping record, or there are two machines on the
9434c65ebfc7SToomas Soome                             // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9435c65ebfc7SToomas Soome                             // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9436c65ebfc7SToomas Soome                             // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9437c65ebfc7SToomas Soome                             else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9438c65ebfc7SToomas Soome                             {
9439c65ebfc7SToomas Soome                                 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9440c65ebfc7SToomas Soome                                 m->mDNSStats.KnownUniqueNameConflicts++;
9441*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9442c65ebfc7SToomas Soome                                 D2D_stop_advertising_record(rr);
9443c65ebfc7SToomas Soome #endif
9444c65ebfc7SToomas Soome                                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9445c65ebfc7SToomas Soome                             }
9446c65ebfc7SToomas Soome                             else
9447c65ebfc7SToomas Soome                                 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9448c65ebfc7SToomas Soome                         }
9449c65ebfc7SToomas Soome                     }
9450c65ebfc7SToomas Soome                     // Else, matching signature, different type or rdata, but not a considered a conflict.
9451c65ebfc7SToomas Soome                     // If the packet record has the cache-flush bit set, then we check to see if we
9452c65ebfc7SToomas Soome                     // have any record(s) of the same type that we should re-assert to rescue them
9453c65ebfc7SToomas Soome                     // (see note about "multi-homing and bridged networks" at the end of this function).
9454*472cd20dSToomas Soome                     else if ((m->rec.r.resrec.rrtype == rr->resrec.rrtype) &&
9455*472cd20dSToomas Soome                         (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) &&
9456*472cd20dSToomas Soome                         ((mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2) &&
9457*472cd20dSToomas Soome                         ResourceRecordIsValidAnswer(rr))
9458*472cd20dSToomas Soome                     {
9459*472cd20dSToomas Soome                         rr->ImmedAnswer = mDNSInterfaceMark;
9460*472cd20dSToomas Soome                         m->NextScheduledResponse = m->timenow;
9461*472cd20dSToomas Soome                     }
9462c65ebfc7SToomas Soome                 }
9463c65ebfc7SToomas Soome             }
9464c65ebfc7SToomas Soome         }
9465c65ebfc7SToomas Soome 
9466c65ebfc7SToomas Soome         if (!AcceptableResponse)
9467c65ebfc7SToomas Soome         {
9468*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9469*472cd20dSToomas Soome     #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9470*472cd20dSToomas Soome             not_answer_but_required_for_dnssec = adds_denial_records_in_cache_record(&m->rec.r.resrec,
9471*472cd20dSToomas Soome                 querier != mDNSNULL && mdns_querier_get_dnssec_ok(querier), &denial_of_existence_records);
9472*472cd20dSToomas Soome     #else
9473*472cd20dSToomas Soome             not_answer_but_required_for_dnssec = mDNSfalse;
9474*472cd20dSToomas Soome     #endif
9475*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9476*472cd20dSToomas Soome             AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords);
9477*472cd20dSToomas Soome 
9478*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9479*472cd20dSToomas Soome             if (AcceptableResponse) mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService);
9480*472cd20dSToomas Soome #else
9481c65ebfc7SToomas Soome             if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9482*472cd20dSToomas Soome #endif
9483c65ebfc7SToomas Soome         }
9484c65ebfc7SToomas Soome 
9485c65ebfc7SToomas Soome         // 2. See if we want to add this packet resource record to our cache
9486c65ebfc7SToomas Soome         // We only try to cache answers if we have a cache to put them in
9487c65ebfc7SToomas Soome         // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9488*472cd20dSToomas Soome         if (!AcceptableResponse) {
9489*472cd20dSToomas Soome             const char* savedString = "";
9490*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9491*472cd20dSToomas Soome             savedString = (not_answer_but_required_for_dnssec ? "Saved for DNSSEC" : "");
9492*472cd20dSToomas Soome #endif
9493*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S " %s",
9494*472cd20dSToomas Soome                 mDNSVal16(response->h.id), CRDisplayString(m, &m->rec.r), savedString);
9495*472cd20dSToomas Soome         }
9496*472cd20dSToomas Soome 
9497c65ebfc7SToomas Soome         if (m->rrcache_size && AcceptableResponse)
9498c65ebfc7SToomas Soome         {
9499c65ebfc7SToomas Soome             const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash);
9500c65ebfc7SToomas Soome             CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec);
9501c65ebfc7SToomas Soome             CacheRecord *rr = mDNSNULL;
9502c65ebfc7SToomas Soome 
9503c65ebfc7SToomas Soome             // 2a. Check if this packet resource record is already in our cache.
9504*472cd20dSToomas Soome             rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, &cfp, InterfaceID);
9505c65ebfc7SToomas Soome 
9506c65ebfc7SToomas Soome             // If packet resource record not in our cache, add it now
9507c65ebfc7SToomas Soome             // (unless it is just a deletion of a record we never had, in which case we don't care)
9508c65ebfc7SToomas Soome             if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9509c65ebfc7SToomas Soome             {
9510c65ebfc7SToomas Soome                 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9511c65ebfc7SToomas Soome                 mDNSs32 delay;
9512c65ebfc7SToomas Soome 
9513c65ebfc7SToomas Soome                 if (AddToCFList)
9514c65ebfc7SToomas Soome                     delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9515c65ebfc7SToomas Soome                 else
95163b436d06SToomas Soome                     delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash);
9517c65ebfc7SToomas Soome 
9518c65ebfc7SToomas Soome                 // If unique, assume we may have to delay delivery of this 'add' event.
9519c65ebfc7SToomas Soome                 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9520c65ebfc7SToomas Soome                 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9521c65ebfc7SToomas Soome                 // to schedule an mDNS_Execute task at the appropriate time.
9522*472cd20dSToomas Soome                 rr = CreateNewCacheEntry(m, slot, cg, delay, mDNStrue, srcaddr);
9523c65ebfc7SToomas Soome                 if (rr)
9524c65ebfc7SToomas Soome                 {
9525*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9526*472cd20dSToomas Soome                     set_denial_records_in_cache_record(rr, &denial_of_existence_records);
9527*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9528*472cd20dSToomas Soome 
9529c65ebfc7SToomas Soome                     rr->responseFlags = response->h.flags;
9530*472cd20dSToomas Soome 
9531*472cd20dSToomas Soome                     if (AddToCFList)
9532c65ebfc7SToomas Soome                     {
9533c65ebfc7SToomas Soome                         *cfp = rr;
9534c65ebfc7SToomas Soome                         cfp = &rr->NextInCFList;
9535c65ebfc7SToomas Soome                         *cfp = (CacheRecord*)1;
9536c65ebfc7SToomas Soome                     }
9537c65ebfc7SToomas Soome                     else if (rr->DelayDelivery)
9538c65ebfc7SToomas Soome                     {
9539c65ebfc7SToomas Soome                         ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9540c65ebfc7SToomas Soome                     }
9541c65ebfc7SToomas Soome                 }
9542c65ebfc7SToomas Soome             }
9543c65ebfc7SToomas Soome         }
9544c65ebfc7SToomas Soome         mDNSCoreResetRecord(m);
9545c65ebfc7SToomas Soome     }
9546c65ebfc7SToomas Soome 
9547c65ebfc7SToomas Soome exit:
9548c65ebfc7SToomas Soome     mDNSCoreResetRecord(m);
9549c65ebfc7SToomas Soome 
9550c65ebfc7SToomas Soome     // If we've just received one or more records with their cache flush bits set,
9551c65ebfc7SToomas Soome     // then scan that cache slot to see if there are any old stale records we need to flush
9552c65ebfc7SToomas Soome     while (CacheFlushRecords != (CacheRecord*)1)
9553c65ebfc7SToomas Soome     {
9554c65ebfc7SToomas Soome         CacheRecord *r1 = CacheFlushRecords, *r2;
9555c65ebfc7SToomas Soome         const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash);
9556c65ebfc7SToomas Soome         const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec);
95573b436d06SToomas Soome         mDNSBool purgedRecords = mDNSfalse;
9558c65ebfc7SToomas Soome         CacheFlushRecords = CacheFlushRecords->NextInCFList;
9559c65ebfc7SToomas Soome         r1->NextInCFList = mDNSNULL;
9560c65ebfc7SToomas Soome 
9561c65ebfc7SToomas Soome         // Look for records in the cache with the same signature as this new one with the cache flush
9562c65ebfc7SToomas Soome         // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9563c65ebfc7SToomas Soome         // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9564c65ebfc7SToomas Soome         // We make these TTL adjustments *only* for records that still have *more* than one second
9565c65ebfc7SToomas Soome         // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9566c65ebfc7SToomas Soome         // (and now has half a second remaining) could inadvertently get its life extended, by either
9567c65ebfc7SToomas Soome         // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9568c65ebfc7SToomas Soome         // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9569c65ebfc7SToomas Soome         // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9570c65ebfc7SToomas Soome         // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9571c65ebfc7SToomas Soome         // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9572c65ebfc7SToomas Soome         // To avoid this, we need to ensure that the cache flushing operation will only act to
9573c65ebfc7SToomas Soome         // *decrease* a record's remaining lifetime, never *increase* it.
9574c65ebfc7SToomas Soome         for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9575c65ebfc7SToomas Soome         {
9576*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9577*472cd20dSToomas Soome             mDNSBool match;
9578*472cd20dSToomas Soome #else
9579*472cd20dSToomas Soome             mDNSu32 id1;
9580*472cd20dSToomas Soome             mDNSu32 id2;
9581*472cd20dSToomas Soome #endif
9582c65ebfc7SToomas Soome             if (!r1->resrec.InterfaceID)
9583c65ebfc7SToomas Soome             {
9584*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9585*472cd20dSToomas Soome                 match = (r1->resrec.dnsservice == r2->resrec.dnsservice) ? mDNStrue : mDNSfalse;
9586*472cd20dSToomas Soome #else
9587c65ebfc7SToomas Soome                 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9588c65ebfc7SToomas Soome                 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9589*472cd20dSToomas Soome #endif
9590c65ebfc7SToomas Soome             }
9591c65ebfc7SToomas Soome             else
9592c65ebfc7SToomas Soome             {
9593*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9594*472cd20dSToomas Soome                 match = mDNStrue;
9595*472cd20dSToomas Soome #else
9596c65ebfc7SToomas Soome                 id1 = id2 = 0;
9597*472cd20dSToomas Soome #endif
9598c65ebfc7SToomas Soome             }
9599c65ebfc7SToomas Soome             // For Unicast (null InterfaceID) the resolver IDs should also match
9600c65ebfc7SToomas Soome             if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9601*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9602*472cd20dSToomas Soome                 (r1->resrec.InterfaceID || match) &&
9603*472cd20dSToomas Soome #else
9604c65ebfc7SToomas Soome                 (r1->resrec.InterfaceID || (id1 == id2)) &&
9605*472cd20dSToomas Soome #endif
9606c65ebfc7SToomas Soome                 r1->resrec.rrtype      == r2->resrec.rrtype &&
9607*472cd20dSToomas Soome                 r1->resrec.rrclass     == r2->resrec.rrclass
9608*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9609*472cd20dSToomas Soome                 // 2 RRSIGs need to cover the same DNS type to be identified as one RRSET, and have the same TTL
9610*472cd20dSToomas Soome                 && are_records_in_the_same_cache_set_for_dnssec(&r1->resrec, &r2->resrec)
9611*472cd20dSToomas Soome #endif
9612*472cd20dSToomas Soome                 )
9613c65ebfc7SToomas Soome             {
96143b436d06SToomas Soome                     if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal)
96153b436d06SToomas Soome                     {
96163b436d06SToomas Soome                         verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2);
96173b436d06SToomas Soome                         r1->resrec.mortality = Mortality_Immortal;   //  Immortalize the replacement record
96183b436d06SToomas Soome                     }
96193b436d06SToomas Soome 
9620c65ebfc7SToomas Soome                     // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9621c65ebfc7SToomas Soome                     // else, if record is old, mark it to be flushed
9622c65ebfc7SToomas Soome                     if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9623c65ebfc7SToomas Soome                     {
9624c65ebfc7SToomas Soome                         // If we find mismatched TTLs in an RRSet, correct them.
9625c65ebfc7SToomas Soome                         // We only do this for records with a TTL of 2 or higher. It's possible to have a
9626c65ebfc7SToomas Soome                         // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9627c65ebfc7SToomas Soome                         // which we treat as a goodbye followed by an addition) and in that case it would be
9628c65ebfc7SToomas Soome                         // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9629c65ebfc7SToomas Soome 
9630c65ebfc7SToomas Soome                         // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9631c65ebfc7SToomas Soome                         // because certain early Bonjour devices are known to have this specific mismatch, and
9632c65ebfc7SToomas Soome                         // there's no point filling syslog with messages about something we already know about.
9633c65ebfc7SToomas Soome                         // We also don't log this for uDNS responses, since a caching name server is obliged
9634c65ebfc7SToomas Soome                         // to give us an aged TTL to correct for how long it has held the record,
9635c65ebfc7SToomas Soome                         // so our received TTLs are expected to vary in that case
9636c65ebfc7SToomas Soome 
9637c65ebfc7SToomas Soome                         // We also suppress log message in the case of SRV records that are received
9638c65ebfc7SToomas Soome                         // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9639c65ebfc7SToomas Soome                         // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9640c65ebfc7SToomas Soome                         // GM builds.
9641c65ebfc7SToomas Soome                         if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9642c65ebfc7SToomas Soome                         {
9643c65ebfc7SToomas Soome                             if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9644c65ebfc7SToomas Soome                                 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9645*472cd20dSToomas Soome                                 ResponseIsMDNS)
9646c65ebfc7SToomas Soome                                 LogInfo("Correcting TTL from %4d to %4d for %s",
9647c65ebfc7SToomas Soome                                         r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9648c65ebfc7SToomas Soome                             r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9649c65ebfc7SToomas Soome                         }
9650c65ebfc7SToomas Soome                         r2->TimeRcvd = m->timenow;
96513b436d06SToomas Soome                         SetNextCacheCheckTimeForRecord(m, r2);
9652c65ebfc7SToomas Soome                     }
96533b436d06SToomas Soome                     else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed
9654c65ebfc7SToomas Soome                     {
9655c65ebfc7SToomas Soome                         verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9656c65ebfc7SToomas Soome                         verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9657c65ebfc7SToomas Soome                         // We set stale records to expire in one second.
9658c65ebfc7SToomas Soome                         // This gives the owner a chance to rescue it if necessary.
9659c65ebfc7SToomas Soome                         // This is important in the case of multi-homing and bridged networks:
9660c65ebfc7SToomas Soome                         //   Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9661c65ebfc7SToomas Soome                         //   bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9662c65ebfc7SToomas Soome                         //   set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9663c65ebfc7SToomas Soome                         //   will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9664c65ebfc7SToomas Soome                         //   By delaying the deletion by one second, we give X a change to notice that this bridging has
9665c65ebfc7SToomas Soome                         //   happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9666c65ebfc7SToomas Soome 
9667c65ebfc7SToomas Soome                         // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9668c65ebfc7SToomas Soome                         // final expiration queries for this record.
9669c65ebfc7SToomas Soome 
9670c65ebfc7SToomas Soome                         // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9671c65ebfc7SToomas Soome                         // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9672c65ebfc7SToomas Soome                         // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9673c65ebfc7SToomas Soome                         // <rdar://problem/5636422> Updating TXT records is too slow
9674c65ebfc7SToomas Soome                         // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9675c65ebfc7SToomas Soome                         // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9676c65ebfc7SToomas Soome                         if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9677c65ebfc7SToomas Soome                         {
9678c65ebfc7SToomas Soome                             LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9679c65ebfc7SToomas Soome                             r2->resrec.rroriginalttl = 0;
9680c65ebfc7SToomas Soome                         }
9681c65ebfc7SToomas Soome                         else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9682c65ebfc7SToomas Soome                         {
9683c65ebfc7SToomas Soome                             // We only set a record to expire in one second if it currently has *more* than a second to live
9684c65ebfc7SToomas Soome                             // If it's already due to expire in a second or less, we just leave it alone
9685c65ebfc7SToomas Soome                             r2->resrec.rroriginalttl = 1;
9686c65ebfc7SToomas Soome                             r2->UnansweredQueries = MaxUnansweredQueries;
9687c65ebfc7SToomas Soome                             r2->TimeRcvd = m->timenow - 1;
9688c65ebfc7SToomas Soome                             // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9689c65ebfc7SToomas Soome                             // that we marked for deletion via an explicit DE record
9690c65ebfc7SToomas Soome                         }
9691c65ebfc7SToomas Soome                         SetNextCacheCheckTimeForRecord(m, r2);
9692c65ebfc7SToomas Soome                     }
96933b436d06SToomas Soome                     else
96943b436d06SToomas Soome                     {
9695*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
96963b436d06SToomas Soome                     if (r2->resrec.mortality == Mortality_Ghost)
96973b436d06SToomas Soome                     {
96983b436d06SToomas Soome                         DNSQuestion * q;
96993b436d06SToomas Soome                         for (q = m->Questions; q; q=q->next)
97003b436d06SToomas Soome                         {
97013b436d06SToomas Soome                             if (!q->LongLived && ActiveQuestion(q) &&
9702*472cd20dSToomas Soome                                 CacheRecordAnswersQuestion(r2, q) &&
97033b436d06SToomas Soome                                 q->metrics.expiredAnswerState == ExpiredAnswer_AnsweredWithExpired)
97043b436d06SToomas Soome                             {
97053b436d06SToomas Soome                                 q->metrics.expiredAnswerState = ExpiredAnswer_ExpiredAnswerChanged;
97063b436d06SToomas Soome                             }
97073b436d06SToomas Soome                         }
97083b436d06SToomas Soome                     }
97093b436d06SToomas Soome #endif
97103b436d06SToomas Soome                     // Old uDNS records are scheduled to be purged instead of given at most one second to live.
97113b436d06SToomas Soome                     mDNS_PurgeCacheResourceRecord(m, r2);
97123b436d06SToomas Soome                     purgedRecords = mDNStrue;
97133b436d06SToomas Soome                 }
97143b436d06SToomas Soome             }
9715c65ebfc7SToomas Soome        }
9716c65ebfc7SToomas Soome 
9717c65ebfc7SToomas Soome         if (r1->DelayDelivery)  // If we were planning to delay delivery of this record, see if we still need to
9718c65ebfc7SToomas Soome         {
97193b436d06SToomas Soome             if (r1->resrec.InterfaceID)
97203b436d06SToomas Soome             {
97213b436d06SToomas Soome                 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash);
97223b436d06SToomas Soome             }
97233b436d06SToomas Soome             else
97243b436d06SToomas Soome             {
97253b436d06SToomas Soome                 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
97263b436d06SToomas Soome                 // them to be deleted before any ADD events for this record.
97273b436d06SToomas Soome                 r1->DelayDelivery = purgedRecords ? NonZeroTime(m->timenow) : 0;
97283b436d06SToomas Soome             }
9729c65ebfc7SToomas Soome             // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9730c65ebfc7SToomas Soome             if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9731c65ebfc7SToomas Soome             else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9732c65ebfc7SToomas Soome         }
9733c65ebfc7SToomas Soome     }
9734c65ebfc7SToomas Soome 
9735c65ebfc7SToomas Soome     // See if we need to generate negative cache entries for unanswered unicast questions
9736*472cd20dSToomas Soome     mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID,
9737*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9738*472cd20dSToomas Soome         querier, uDNSService,
9739*472cd20dSToomas Soome #endif
9740*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9741*472cd20dSToomas Soome         &denial_of_existence_records,
9742*472cd20dSToomas Soome #endif
9743*472cd20dSToomas Soome         LLQType);
9744c65ebfc7SToomas Soome 
9745*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9746*472cd20dSToomas Soome         destroy_denial_of_existence_records_t_if_nonnull(denial_of_existence_records);
9747*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9748c65ebfc7SToomas Soome }
9749c65ebfc7SToomas Soome 
9750c65ebfc7SToomas Soome // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9751c65ebfc7SToomas Soome // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9752c65ebfc7SToomas Soome // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9753c65ebfc7SToomas Soome // that warrants waking the sleeping host.
9754c65ebfc7SToomas Soome // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9755c65ebfc7SToomas Soome 
ScheduleWakeupForList(mDNS * const m,mDNSInterfaceID InterfaceID,mDNSEthAddr * e,AuthRecord * const thelist)9756c65ebfc7SToomas Soome mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9757c65ebfc7SToomas Soome {
9758c65ebfc7SToomas Soome     // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9759c65ebfc7SToomas Soome     // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9760c65ebfc7SToomas Soome     // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9761c65ebfc7SToomas Soome     // simple, we use the same mechanism for both lists.
9762c65ebfc7SToomas Soome     if (!e->l[0])
9763c65ebfc7SToomas Soome     {
9764c65ebfc7SToomas Soome         LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9765c65ebfc7SToomas Soome         return;
9766c65ebfc7SToomas Soome     }
9767c65ebfc7SToomas Soome     m->CurrentRecord = thelist;
9768c65ebfc7SToomas Soome     while (m->CurrentRecord)
9769c65ebfc7SToomas Soome     {
9770c65ebfc7SToomas Soome         AuthRecord *const rr = m->CurrentRecord;
9771c65ebfc7SToomas Soome         if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9772c65ebfc7SToomas Soome         {
9773c65ebfc7SToomas Soome             LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9774c65ebfc7SToomas Soome             mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9775c65ebfc7SToomas Soome         }
9776c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9777c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
9778c65ebfc7SToomas Soome     }
9779c65ebfc7SToomas Soome }
9780c65ebfc7SToomas Soome 
ScheduleWakeup(mDNS * const m,mDNSInterfaceID InterfaceID,mDNSEthAddr * e)9781c65ebfc7SToomas Soome mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9782c65ebfc7SToomas Soome {
9783c65ebfc7SToomas Soome     if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9784c65ebfc7SToomas Soome     ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9785c65ebfc7SToomas Soome     ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9786c65ebfc7SToomas Soome }
9787c65ebfc7SToomas Soome 
SPSRecordCallback(mDNS * const m,AuthRecord * const ar,mStatus result)9788c65ebfc7SToomas Soome mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9789c65ebfc7SToomas Soome {
9790c65ebfc7SToomas Soome     if (result && result != mStatus_MemFree)
9791c65ebfc7SToomas Soome         LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9792c65ebfc7SToomas Soome 
9793c65ebfc7SToomas Soome     if (result == mStatus_NameConflict)
9794c65ebfc7SToomas Soome     {
9795c65ebfc7SToomas Soome         mDNS_Lock(m);
9796c65ebfc7SToomas Soome         LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9797c65ebfc7SToomas Soome         if (ar->WakeUp.HMAC.l[0])
9798c65ebfc7SToomas Soome         {
9799c65ebfc7SToomas Soome             SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse);  // Send one wakeup magic packet
9800c65ebfc7SToomas Soome             ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC);                               // Schedule all other records with the same owner to be woken
9801c65ebfc7SToomas Soome         }
9802c65ebfc7SToomas Soome         mDNS_Unlock(m);
9803c65ebfc7SToomas Soome     }
9804c65ebfc7SToomas Soome 
9805c65ebfc7SToomas Soome     if (result == mStatus_NameConflict || result == mStatus_MemFree)
9806c65ebfc7SToomas Soome     {
9807c65ebfc7SToomas Soome         m->ProxyRecords--;
9808c65ebfc7SToomas Soome         mDNSPlatformMemFree(ar);
9809c65ebfc7SToomas Soome         mDNS_UpdateAllowSleep(m);
9810c65ebfc7SToomas Soome     }
9811c65ebfc7SToomas Soome }
9812c65ebfc7SToomas Soome 
GetValueForMACAddr(mDNSu8 * ptr,mDNSu8 * limit,mDNSEthAddr * eth)9813c65ebfc7SToomas Soome mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9814c65ebfc7SToomas Soome {
9815c65ebfc7SToomas Soome     int     i;
9816c65ebfc7SToomas Soome     mDNSs8  hval   = 0;
9817c65ebfc7SToomas Soome     int     colons = 0;
98183b436d06SToomas Soome     mDNSu16  val    = 0; /* need to use 16 bit int to detect overflow */
9819c65ebfc7SToomas Soome 
9820c65ebfc7SToomas Soome     for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9821c65ebfc7SToomas Soome     {
9822c65ebfc7SToomas Soome         hval = HexVal(*ptr);
9823c65ebfc7SToomas Soome         if (hval != -1)
9824c65ebfc7SToomas Soome         {
9825c65ebfc7SToomas Soome             val <<= 4;
9826c65ebfc7SToomas Soome             val |= hval;
9827c65ebfc7SToomas Soome         }
9828c65ebfc7SToomas Soome         else if (*ptr == ':')
9829c65ebfc7SToomas Soome         {
9830c65ebfc7SToomas Soome             if (colons >=5)
9831c65ebfc7SToomas Soome             {
9832c65ebfc7SToomas Soome                 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9833c65ebfc7SToomas Soome                 return mDNSNULL;
9834c65ebfc7SToomas Soome             }
98353b436d06SToomas Soome             eth->b[colons] = (mDNSs8)val;
9836c65ebfc7SToomas Soome             colons++;
9837c65ebfc7SToomas Soome             val = 0;
9838c65ebfc7SToomas Soome         }
9839c65ebfc7SToomas Soome     }
9840c65ebfc7SToomas Soome     if (colons != 5)
9841c65ebfc7SToomas Soome     {
9842c65ebfc7SToomas Soome         LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9843c65ebfc7SToomas Soome         return mDNSNULL;
9844c65ebfc7SToomas Soome     }
98453b436d06SToomas Soome     eth->b[colons] = (mDNSs8)val;
9846c65ebfc7SToomas Soome     return ptr;
9847c65ebfc7SToomas Soome }
9848c65ebfc7SToomas Soome 
GetValueForIPv6Addr(mDNSu8 * ptr,mDNSu8 * limit,mDNSv6Addr * v6)9849c65ebfc7SToomas Soome mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9850c65ebfc7SToomas Soome {
9851c65ebfc7SToomas Soome     int hval;
9852c65ebfc7SToomas Soome     int value;
9853c65ebfc7SToomas Soome     int numBytes;
9854c65ebfc7SToomas Soome     int digitsProcessed;
9855c65ebfc7SToomas Soome     int zeroFillStart;
9856c65ebfc7SToomas Soome     int numColons;
9857c65ebfc7SToomas Soome     mDNSu8 v6addr[16];
9858c65ebfc7SToomas Soome 
9859c65ebfc7SToomas Soome     // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9860c65ebfc7SToomas Soome     // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9861c65ebfc7SToomas Soome     //
9862c65ebfc7SToomas Soome     // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9863c65ebfc7SToomas Soome     // the result in "v6"
9864c65ebfc7SToomas Soome 
9865c65ebfc7SToomas Soome     numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9866c65ebfc7SToomas Soome     while (ptr < limit && *ptr != ' ')
9867c65ebfc7SToomas Soome     {
9868c65ebfc7SToomas Soome         hval = HexVal(*ptr);
9869c65ebfc7SToomas Soome         if (hval != -1)
9870c65ebfc7SToomas Soome         {
9871c65ebfc7SToomas Soome             value <<= 4;
9872c65ebfc7SToomas Soome             value |= hval;
9873c65ebfc7SToomas Soome             digitsProcessed = 1;
9874c65ebfc7SToomas Soome         }
9875c65ebfc7SToomas Soome         else if (*ptr == ':')
9876c65ebfc7SToomas Soome         {
9877c65ebfc7SToomas Soome             if (!digitsProcessed)
9878c65ebfc7SToomas Soome             {
9879c65ebfc7SToomas Soome                 // If we have already seen a "::", we should not see one more. Handle the special
9880c65ebfc7SToomas Soome                 // case of "::"
9881c65ebfc7SToomas Soome                 if (numColons)
9882c65ebfc7SToomas Soome                 {
9883c65ebfc7SToomas Soome                     // if we never filled any bytes and the next character is space (we have reached the end)
9884c65ebfc7SToomas Soome                     // we are done
9885c65ebfc7SToomas Soome                     if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9886c65ebfc7SToomas Soome                     {
9887c65ebfc7SToomas Soome                         mDNSPlatformMemZero(v6->b, 16);
9888c65ebfc7SToomas Soome                         return ptr + 1;
9889c65ebfc7SToomas Soome                     }
9890c65ebfc7SToomas Soome                     LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9891c65ebfc7SToomas Soome                     return mDNSNULL;
9892c65ebfc7SToomas Soome                 }
9893c65ebfc7SToomas Soome 
9894c65ebfc7SToomas Soome                 // We processed "::". We need to fill zeroes later. For now, mark the
9895c65ebfc7SToomas Soome                 // point where we will start filling zeroes from.
9896c65ebfc7SToomas Soome                 zeroFillStart = numBytes;
9897c65ebfc7SToomas Soome                 numColons++;
9898c65ebfc7SToomas Soome             }
9899c65ebfc7SToomas Soome             else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9900c65ebfc7SToomas Soome             {
9901c65ebfc7SToomas Soome                 // We have a trailing ":" i.e., no more characters after ":"
9902c65ebfc7SToomas Soome                 LogMsg("GetValueForIPv6Addr: Trailing colon");
9903c65ebfc7SToomas Soome                 return mDNSNULL;
9904c65ebfc7SToomas Soome             }
9905c65ebfc7SToomas Soome             else
9906c65ebfc7SToomas Soome             {
9907c65ebfc7SToomas Soome                 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9908c65ebfc7SToomas Soome                 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9909c65ebfc7SToomas Soome                 // filled here is 12 and 13.
9910c65ebfc7SToomas Soome                 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9911c65ebfc7SToomas Soome 
9912c65ebfc7SToomas Soome                 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9913c65ebfc7SToomas Soome                 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9914c65ebfc7SToomas Soome                 digitsProcessed = value = 0;
9915c65ebfc7SToomas Soome 
9916c65ebfc7SToomas Soome                 // Make sure that we did not fill the 13th and 14th byte above
9917c65ebfc7SToomas Soome                 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9918c65ebfc7SToomas Soome             }
9919c65ebfc7SToomas Soome         }
9920c65ebfc7SToomas Soome         ptr++;
9921c65ebfc7SToomas Soome     }
9922c65ebfc7SToomas Soome 
9923c65ebfc7SToomas Soome     // We should be processing the last set of bytes following the last ":" here
9924c65ebfc7SToomas Soome     if (!digitsProcessed)
9925c65ebfc7SToomas Soome     {
9926c65ebfc7SToomas Soome         LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9927c65ebfc7SToomas Soome         return mDNSNULL;
9928c65ebfc7SToomas Soome     }
9929c65ebfc7SToomas Soome 
9930c65ebfc7SToomas Soome     if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9931c65ebfc7SToomas Soome     v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9932c65ebfc7SToomas Soome     v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9933c65ebfc7SToomas Soome 
9934c65ebfc7SToomas Soome     if (zeroFillStart)
9935c65ebfc7SToomas Soome     {
9936c65ebfc7SToomas Soome         int i, j, n;
9937c65ebfc7SToomas Soome         for (i = 0; i < zeroFillStart; i++)
9938c65ebfc7SToomas Soome             v6->b[i] = v6addr[i];
9939c65ebfc7SToomas Soome         for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9940c65ebfc7SToomas Soome             v6->b[j] = 0;
9941c65ebfc7SToomas Soome         for (; j < 16; i++, j++)
9942c65ebfc7SToomas Soome             v6->b[j] = v6addr[i];
9943c65ebfc7SToomas Soome     }
9944c65ebfc7SToomas Soome     else if (numBytes == 16)
9945c65ebfc7SToomas Soome         mDNSPlatformMemCopy(v6->b, v6addr, 16);
9946c65ebfc7SToomas Soome     else
9947c65ebfc7SToomas Soome     {
9948c65ebfc7SToomas Soome         LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9949c65ebfc7SToomas Soome         return mDNSNULL;
9950c65ebfc7SToomas Soome     }
9951c65ebfc7SToomas Soome     return ptr;
9952c65ebfc7SToomas Soome }
9953c65ebfc7SToomas Soome 
GetValueForIPv4Addr(mDNSu8 * ptr,mDNSu8 * limit,mDNSv4Addr * v4)9954c65ebfc7SToomas Soome mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9955c65ebfc7SToomas Soome {
9956c65ebfc7SToomas Soome     mDNSu32 val;
9957c65ebfc7SToomas Soome     int dots = 0;
9958c65ebfc7SToomas Soome     val = 0;
9959c65ebfc7SToomas Soome 
9960c65ebfc7SToomas Soome     for ( ; ptr < limit && *ptr != ' '; ptr++)
9961c65ebfc7SToomas Soome     {
9962c65ebfc7SToomas Soome         if (*ptr >= '0' &&  *ptr <= '9')
9963c65ebfc7SToomas Soome             val = val * 10 + *ptr - '0';
9964c65ebfc7SToomas Soome         else if (*ptr == '.')
9965c65ebfc7SToomas Soome         {
9966c65ebfc7SToomas Soome             if (val > 255 || dots >= 3)
9967c65ebfc7SToomas Soome             {
9968c65ebfc7SToomas Soome                 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
9969c65ebfc7SToomas Soome                 return mDNSNULL;
9970c65ebfc7SToomas Soome             }
9971c65ebfc7SToomas Soome             v4->b[dots++] = val;
9972c65ebfc7SToomas Soome             val = 0;
9973c65ebfc7SToomas Soome         }
9974c65ebfc7SToomas Soome         else
9975c65ebfc7SToomas Soome         {
9976c65ebfc7SToomas Soome             // We have a zero at the end and if we reached that, then we are done.
9977c65ebfc7SToomas Soome             if (*ptr == 0 && ptr == limit - 1 && dots == 3)
9978c65ebfc7SToomas Soome             {
9979c65ebfc7SToomas Soome                 v4->b[dots] = val;
9980c65ebfc7SToomas Soome                 return ptr + 1;
9981c65ebfc7SToomas Soome             }
9982c65ebfc7SToomas Soome             else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
9983c65ebfc7SToomas Soome         }
9984c65ebfc7SToomas Soome     }
9985c65ebfc7SToomas Soome     if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
9986c65ebfc7SToomas Soome     v4->b[dots] = val;
9987c65ebfc7SToomas Soome     return ptr;
9988c65ebfc7SToomas Soome }
9989c65ebfc7SToomas Soome 
GetValueForKeepalive(mDNSu8 * ptr,mDNSu8 * limit,mDNSu32 * value)9990c65ebfc7SToomas Soome mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
9991c65ebfc7SToomas Soome {
9992c65ebfc7SToomas Soome     mDNSu32 val;
9993c65ebfc7SToomas Soome 
9994c65ebfc7SToomas Soome     val = 0;
9995c65ebfc7SToomas Soome     for ( ; ptr < limit && *ptr != ' '; ptr++)
9996c65ebfc7SToomas Soome     {
9997c65ebfc7SToomas Soome         if (*ptr < '0' || *ptr > '9')
9998c65ebfc7SToomas Soome         {
9999c65ebfc7SToomas Soome             // We have a zero at the end and if we reached that, then we are done.
10000c65ebfc7SToomas Soome             if (*ptr == 0 && ptr == limit - 1)
10001c65ebfc7SToomas Soome             {
10002c65ebfc7SToomas Soome                 *value = val;
10003c65ebfc7SToomas Soome                 return ptr + 1;
10004c65ebfc7SToomas Soome             }
10005c65ebfc7SToomas Soome             else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
10006c65ebfc7SToomas Soome         }
10007c65ebfc7SToomas Soome         val = val * 10 + *ptr - '0';
10008c65ebfc7SToomas Soome     }
10009c65ebfc7SToomas Soome     *value = val;
10010c65ebfc7SToomas Soome     return ptr;
10011c65ebfc7SToomas Soome }
10012c65ebfc7SToomas Soome 
mDNSValidKeepAliveRecord(AuthRecord * rr)10013c65ebfc7SToomas Soome mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
10014c65ebfc7SToomas Soome {
10015c65ebfc7SToomas Soome     mDNSAddr    laddr, raddr;
10016c65ebfc7SToomas Soome     mDNSEthAddr eth;
10017c65ebfc7SToomas Soome     mDNSIPPort  lport, rport;
10018c65ebfc7SToomas Soome     mDNSu32     timeout, seq, ack;
10019c65ebfc7SToomas Soome     mDNSu16     win;
10020c65ebfc7SToomas Soome 
10021c65ebfc7SToomas Soome     if (!mDNS_KeepaliveRecord(&rr->resrec))
10022c65ebfc7SToomas Soome     {
10023c65ebfc7SToomas Soome         return mDNSfalse;
10024c65ebfc7SToomas Soome     }
10025c65ebfc7SToomas Soome 
10026c65ebfc7SToomas Soome     timeout = seq = ack = 0;
10027c65ebfc7SToomas Soome     win = 0;
10028c65ebfc7SToomas Soome     laddr = raddr = zeroAddr;
10029c65ebfc7SToomas Soome     lport = rport = zeroIPPort;
10030c65ebfc7SToomas Soome     eth = zeroEthAddr;
10031c65ebfc7SToomas Soome 
10032c65ebfc7SToomas Soome     mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10033c65ebfc7SToomas Soome 
10034c65ebfc7SToomas Soome     if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
10035c65ebfc7SToomas Soome         mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
10036c65ebfc7SToomas Soome         mDNSEthAddressIsZero(eth))
10037c65ebfc7SToomas Soome     {
10038c65ebfc7SToomas Soome         return mDNSfalse;
10039c65ebfc7SToomas Soome     }
10040c65ebfc7SToomas Soome 
10041c65ebfc7SToomas Soome     return mDNStrue;
10042c65ebfc7SToomas Soome }
10043c65ebfc7SToomas Soome 
10044c65ebfc7SToomas Soome 
mDNS_ExtractKeepaliveInfo(AuthRecord * ar,mDNSu32 * timeout,mDNSAddr * laddr,mDNSAddr * raddr,mDNSEthAddr * eth,mDNSu32 * seq,mDNSu32 * ack,mDNSIPPort * lport,mDNSIPPort * rport,mDNSu16 * win)10045c65ebfc7SToomas Soome mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
10046c65ebfc7SToomas Soome                                          mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
10047c65ebfc7SToomas Soome {
10048c65ebfc7SToomas Soome     if (ar->resrec.rrtype != kDNSType_NULL)
10049c65ebfc7SToomas Soome         return;
10050c65ebfc7SToomas Soome 
10051c65ebfc7SToomas Soome     if (mDNS_KeepaliveRecord(&ar->resrec))
10052c65ebfc7SToomas Soome     {
10053c65ebfc7SToomas Soome         int len = ar->resrec.rdlength;
10054c65ebfc7SToomas Soome         mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
10055c65ebfc7SToomas Soome         mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
10056c65ebfc7SToomas Soome         mDNSu32 value = 0;
10057c65ebfc7SToomas Soome 
10058c65ebfc7SToomas Soome         while (ptr < limit)
10059c65ebfc7SToomas Soome         {
10060c65ebfc7SToomas Soome             mDNSu8 param = *ptr;
10061c65ebfc7SToomas Soome             ptr += 2;   // Skip the letter and the "="
10062c65ebfc7SToomas Soome             if (param == 'h')
10063c65ebfc7SToomas Soome             {
10064c65ebfc7SToomas Soome                 laddr->type = mDNSAddrType_IPv4;
10065c65ebfc7SToomas Soome                 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
10066c65ebfc7SToomas Soome             }
10067c65ebfc7SToomas Soome             else if (param == 'd')
10068c65ebfc7SToomas Soome             {
10069c65ebfc7SToomas Soome                 raddr->type = mDNSAddrType_IPv4;
10070c65ebfc7SToomas Soome                 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
10071c65ebfc7SToomas Soome             }
10072c65ebfc7SToomas Soome             else if (param == 'H')
10073c65ebfc7SToomas Soome             {
10074c65ebfc7SToomas Soome                 laddr->type = mDNSAddrType_IPv6;
10075c65ebfc7SToomas Soome                 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
10076c65ebfc7SToomas Soome             }
10077c65ebfc7SToomas Soome             else if (param == 'D')
10078c65ebfc7SToomas Soome             {
10079c65ebfc7SToomas Soome                 raddr->type = mDNSAddrType_IPv6;
10080c65ebfc7SToomas Soome                 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
10081c65ebfc7SToomas Soome             }
10082c65ebfc7SToomas Soome             else if (param == 'm')
10083c65ebfc7SToomas Soome             {
10084c65ebfc7SToomas Soome                 ptr = GetValueForMACAddr(ptr, limit, eth);
10085c65ebfc7SToomas Soome             }
10086c65ebfc7SToomas Soome             else
10087c65ebfc7SToomas Soome             {
10088c65ebfc7SToomas Soome                 ptr = GetValueForKeepalive(ptr, limit, &value);
10089c65ebfc7SToomas Soome             }
10090c65ebfc7SToomas Soome             if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10091c65ebfc7SToomas Soome 
10092c65ebfc7SToomas Soome             // Extract everything in network order so that it is easy for sending a keepalive and also
10093c65ebfc7SToomas Soome             // for matching incoming TCP packets
10094c65ebfc7SToomas Soome             switch (param)
10095c65ebfc7SToomas Soome             {
10096c65ebfc7SToomas Soome             case 't':
10097c65ebfc7SToomas Soome                 *timeout = value;
10098c65ebfc7SToomas Soome                 //if (*timeout < 120) *timeout = 120;
10099c65ebfc7SToomas Soome                 break;
10100c65ebfc7SToomas Soome             case 'h':
10101c65ebfc7SToomas Soome             case 'H':
10102c65ebfc7SToomas Soome             case 'd':
10103c65ebfc7SToomas Soome             case 'D':
10104c65ebfc7SToomas Soome             case 'm':
10105c65ebfc7SToomas Soome             case 'i':
10106c65ebfc7SToomas Soome             case 'c':
10107c65ebfc7SToomas Soome                 break;
10108c65ebfc7SToomas Soome             case 'l':
10109c65ebfc7SToomas Soome                 lport->NotAnInteger = swap16((mDNSu16)value);
10110c65ebfc7SToomas Soome                 break;
10111c65ebfc7SToomas Soome             case 'r':
10112c65ebfc7SToomas Soome                 rport->NotAnInteger = swap16((mDNSu16)value);
10113c65ebfc7SToomas Soome                 break;
10114c65ebfc7SToomas Soome             case 's':
10115c65ebfc7SToomas Soome                 *seq = swap32(value);
10116c65ebfc7SToomas Soome                 break;
10117c65ebfc7SToomas Soome             case 'a':
10118c65ebfc7SToomas Soome                 *ack = swap32(value);
10119c65ebfc7SToomas Soome                 break;
10120c65ebfc7SToomas Soome             case 'w':
10121c65ebfc7SToomas Soome                 *win = swap16((mDNSu16)value);
10122c65ebfc7SToomas Soome                 break;
10123c65ebfc7SToomas Soome             default:
10124c65ebfc7SToomas Soome                 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
10125c65ebfc7SToomas Soome                 ptr = limit;
10126c65ebfc7SToomas Soome                 break;
10127c65ebfc7SToomas Soome             }
10128c65ebfc7SToomas Soome             ptr++; // skip the space
10129c65ebfc7SToomas Soome         }
10130c65ebfc7SToomas Soome     }
10131c65ebfc7SToomas Soome }
10132c65ebfc7SToomas Soome 
10133c65ebfc7SToomas Soome // 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
10134c65ebfc7SToomas Soome // the clients need not retrieve this information from the auth record again.
mDNS_MatchKeepaliveInfo(mDNS * const m,const mDNSAddr * pladdr,const mDNSAddr * praddr,const mDNSIPPort plport,const mDNSIPPort prport,mDNSu32 * rseq,mDNSu32 * rack)10135c65ebfc7SToomas Soome mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
10136c65ebfc7SToomas Soome                                               const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
10137c65ebfc7SToomas Soome {
10138c65ebfc7SToomas Soome     AuthRecord *ar;
10139c65ebfc7SToomas Soome     mDNSAddr laddr, raddr;
10140c65ebfc7SToomas Soome     mDNSEthAddr eth;
10141c65ebfc7SToomas Soome     mDNSIPPort lport, rport;
10142c65ebfc7SToomas Soome     mDNSu32 timeout, seq, ack;
10143c65ebfc7SToomas Soome     mDNSu16 win;
10144c65ebfc7SToomas Soome 
10145c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar; ar=ar->next)
10146c65ebfc7SToomas Soome     {
10147c65ebfc7SToomas Soome         timeout = seq = ack = 0;
10148c65ebfc7SToomas Soome         win = 0;
10149c65ebfc7SToomas Soome         laddr = raddr = zeroAddr;
10150c65ebfc7SToomas Soome         lport = rport = zeroIPPort;
10151c65ebfc7SToomas Soome 
10152c65ebfc7SToomas Soome         if (!ar->WakeUp.HMAC.l[0]) continue;
10153c65ebfc7SToomas Soome 
10154c65ebfc7SToomas Soome         mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10155c65ebfc7SToomas Soome 
10156c65ebfc7SToomas Soome         // Did we parse correctly ?
10157c65ebfc7SToomas Soome         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10158c65ebfc7SToomas Soome         {
10159c65ebfc7SToomas Soome             debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
10160c65ebfc7SToomas Soome             continue;
10161c65ebfc7SToomas Soome         }
10162c65ebfc7SToomas Soome 
10163c65ebfc7SToomas Soome         debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10164c65ebfc7SToomas Soome                &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
10165c65ebfc7SToomas Soome 
10166c65ebfc7SToomas Soome         // Does it match the incoming TCP packet ?
10167c65ebfc7SToomas Soome         if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
10168c65ebfc7SToomas Soome         {
10169c65ebfc7SToomas Soome             // returning in network order
10170c65ebfc7SToomas Soome             *rseq = seq;
10171c65ebfc7SToomas Soome             *rack = ack;
10172c65ebfc7SToomas Soome             return ar;
10173c65ebfc7SToomas Soome         }
10174c65ebfc7SToomas Soome     }
10175c65ebfc7SToomas Soome     return mDNSNULL;
10176c65ebfc7SToomas Soome }
10177c65ebfc7SToomas Soome 
mDNS_SendKeepalives(mDNS * const m)10178c65ebfc7SToomas Soome mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
10179c65ebfc7SToomas Soome {
10180c65ebfc7SToomas Soome     AuthRecord *ar;
10181c65ebfc7SToomas Soome 
10182c65ebfc7SToomas Soome     for (ar = m->ResourceRecords; ar; ar=ar->next)
10183c65ebfc7SToomas Soome     {
10184c65ebfc7SToomas Soome         mDNSu32 timeout, seq, ack;
10185c65ebfc7SToomas Soome         mDNSu16 win;
10186c65ebfc7SToomas Soome         mDNSAddr laddr, raddr;
10187c65ebfc7SToomas Soome         mDNSEthAddr eth;
10188c65ebfc7SToomas Soome         mDNSIPPort lport, rport;
10189c65ebfc7SToomas Soome 
10190c65ebfc7SToomas Soome         timeout = seq = ack = 0;
10191c65ebfc7SToomas Soome         win = 0;
10192c65ebfc7SToomas Soome 
10193c65ebfc7SToomas Soome         laddr = raddr = zeroAddr;
10194c65ebfc7SToomas Soome         lport = rport = zeroIPPort;
10195c65ebfc7SToomas Soome 
10196c65ebfc7SToomas Soome         if (!ar->WakeUp.HMAC.l[0]) continue;
10197c65ebfc7SToomas Soome 
10198c65ebfc7SToomas Soome         mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10199c65ebfc7SToomas Soome 
10200c65ebfc7SToomas Soome         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10201c65ebfc7SToomas Soome         {
10202c65ebfc7SToomas Soome             debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
10203c65ebfc7SToomas Soome             continue;
10204c65ebfc7SToomas Soome         }
10205c65ebfc7SToomas Soome         LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10206c65ebfc7SToomas Soome 
10207c65ebfc7SToomas Soome         // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10208c65ebfc7SToomas Soome         // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10209c65ebfc7SToomas Soome         if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
10210c65ebfc7SToomas Soome         {
10211c65ebfc7SToomas Soome             mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10212c65ebfc7SToomas Soome             ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
10213c65ebfc7SToomas Soome         }
10214c65ebfc7SToomas Soome         if (m->NextScheduledKA - ar->KATimeExpire > 0)
10215c65ebfc7SToomas Soome             m->NextScheduledKA = ar->KATimeExpire;
10216c65ebfc7SToomas Soome     }
10217c65ebfc7SToomas Soome }
10218c65ebfc7SToomas Soome 
mDNS_SendKeepaliveACK(mDNS * const m,AuthRecord * ar)10219c65ebfc7SToomas Soome mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
10220c65ebfc7SToomas Soome {
10221c65ebfc7SToomas Soome     mDNSu32     timeout, seq, ack, seqInc;
10222c65ebfc7SToomas Soome     mDNSu16     win;
10223c65ebfc7SToomas Soome     mDNSAddr    laddr, raddr;
10224c65ebfc7SToomas Soome     mDNSEthAddr eth;
10225c65ebfc7SToomas Soome     mDNSIPPort  lport, rport;
10226c65ebfc7SToomas Soome     mDNSu8      *ptr;
10227c65ebfc7SToomas Soome 
10228c65ebfc7SToomas Soome     if (ar == mDNSNULL)
10229c65ebfc7SToomas Soome     {
10230c65ebfc7SToomas Soome         LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10231c65ebfc7SToomas Soome         return;
10232c65ebfc7SToomas Soome     }
10233c65ebfc7SToomas Soome 
10234c65ebfc7SToomas Soome     timeout = seq = ack = 0;
10235c65ebfc7SToomas Soome     win = 0;
10236c65ebfc7SToomas Soome 
10237c65ebfc7SToomas Soome     laddr = raddr = zeroAddr;
10238c65ebfc7SToomas Soome     lport = rport = zeroIPPort;
10239c65ebfc7SToomas Soome 
10240c65ebfc7SToomas Soome     mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10241c65ebfc7SToomas Soome 
10242c65ebfc7SToomas Soome     if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10243c65ebfc7SToomas Soome     {
10244c65ebfc7SToomas Soome         LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
10245c65ebfc7SToomas Soome         return;
10246c65ebfc7SToomas Soome     }
10247c65ebfc7SToomas Soome 
10248c65ebfc7SToomas Soome     // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10249c65ebfc7SToomas Soome     // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10250c65ebfc7SToomas Soome     // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10251c65ebfc7SToomas Soome     // it's converted to host byte order before incrementing it by one.
10252c65ebfc7SToomas Soome     ptr = (mDNSu8 *)&seq;
10253c65ebfc7SToomas Soome     seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
10254c65ebfc7SToomas Soome     ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
10255c65ebfc7SToomas Soome     ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
10256c65ebfc7SToomas Soome     ptr[2] = (mDNSu8)((seqInc >>  8) & 0xFF);
10257c65ebfc7SToomas Soome     ptr[3] = (mDNSu8)((seqInc      ) & 0xFF);
10258c65ebfc7SToomas Soome     LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10259c65ebfc7SToomas Soome     mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10260c65ebfc7SToomas Soome }
10261c65ebfc7SToomas Soome 
mDNSCoreReceiveUpdate(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * end,const mDNSAddr * srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,mDNSIPPort dstport,const mDNSInterfaceID InterfaceID)10262c65ebfc7SToomas Soome mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
10263c65ebfc7SToomas Soome                                      const DNSMessage *const msg, const mDNSu8 *end,
10264c65ebfc7SToomas Soome                                      const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
10265c65ebfc7SToomas Soome                                      const mDNSInterfaceID InterfaceID)
10266c65ebfc7SToomas Soome {
10267c65ebfc7SToomas Soome     int i;
10268c65ebfc7SToomas Soome     AuthRecord opt;
10269c65ebfc7SToomas Soome     mDNSu8 *p = m->omsg.data;
10270c65ebfc7SToomas Soome     OwnerOptData owner = zeroOwner;     // Need to zero this, so we'll know if this Update packet was missing its Owner option
10271c65ebfc7SToomas Soome     mDNSu32 updatelease = 0;
10272c65ebfc7SToomas Soome     const mDNSu8 *ptr;
10273c65ebfc7SToomas Soome 
10274c65ebfc7SToomas Soome     LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10275c65ebfc7SToomas Soome            "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10276c65ebfc7SToomas Soome            srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
10277c65ebfc7SToomas Soome            msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
10278c65ebfc7SToomas Soome            msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
10279c65ebfc7SToomas Soome            msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
10280c65ebfc7SToomas Soome            msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
10281c65ebfc7SToomas Soome 
10282c65ebfc7SToomas Soome     if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
10283c65ebfc7SToomas Soome 
10284c65ebfc7SToomas Soome     if (mDNS_PacketLoggingEnabled)
10285*472cd20dSToomas Soome         DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10286c65ebfc7SToomas Soome 
10287c65ebfc7SToomas Soome     ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
10288c65ebfc7SToomas Soome     if (ptr)
10289c65ebfc7SToomas Soome     {
10290c65ebfc7SToomas Soome         ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10291c65ebfc7SToomas Soome         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10292c65ebfc7SToomas Soome         {
10293c65ebfc7SToomas Soome             const rdataOPT *o;
10294c65ebfc7SToomas Soome             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10295c65ebfc7SToomas Soome             for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10296c65ebfc7SToomas Soome             {
10297c65ebfc7SToomas Soome                 if      (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10298c65ebfc7SToomas Soome                 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner       = o->u.owner;
10299c65ebfc7SToomas Soome             }
10300c65ebfc7SToomas Soome         }
10301c65ebfc7SToomas Soome         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10302c65ebfc7SToomas Soome     }
10303c65ebfc7SToomas Soome 
10304c65ebfc7SToomas Soome     InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10305c65ebfc7SToomas Soome 
10306c65ebfc7SToomas Soome     if (!updatelease || !owner.HMAC.l[0])
10307c65ebfc7SToomas Soome     {
10308c65ebfc7SToomas Soome         static int msgs = 0;
10309c65ebfc7SToomas Soome         if (msgs < 100)
10310c65ebfc7SToomas Soome         {
10311c65ebfc7SToomas Soome             msgs++;
10312c65ebfc7SToomas Soome             LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10313c65ebfc7SToomas Soome                    !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10314c65ebfc7SToomas Soome         }
10315c65ebfc7SToomas Soome         m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10316c65ebfc7SToomas Soome     }
10317c65ebfc7SToomas Soome     else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10318c65ebfc7SToomas Soome     {
10319c65ebfc7SToomas Soome         static int msgs = 0;
10320c65ebfc7SToomas Soome         if (msgs < 100)
10321c65ebfc7SToomas Soome         {
10322c65ebfc7SToomas Soome             msgs++;
10323c65ebfc7SToomas Soome             LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10324c65ebfc7SToomas Soome                    m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10325c65ebfc7SToomas Soome         }
10326c65ebfc7SToomas Soome         m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10327c65ebfc7SToomas Soome     }
10328c65ebfc7SToomas Soome     else
10329c65ebfc7SToomas Soome     {
10330c65ebfc7SToomas Soome         LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10331c65ebfc7SToomas Soome 
10332c65ebfc7SToomas Soome         if (updatelease > 24 * 60 * 60)
10333c65ebfc7SToomas Soome             updatelease = 24 * 60 * 60;
10334c65ebfc7SToomas Soome 
10335c65ebfc7SToomas Soome         if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10336c65ebfc7SToomas Soome             updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10337c65ebfc7SToomas Soome 
10338c65ebfc7SToomas Soome         ptr = LocateAuthorities(msg, end);
10339c65ebfc7SToomas Soome 
10340c65ebfc7SToomas Soome         // Clear any stale TCP keepalive records that may exist
10341c65ebfc7SToomas Soome         ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10342c65ebfc7SToomas Soome         ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10343c65ebfc7SToomas Soome 
10344c65ebfc7SToomas Soome         for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10345c65ebfc7SToomas Soome         {
10346c65ebfc7SToomas Soome             ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10347c65ebfc7SToomas Soome             if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10348c65ebfc7SToomas Soome             {
10349c65ebfc7SToomas Soome                 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10350*472cd20dSToomas Soome                 AuthRecord *ar = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10351c65ebfc7SToomas Soome                 if (!ar)
10352c65ebfc7SToomas Soome                 {
10353c65ebfc7SToomas Soome                     m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10354c65ebfc7SToomas Soome                     break;
10355c65ebfc7SToomas Soome                 }
10356c65ebfc7SToomas Soome                 else
10357c65ebfc7SToomas Soome                 {
10358c65ebfc7SToomas Soome                     mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10359c65ebfc7SToomas Soome                     m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10360c65ebfc7SToomas Soome                     // All stale keepalive records have been flushed prior to this loop.
10361c65ebfc7SToomas Soome                     if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10362c65ebfc7SToomas Soome                     {
10363c65ebfc7SToomas Soome                         ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10364c65ebfc7SToomas Soome                         ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10365c65ebfc7SToomas Soome                     }
10366c65ebfc7SToomas Soome                     mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10367c65ebfc7SToomas Soome                     AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10368c65ebfc7SToomas Soome                     ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10369c65ebfc7SToomas Soome                     ar->resrec.rdata->MaxRDLength = RDLengthMem;
10370c65ebfc7SToomas Soome                     mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10371c65ebfc7SToomas Soome                     ar->ForceMCast = mDNStrue;
10372c65ebfc7SToomas Soome                     ar->WakeUp     = owner;
10373c65ebfc7SToomas Soome                     if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10374c65ebfc7SToomas Soome                     {
10375c65ebfc7SToomas Soome                         mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10376c65ebfc7SToomas Soome                         if      (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10377c65ebfc7SToomas Soome                         else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10378c65ebfc7SToomas Soome                         debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10379c65ebfc7SToomas Soome                         if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10380c65ebfc7SToomas Soome                     }
10381c65ebfc7SToomas Soome                     ar->TimeRcvd   = m->timenow;
10382c65ebfc7SToomas Soome                     ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10383c65ebfc7SToomas Soome                     if (m->NextScheduledSPS - ar->TimeExpire > 0)
10384c65ebfc7SToomas Soome                         m->NextScheduledSPS = ar->TimeExpire;
10385c65ebfc7SToomas Soome                     ar->KATimeExpire = 0;
10386c65ebfc7SToomas Soome                     mDNS_Register_internal(m, ar);
10387c65ebfc7SToomas Soome 
10388c65ebfc7SToomas Soome                     m->ProxyRecords++;
10389c65ebfc7SToomas Soome                     mDNS_UpdateAllowSleep(m);
10390c65ebfc7SToomas Soome                     LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10391c65ebfc7SToomas Soome                 }
10392c65ebfc7SToomas Soome             }
10393c65ebfc7SToomas Soome             m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10394c65ebfc7SToomas Soome         }
10395c65ebfc7SToomas Soome 
10396c65ebfc7SToomas Soome         if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10397c65ebfc7SToomas Soome         {
10398c65ebfc7SToomas Soome             LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10399c65ebfc7SToomas Soome             ClearProxyRecords(m, &owner, m->DuplicateRecords);
10400c65ebfc7SToomas Soome             ClearProxyRecords(m, &owner, m->ResourceRecords);
10401c65ebfc7SToomas Soome         }
10402c65ebfc7SToomas Soome         else
10403c65ebfc7SToomas Soome         {
10404c65ebfc7SToomas Soome             mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10405c65ebfc7SToomas Soome             opt.resrec.rrclass    = NormalMaxDNSMessageData;
10406c65ebfc7SToomas Soome             opt.resrec.rdlength   = sizeof(rdataOPT);   // One option in this OPT record
10407c65ebfc7SToomas Soome             opt.resrec.rdestimate = sizeof(rdataOPT);
10408c65ebfc7SToomas Soome             opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
10409c65ebfc7SToomas Soome             opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10410c65ebfc7SToomas Soome             p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10411c65ebfc7SToomas Soome         }
10412c65ebfc7SToomas Soome     }
10413c65ebfc7SToomas Soome 
10414*472cd20dSToomas Soome     if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, mDNSNULL, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSfalse);
10415c65ebfc7SToomas Soome     mDNS_SendKeepalives(m);
10416c65ebfc7SToomas Soome }
10417c65ebfc7SToomas Soome 
mDNSGenerateOwnerOptForInterface(mDNS * const m,const mDNSInterfaceID InterfaceID,DNSMessage * msg)10418c65ebfc7SToomas Soome mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg)
10419c65ebfc7SToomas Soome {
10420c65ebfc7SToomas Soome     mDNSu8 *ptr    = msg->data;
10421c65ebfc7SToomas Soome     mDNSu8 *end    = mDNSNULL;
10422c65ebfc7SToomas Soome     mDNSu32 length = 0;
10423c65ebfc7SToomas Soome     AuthRecord opt;
10424c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
10425c65ebfc7SToomas Soome 
10426c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10427c65ebfc7SToomas Soome     opt.resrec.rrclass    = NormalMaxDNSMessageData;
10428c65ebfc7SToomas Soome     opt.resrec.rdlength   = sizeof(rdataOPT);
10429c65ebfc7SToomas Soome     opt.resrec.rdestimate = sizeof(rdataOPT);
10430c65ebfc7SToomas Soome 
10431c65ebfc7SToomas Soome     intf = FirstInterfaceForID(m, InterfaceID);
10432c65ebfc7SToomas Soome     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
10433c65ebfc7SToomas Soome 
10434c65ebfc7SToomas Soome     LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt));
10435c65ebfc7SToomas Soome     end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec);
10436c65ebfc7SToomas Soome     if (end != mDNSNULL)
10437c65ebfc7SToomas Soome     {
10438c65ebfc7SToomas Soome         // Put all the integer values in IETF byte-order (MSB first, LSB second)
10439c65ebfc7SToomas Soome         SwapDNSHeaderBytes(msg);
10440*472cd20dSToomas Soome         length = (mDNSu32)(end - msg->data);
10441c65ebfc7SToomas Soome     }
10442c65ebfc7SToomas Soome     else
10443c65ebfc7SToomas Soome         LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10444c65ebfc7SToomas Soome 
10445c65ebfc7SToomas Soome     return length;
10446c65ebfc7SToomas Soome }
10447c65ebfc7SToomas Soome 
10448c65ebfc7SToomas Soome // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10449c65ebfc7SToomas Soome // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10450c65ebfc7SToomas Soome // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10451c65ebfc7SToomas Soome // Really, both should be unified and handled in one place.
mDNSCoreReceiveUpdateR(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * end,const mDNSAddr * srcaddr,const mDNSInterfaceID InterfaceID)10452c65ebfc7SToomas Soome mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10453c65ebfc7SToomas Soome {
10454c65ebfc7SToomas Soome     if (InterfaceID)
10455c65ebfc7SToomas Soome     {
10456c65ebfc7SToomas Soome         mDNSu32 pktlease = 0, spsupdates = 0;
10457c65ebfc7SToomas Soome         const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease);
10458c65ebfc7SToomas Soome         const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour
10459c65ebfc7SToomas Soome         if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10460c65ebfc7SToomas Soome 
10461c65ebfc7SToomas Soome         if (m->CurrentRecord)
10462c65ebfc7SToomas Soome             LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10463c65ebfc7SToomas Soome         m->CurrentRecord = m->ResourceRecords;
10464c65ebfc7SToomas Soome         while (m->CurrentRecord)
10465c65ebfc7SToomas Soome         {
10466c65ebfc7SToomas Soome             AuthRecord *const rr = m->CurrentRecord;
10467c65ebfc7SToomas Soome             if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10468c65ebfc7SToomas Soome                 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10469c65ebfc7SToomas Soome                 {
10470c65ebfc7SToomas Soome                     // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10471c65ebfc7SToomas Soome                     // Clear the updateid when we are done sending on all interfaces.
10472c65ebfc7SToomas Soome                     mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10473c65ebfc7SToomas Soome                     if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10474c65ebfc7SToomas Soome                         bit_clr_opaque64(rr->updateIntID, scopeid);
10475c65ebfc7SToomas Soome                     if (mDNSOpaque64IsZero(&rr->updateIntID))
10476c65ebfc7SToomas Soome                         rr->updateid = zeroID;
10477c65ebfc7SToomas Soome                     rr->expire   = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10478c65ebfc7SToomas Soome                     spsupdates++;
10479c65ebfc7SToomas Soome                     LogSPS("Sleep Proxy %s record %2d %5d 0x%x 0x%x (%d) %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", spsupdates, updatelease, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr));
10480c65ebfc7SToomas Soome                     if (rr->WakeUp.HMAC.l[0])
10481c65ebfc7SToomas Soome                     {
10482c65ebfc7SToomas Soome                         rr->WakeUp.HMAC = zeroEthAddr;  // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10483c65ebfc7SToomas Soome                         rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10484c65ebfc7SToomas Soome                         mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10485c65ebfc7SToomas Soome                     }
10486c65ebfc7SToomas Soome                 }
10487c65ebfc7SToomas Soome             // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10488c65ebfc7SToomas Soome             // new records could have been added to the end of the list as a result of that call.
10489c65ebfc7SToomas Soome             if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10490c65ebfc7SToomas Soome                 m->CurrentRecord = rr->next;
10491c65ebfc7SToomas Soome         }
10492c65ebfc7SToomas Soome         if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10493c65ebfc7SToomas Soome         {
10494c65ebfc7SToomas Soome             char *ifname;
10495c65ebfc7SToomas Soome             mDNSAddr spsaddr;
10496c65ebfc7SToomas Soome             DNSMessage optMsg;
10497c65ebfc7SToomas Soome             int length;
10498c65ebfc7SToomas Soome             // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10499c65ebfc7SToomas Soome             ifname = InterfaceNameForID(m, InterfaceID);
10500c65ebfc7SToomas Soome             mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10501c65ebfc7SToomas Soome             mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10502c65ebfc7SToomas Soome 
10503c65ebfc7SToomas Soome             // Store the Owner OPT record for this interface.
10504c65ebfc7SToomas Soome             // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10505c65ebfc7SToomas Soome             InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags);
10506c65ebfc7SToomas Soome             length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg);
10507c65ebfc7SToomas Soome             if (length != 0)
10508c65ebfc7SToomas Soome             {
10509c65ebfc7SToomas Soome                 length += sizeof(DNSMessageHeader);
10510c65ebfc7SToomas Soome                 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length);
10511c65ebfc7SToomas Soome             }
10512c65ebfc7SToomas Soome         }
10513c65ebfc7SToomas Soome     }
10514c65ebfc7SToomas Soome     // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10515c65ebfc7SToomas Soome     // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10516c65ebfc7SToomas Soome     if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10517c65ebfc7SToomas Soome }
10518c65ebfc7SToomas Soome 
MakeNegativeCacheRecord(mDNS * const m,CacheRecord * const cr,const domainname * const name,const mDNSu32 namehash,const mDNSu16 rrtype,const mDNSu16 rrclass,mDNSu32 ttl_seconds,mDNSInterfaceID InterfaceID,mdns_dns_service_t service)10519*472cd20dSToomas Soome mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr, const domainname *const name,
10520*472cd20dSToomas Soome     const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID,
10521*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10522*472cd20dSToomas Soome     mdns_dns_service_t service)
10523*472cd20dSToomas Soome #else
10524*472cd20dSToomas Soome     DNSServer *dnsserver)
10525*472cd20dSToomas Soome #endif
10526c65ebfc7SToomas Soome {
10527c65ebfc7SToomas Soome     if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10528c65ebfc7SToomas Soome         LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10529c65ebfc7SToomas Soome 
10530c65ebfc7SToomas Soome     // Create empty resource record
10531c65ebfc7SToomas Soome     cr->resrec.RecordType    = kDNSRecordTypePacketNegative;
10532c65ebfc7SToomas Soome     cr->resrec.InterfaceID   = InterfaceID;
10533*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10534*472cd20dSToomas Soome     mdns_replace(&cr->resrec.dnsservice, service);
10535*472cd20dSToomas Soome #else
10536c65ebfc7SToomas Soome     cr->resrec.rDNSServer    = dnsserver;
10537*472cd20dSToomas Soome #endif
10538c65ebfc7SToomas Soome     cr->resrec.name          = name;    // Will be updated to point to cg->name when we call CreateNewCacheEntry
10539c65ebfc7SToomas Soome     cr->resrec.rrtype        = rrtype;
10540c65ebfc7SToomas Soome     cr->resrec.rrclass       = rrclass;
10541c65ebfc7SToomas Soome     cr->resrec.rroriginalttl = ttl_seconds;
10542c65ebfc7SToomas Soome     cr->resrec.rdlength      = 0;
10543c65ebfc7SToomas Soome     cr->resrec.rdestimate    = 0;
10544c65ebfc7SToomas Soome     cr->resrec.namehash      = namehash;
10545c65ebfc7SToomas Soome     cr->resrec.rdatahash     = 0;
10546c65ebfc7SToomas Soome     cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10547c65ebfc7SToomas Soome     cr->resrec.rdata->MaxRDLength = 0;
10548c65ebfc7SToomas Soome 
10549c65ebfc7SToomas Soome     cr->NextInKAList       = mDNSNULL;
10550c65ebfc7SToomas Soome     cr->TimeRcvd           = m->timenow;
10551c65ebfc7SToomas Soome     cr->DelayDelivery      = 0;
10552c65ebfc7SToomas Soome     cr->NextRequiredQuery  = m->timenow;
10553*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
10554*472cd20dSToomas Soome     cr->LastCachedAnswerTime= 0;
10555*472cd20dSToomas Soome #endif
10556c65ebfc7SToomas Soome     cr->CRActiveQuestion   = mDNSNULL;
10557c65ebfc7SToomas Soome     cr->UnansweredQueries  = 0;
10558c65ebfc7SToomas Soome     cr->LastUnansweredTime = 0;
10559c65ebfc7SToomas Soome     cr->NextInCFList       = mDNSNULL;
10560c65ebfc7SToomas Soome     cr->soa                = mDNSNULL;
10561c65ebfc7SToomas Soome     // Initialize to the basic one and the caller can set it to more
10562c65ebfc7SToomas Soome     // specific based on the response if any
10563c65ebfc7SToomas Soome     cr->responseFlags      = ResponseFlags;
10564c65ebfc7SToomas Soome }
10565c65ebfc7SToomas Soome 
10566*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
mDNSCoreReceiveForQuerier(mDNS * const m,DNSMessage * const msg,const mDNSu8 * const end,mdns_querier_t querier,mdns_dns_service_t dnsservice)10567*472cd20dSToomas Soome mDNSexport void mDNSCoreReceiveForQuerier(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10568*472cd20dSToomas Soome     mdns_querier_t querier, mdns_dns_service_t dnsservice)
10569*472cd20dSToomas Soome {
10570*472cd20dSToomas Soome     SwapDNSHeaderBytes(msg);
10571*472cd20dSToomas Soome     mDNS_Lock(m);
10572*472cd20dSToomas Soome     mDNSCoreReceiveResponse(m, msg, end, mDNSNULL, zeroIPPort, mDNSNULL, zeroIPPort, querier, dnsservice, mDNSNULL);
10573*472cd20dSToomas Soome     mDNS_Unlock(m);
10574*472cd20dSToomas Soome }
10575*472cd20dSToomas Soome #endif
10576*472cd20dSToomas Soome 
mDNSCoreReceive(mDNS * const m,DNSMessage * const msg,const mDNSu8 * const end,const mDNSAddr * const srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,const mDNSIPPort dstport,const mDNSInterfaceID InterfaceID)10577c65ebfc7SToomas Soome mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10578c65ebfc7SToomas Soome                                 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10579c65ebfc7SToomas Soome                                 const mDNSInterfaceID InterfaceID)
10580c65ebfc7SToomas Soome {
10581c65ebfc7SToomas Soome     mDNSInterfaceID ifid = InterfaceID;
10582c65ebfc7SToomas Soome     const mDNSu8 *const pkt = (mDNSu8 *)msg;
10583c65ebfc7SToomas Soome     const mDNSu8 StdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery;
10584c65ebfc7SToomas Soome     const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10585c65ebfc7SToomas Soome     const mDNSu8 UpdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_Update;
10586c65ebfc7SToomas Soome     const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10587c65ebfc7SToomas Soome     mDNSu8 QR_OP;
10588c65ebfc7SToomas Soome     mDNSu8 *ptr = mDNSNULL;
10589c65ebfc7SToomas Soome     mDNSBool TLS = (dstaddr == (mDNSAddr *)1);  // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10590c65ebfc7SToomas Soome     if (TLS) dstaddr = mDNSNULL;
10591c65ebfc7SToomas Soome 
10592c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
10593c65ebfc7SToomas Soome     if (mDNSSameAddress(srcaddr, &m->Router))
10594c65ebfc7SToomas Soome     {
10595c65ebfc7SToomas Soome #ifdef _LEGACY_NAT_TRAVERSAL_
10596c65ebfc7SToomas Soome         if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10597c65ebfc7SToomas Soome         {
10598c65ebfc7SToomas Soome             mDNS_Lock(m);
10599c65ebfc7SToomas Soome             LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10600c65ebfc7SToomas Soome             mDNS_Unlock(m);
10601c65ebfc7SToomas Soome             return;
10602c65ebfc7SToomas Soome         }
10603c65ebfc7SToomas Soome #endif
10604c65ebfc7SToomas Soome         if (mDNSSameIPPort(srcport, NATPMPPort))
10605c65ebfc7SToomas Soome         {
10606c65ebfc7SToomas Soome             mDNS_Lock(m);
10607c65ebfc7SToomas Soome             uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10608c65ebfc7SToomas Soome             mDNS_Unlock(m);
10609c65ebfc7SToomas Soome             return;
10610c65ebfc7SToomas Soome         }
10611c65ebfc7SToomas Soome     }
10612c65ebfc7SToomas Soome #ifdef _LEGACY_NAT_TRAVERSAL_
10613c65ebfc7SToomas Soome     else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10614c65ebfc7SToomas Soome #endif
10615c65ebfc7SToomas Soome 
10616c65ebfc7SToomas Soome #endif
10617c65ebfc7SToomas Soome     if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader))
10618c65ebfc7SToomas Soome     {
10619c65ebfc7SToomas Soome         LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt));
10620c65ebfc7SToomas Soome         return;
10621c65ebfc7SToomas Soome     }
10622c65ebfc7SToomas Soome     QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10623c65ebfc7SToomas Soome     // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10624c65ebfc7SToomas Soome     ptr = (mDNSu8 *)&msg->h.numQuestions;
10625c65ebfc7SToomas Soome     msg->h.numQuestions   = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10626c65ebfc7SToomas Soome     msg->h.numAnswers     = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10627c65ebfc7SToomas Soome     msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10628c65ebfc7SToomas Soome     msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10629c65ebfc7SToomas Soome 
10630c65ebfc7SToomas Soome     if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10631c65ebfc7SToomas Soome 
10632c65ebfc7SToomas Soome     // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10633c65ebfc7SToomas Soome     // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10634*472cd20dSToomas Soome     if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10635c65ebfc7SToomas Soome 
10636c65ebfc7SToomas Soome     mDNS_Lock(m);
10637c65ebfc7SToomas Soome     m->PktNum++;
10638c65ebfc7SToomas Soome     if (mDNSOpaque16IsZero(msg->h.id))
10639c65ebfc7SToomas Soome     {
10640c65ebfc7SToomas Soome         m->MPktNum++;
10641c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
10642c65ebfc7SToomas Soome         // Track the number of multicast packets received from a source outside our subnet.
10643c65ebfc7SToomas Soome         // Check the destination address to avoid accounting for spurious packets that
10644c65ebfc7SToomas Soome         // comes in with message id zero.
10645c65ebfc7SToomas Soome         if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr &&
10646c65ebfc7SToomas Soome             mDNSAddressIsAllDNSLinkGroup(dstaddr))
10647c65ebfc7SToomas Soome         {
10648c65ebfc7SToomas Soome             m->RemoteSubnet++;
10649c65ebfc7SToomas Soome         }
10650c65ebfc7SToomas Soome #endif // #if APPLE_OSX_mDNSResponder
10651c65ebfc7SToomas Soome     }
10652c65ebfc7SToomas Soome 
10653c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
10654c65ebfc7SToomas Soome     if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10655c65ebfc7SToomas Soome         if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10656c65ebfc7SToomas Soome         {
10657c65ebfc7SToomas Soome             ifid = mDNSInterface_Any;
10658c65ebfc7SToomas Soome             if (mDNS_PacketLoggingEnabled)
10659*472cd20dSToomas Soome                 DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10660c65ebfc7SToomas Soome             uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10661c65ebfc7SToomas Soome             // Note: mDNSCore also needs to get access to received unicast responses
10662c65ebfc7SToomas Soome         }
10663c65ebfc7SToomas Soome #endif
10664c65ebfc7SToomas Soome     if      (QR_OP == StdQ) mDNSCoreReceiveQuery   (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10665*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10666*472cd20dSToomas Soome     else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, mDNSNULL, mDNSNULL, ifid);
10667*472cd20dSToomas Soome #else
10668c65ebfc7SToomas Soome     else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10669*472cd20dSToomas Soome #endif
10670c65ebfc7SToomas Soome     else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate  (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10671c65ebfc7SToomas Soome     else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr,                            InterfaceID);
10672c65ebfc7SToomas Soome     else
10673c65ebfc7SToomas Soome     {
10674c65ebfc7SToomas Soome         if (mDNS_LoggingEnabled)
10675c65ebfc7SToomas Soome         {
10676c65ebfc7SToomas Soome             static int msgCount = 0;
10677c65ebfc7SToomas Soome             if (msgCount < 1000) {
10678c65ebfc7SToomas Soome                 int i = 0;
10679c65ebfc7SToomas Soome                 msgCount++;
10680c65ebfc7SToomas Soome                 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10681c65ebfc7SToomas Soome                         msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID);
10682c65ebfc7SToomas Soome                 while (i < (int)(end - pkt))
10683c65ebfc7SToomas Soome                 {
10684c65ebfc7SToomas Soome                     char buffer[128];
10685c65ebfc7SToomas Soome                     char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10686c65ebfc7SToomas Soome                     do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15);
10687c65ebfc7SToomas Soome                     LogInfo("%s", buffer);
10688c65ebfc7SToomas Soome                 }
10689c65ebfc7SToomas Soome             }
10690c65ebfc7SToomas Soome         }
10691c65ebfc7SToomas Soome     }
10692c65ebfc7SToomas Soome     // Packet reception often causes a change to the task list:
10693c65ebfc7SToomas Soome     // 1. Inbound queries can cause us to need to send responses
10694c65ebfc7SToomas Soome     // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10695c65ebfc7SToomas Soome     // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10696c65ebfc7SToomas Soome     // 4. Response packets that answer questions may cause our client to issue new questions
10697c65ebfc7SToomas Soome     mDNS_Unlock(m);
10698c65ebfc7SToomas Soome }
10699c65ebfc7SToomas Soome 
10700c65ebfc7SToomas Soome // ***************************************************************************
10701c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
10702c65ebfc7SToomas Soome #pragma mark -
10703c65ebfc7SToomas Soome #pragma mark - Searcher Functions
10704c65ebfc7SToomas Soome #endif
10705c65ebfc7SToomas Soome 
10706c65ebfc7SToomas Soome // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10707c65ebfc7SToomas Soome // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10708c65ebfc7SToomas Soome // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10709c65ebfc7SToomas Soome // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10710c65ebfc7SToomas Soome // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10711c65ebfc7SToomas Soome //
10712c65ebfc7SToomas Soome // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10713c65ebfc7SToomas Soome // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10714c65ebfc7SToomas Soome // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10715c65ebfc7SToomas Soome // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10716c65ebfc7SToomas Soome // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10717c65ebfc7SToomas Soome // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10718c65ebfc7SToomas Soome // breaks this design principle.
10719c65ebfc7SToomas Soome //
10720c65ebfc7SToomas Soome 
10721c65ebfc7SToomas Soome // If IsLLQ(Q) is true, it means the question is both:
10722c65ebfc7SToomas Soome // (a) long-lived and
10723c65ebfc7SToomas Soome // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10724c65ebfc7SToomas Soome // for multicast questions, we don't want to treat LongLived as anything special
10725c65ebfc7SToomas Soome #define IsLLQ(Q)                 ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10726*472cd20dSToomas Soome #define AWDLIsIncluded(Q)        (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10727*472cd20dSToomas Soome #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10728c65ebfc7SToomas Soome 
FindDuplicateQuestion(const mDNS * const m,const DNSQuestion * const question)10729c65ebfc7SToomas Soome mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10730c65ebfc7SToomas Soome {
10731c65ebfc7SToomas Soome     DNSQuestion *q;
10732c65ebfc7SToomas Soome     // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10733c65ebfc7SToomas Soome     // This prevents circular references, where two questions are each marked as a duplicate of the other.
10734c65ebfc7SToomas Soome     // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10735c65ebfc7SToomas Soome     // further in the list.
10736*472cd20dSToomas Soome     for (q = m->Questions; q && (q != question); q = q->next)
10737*472cd20dSToomas Soome     {
10738*472cd20dSToomas Soome         if (!SameQuestionKind(q, question))                             continue;
10739*472cd20dSToomas Soome         if (q->qnamehash          != question->qnamehash)               continue;
10740*472cd20dSToomas Soome         if (q->InterfaceID        != question->InterfaceID)             continue;
10741*472cd20dSToomas Soome         if (q->qtype              != question->qtype)                   continue;
10742*472cd20dSToomas Soome         if (q->qclass             != question->qclass)                  continue;
10743*472cd20dSToomas Soome         if (IsLLQ(q)              != IsLLQ(question))                   continue;
10744*472cd20dSToomas Soome         if (q->AuthInfo && !question->AuthInfo)                         continue;
10745*472cd20dSToomas Soome         if (!q->Suppressed        != !question->Suppressed)             continue;
10746*472cd20dSToomas Soome         if (q->BrowseThreshold    != question->BrowseThreshold)         continue;
10747*472cd20dSToomas Soome         if (AWDLIsIncluded(q)     != AWDLIsIncluded(question))          continue;
10748*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10749*472cd20dSToomas Soome         if (q->dnsservice         != question->dnsservice)              continue;
10750*472cd20dSToomas Soome #endif
10751*472cd20dSToomas Soome         if (!SameDomainName(&q->qname, &question->qname))               continue;
10752c65ebfc7SToomas Soome         return(q);
10753*472cd20dSToomas Soome     }
10754c65ebfc7SToomas Soome     return(mDNSNULL);
10755c65ebfc7SToomas Soome }
10756c65ebfc7SToomas Soome 
10757c65ebfc7SToomas Soome // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
UpdateQuestionDuplicates(mDNS * const m,DNSQuestion * const question)10758c65ebfc7SToomas Soome mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10759c65ebfc7SToomas Soome {
10760c65ebfc7SToomas Soome     DNSQuestion *q;
10761c65ebfc7SToomas Soome     DNSQuestion *first = mDNSNULL;
10762c65ebfc7SToomas Soome 
10763c65ebfc7SToomas Soome     // This is referring to some other question as duplicate. No other question can refer to this
10764c65ebfc7SToomas Soome     // question as a duplicate.
10765c65ebfc7SToomas Soome     if (question->DuplicateOf)
10766c65ebfc7SToomas Soome     {
10767*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10768*472cd20dSToomas Soome                "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME " (" PUB_S ") duplicate of %p " PRI_DM_NAME " (" PUB_S ")",
10769*472cd20dSToomas Soome                question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID),
10770*472cd20dSToomas Soome                question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), question->DuplicateOf,
10771*472cd20dSToomas Soome                DM_NAME_PARAM(&question->DuplicateOf->qname), DNSTypeName(question->DuplicateOf->qtype));
10772c65ebfc7SToomas Soome         return;
10773c65ebfc7SToomas Soome     }
10774c65ebfc7SToomas Soome 
10775c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next)        // Scan our list of questions
10776c65ebfc7SToomas Soome         if (q->DuplicateOf == question)         // To see if any questions were referencing this as their duplicate
10777c65ebfc7SToomas Soome         {
10778c65ebfc7SToomas Soome             q->DuplicateOf = first;
10779c65ebfc7SToomas Soome             if (!first)
10780c65ebfc7SToomas Soome             {
10781c65ebfc7SToomas Soome                 first = q;
10782c65ebfc7SToomas Soome                 // If q used to be a duplicate, but now is not,
10783c65ebfc7SToomas Soome                 // then inherit the state from the question that's going away
10784c65ebfc7SToomas Soome                 q->LastQTime         = question->LastQTime;
10785c65ebfc7SToomas Soome                 q->ThisQInterval     = question->ThisQInterval;
10786c65ebfc7SToomas Soome                 q->ExpectUnicastResp = question->ExpectUnicastResp;
10787c65ebfc7SToomas Soome                 q->LastAnswerPktNum  = question->LastAnswerPktNum;
10788c65ebfc7SToomas Soome                 q->RecentAnswerPkts  = question->RecentAnswerPkts;
10789c65ebfc7SToomas Soome                 q->RequestUnicast    = question->RequestUnicast;
10790c65ebfc7SToomas Soome                 q->LastQTxTime       = question->LastQTxTime;
10791c65ebfc7SToomas Soome                 q->CNAMEReferrals    = question->CNAMEReferrals;
10792c65ebfc7SToomas Soome                 q->nta               = question->nta;
10793c65ebfc7SToomas Soome                 q->servAddr          = question->servAddr;
10794c65ebfc7SToomas Soome                 q->servPort          = question->servPort;
10795*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10796*472cd20dSToomas Soome                 mdns_replace(&q->dnsservice, question->dnsservice);
10797*472cd20dSToomas Soome                 mdns_forget(&question->dnsservice);
10798*472cd20dSToomas Soome                 mdns_querier_forget(&q->querier);
10799*472cd20dSToomas Soome                 mdns_replace(&q->querier, question->querier);
10800*472cd20dSToomas Soome                 mdns_forget(&question->querier);
10801*472cd20dSToomas Soome #else
10802c65ebfc7SToomas Soome                 q->qDNSServer        = question->qDNSServer;
10803c65ebfc7SToomas Soome                 q->validDNSServers   = question->validDNSServers;
10804c65ebfc7SToomas Soome                 q->unansweredQueries = question->unansweredQueries;
10805c65ebfc7SToomas Soome                 q->noServerResponse  = question->noServerResponse;
10806c65ebfc7SToomas Soome                 q->triedAllServersOnce = question->triedAllServersOnce;
10807*472cd20dSToomas Soome #endif
10808c65ebfc7SToomas Soome 
10809c65ebfc7SToomas Soome                 q->TargetQID         = question->TargetQID;
10810*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10811c65ebfc7SToomas Soome                 q->LocalSocket       = question->LocalSocket;
10812c65ebfc7SToomas Soome                 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10813*472cd20dSToomas Soome #endif
10814c65ebfc7SToomas Soome 
10815c65ebfc7SToomas Soome                 q->state             = question->state;
10816c65ebfc7SToomas Soome                 //  q->tcp               = question->tcp;
10817c65ebfc7SToomas Soome                 q->ReqLease          = question->ReqLease;
10818c65ebfc7SToomas Soome                 q->expire            = question->expire;
10819c65ebfc7SToomas Soome                 q->ntries            = question->ntries;
10820c65ebfc7SToomas Soome                 q->id                = question->id;
10821c65ebfc7SToomas Soome 
10822*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10823c65ebfc7SToomas Soome                 question->LocalSocket = mDNSNULL;
10824*472cd20dSToomas Soome #endif
10825c65ebfc7SToomas Soome                 question->nta        = mDNSNULL;    // If we've got a GetZoneData in progress, transfer it to the newly active question
10826c65ebfc7SToomas Soome                 //  question->tcp        = mDNSNULL;
10827c65ebfc7SToomas Soome 
10828*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10829c65ebfc7SToomas Soome                 if (q->LocalSocket)
10830c65ebfc7SToomas Soome                     debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10831*472cd20dSToomas Soome #endif
10832c65ebfc7SToomas Soome                 if (q->nta)
10833c65ebfc7SToomas Soome                 {
10834c65ebfc7SToomas Soome                     LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10835c65ebfc7SToomas Soome                     q->nta->ZoneDataContext = q;
10836c65ebfc7SToomas Soome                 }
10837c65ebfc7SToomas Soome 
10838c65ebfc7SToomas Soome                 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10839c65ebfc7SToomas Soome                 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10840c65ebfc7SToomas Soome 
10841c65ebfc7SToomas Soome                 if (question->state == LLQ_Established)
10842c65ebfc7SToomas Soome                 {
10843c65ebfc7SToomas Soome                     LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10844c65ebfc7SToomas Soome                     question->state = 0;    // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10845c65ebfc7SToomas Soome                 }
10846c65ebfc7SToomas Soome 
10847c65ebfc7SToomas Soome                 SetNextQueryTime(m,q);
10848c65ebfc7SToomas Soome             }
10849c65ebfc7SToomas Soome         }
10850c65ebfc7SToomas Soome }
10851c65ebfc7SToomas Soome 
mDNS_AddMcastResolver(mDNS * const m,const domainname * d,const mDNSInterfaceID interface,mDNSu32 timeout)10852c65ebfc7SToomas Soome mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10853c65ebfc7SToomas Soome {
10854c65ebfc7SToomas Soome     McastResolver **p = &m->McastResolvers;
10855c65ebfc7SToomas Soome     McastResolver *tmp = mDNSNULL;
10856c65ebfc7SToomas Soome 
10857c65ebfc7SToomas Soome     if (!d) d = (const domainname *)"";
10858c65ebfc7SToomas Soome 
10859*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10860*472cd20dSToomas Soome         "mDNS_AddMcastResolver: Adding " PUB_DM_NAME ", InterfaceID %p, timeout %u", DM_NAME_PARAM(d), interface, timeout);
10861c65ebfc7SToomas Soome 
10862c65ebfc7SToomas Soome     mDNS_CheckLock(m);
10863c65ebfc7SToomas Soome 
10864c65ebfc7SToomas Soome     while (*p)  // Check if we already have this {interface, domain} tuple registered
10865c65ebfc7SToomas Soome     {
10866c65ebfc7SToomas Soome         if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10867c65ebfc7SToomas Soome         {
10868c65ebfc7SToomas Soome             if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10869c65ebfc7SToomas Soome             (*p)->flags &= ~McastResolver_FlagDelete;
10870c65ebfc7SToomas Soome             tmp = *p;
10871c65ebfc7SToomas Soome             *p = tmp->next;
10872c65ebfc7SToomas Soome             tmp->next = mDNSNULL;
10873c65ebfc7SToomas Soome         }
10874c65ebfc7SToomas Soome         else
10875c65ebfc7SToomas Soome             p=&(*p)->next;
10876c65ebfc7SToomas Soome     }
10877c65ebfc7SToomas Soome 
10878c65ebfc7SToomas Soome     if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10879c65ebfc7SToomas Soome     else
10880c65ebfc7SToomas Soome     {
10881c65ebfc7SToomas Soome         // allocate, add to list
10882*472cd20dSToomas Soome         *p = (McastResolver *) mDNSPlatformMemAllocateClear(sizeof(**p));
10883c65ebfc7SToomas Soome         if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10884c65ebfc7SToomas Soome         else
10885c65ebfc7SToomas Soome         {
10886c65ebfc7SToomas Soome             (*p)->interface = interface;
10887c65ebfc7SToomas Soome             (*p)->flags     = McastResolver_FlagNew;
10888c65ebfc7SToomas Soome             (*p)->timeout   = timeout;
10889c65ebfc7SToomas Soome             AssignDomainName(&(*p)->domain, d);
10890c65ebfc7SToomas Soome             (*p)->next = mDNSNULL;
10891c65ebfc7SToomas Soome         }
10892c65ebfc7SToomas Soome     }
10893c65ebfc7SToomas Soome     return(*p);
10894c65ebfc7SToomas Soome }
10895c65ebfc7SToomas Soome 
10896*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
PenaltyTimeForServer(mDNS * m,DNSServer * server)10897c65ebfc7SToomas Soome mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10898c65ebfc7SToomas Soome {
10899c65ebfc7SToomas Soome     mDNSs32 ptime = 0;
10900c65ebfc7SToomas Soome     if (server->penaltyTime != 0)
10901c65ebfc7SToomas Soome     {
10902c65ebfc7SToomas Soome         ptime = server->penaltyTime - m->timenow;
10903c65ebfc7SToomas Soome         if (ptime < 0)
10904c65ebfc7SToomas Soome         {
10905c65ebfc7SToomas Soome             // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10906c65ebfc7SToomas Soome             // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10907c65ebfc7SToomas Soome             // here
10908c65ebfc7SToomas Soome             LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10909c65ebfc7SToomas Soome                    ptime, server->penaltyTime, m->timenow);
10910c65ebfc7SToomas Soome             server->penaltyTime = 0;
10911c65ebfc7SToomas Soome             ptime = 0;
10912c65ebfc7SToomas Soome         }
10913c65ebfc7SToomas Soome     }
10914c65ebfc7SToomas Soome     return ptime;
10915c65ebfc7SToomas Soome }
10916*472cd20dSToomas Soome #endif
10917c65ebfc7SToomas Soome 
10918c65ebfc7SToomas Soome //Checks to see whether the newname is a better match for the name, given the best one we have
10919c65ebfc7SToomas Soome //seen so far (given in bestcount).
10920c65ebfc7SToomas Soome //Returns -1 if the newname is not a better match
10921c65ebfc7SToomas Soome //Returns 0 if the newname is the same as the old match
10922c65ebfc7SToomas Soome //Returns 1 if the newname is a better match
BetterMatchForName(const domainname * name,int namecount,const domainname * newname,int newcount,int bestcount)10923c65ebfc7SToomas Soome mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10924c65ebfc7SToomas Soome                                  int bestcount)
10925c65ebfc7SToomas Soome {
10926c65ebfc7SToomas Soome     // If the name contains fewer labels than the new server's domain or the new name
10927c65ebfc7SToomas Soome     // contains fewer labels than the current best, then it can't possibly be a better match
10928c65ebfc7SToomas Soome     if (namecount < newcount || newcount < bestcount) return -1;
10929c65ebfc7SToomas Soome 
10930c65ebfc7SToomas Soome     // If there is no match, return -1 and the caller will skip this newname for
10931c65ebfc7SToomas Soome     // selection
10932c65ebfc7SToomas Soome     //
10933c65ebfc7SToomas Soome     // If we find a match and the number of labels is the same as bestcount, then
10934c65ebfc7SToomas Soome     // we return 0 so that the caller can do additional logic to pick one of
10935c65ebfc7SToomas Soome     // the best based on some other factors e.g., penaltyTime
10936c65ebfc7SToomas Soome     //
10937c65ebfc7SToomas Soome     // If we find a match and the number of labels is more than bestcount, then we
10938c65ebfc7SToomas Soome     // return 1 so that the caller can pick this over the old one.
10939c65ebfc7SToomas Soome     //
10940c65ebfc7SToomas Soome     // Note: newcount can either be equal or greater than bestcount beause of the
10941c65ebfc7SToomas Soome     // check above.
10942c65ebfc7SToomas Soome 
10943c65ebfc7SToomas Soome     if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10944c65ebfc7SToomas Soome         return bestcount == newcount ? 0 : 1;
10945c65ebfc7SToomas Soome     else
10946c65ebfc7SToomas Soome         return -1;
10947c65ebfc7SToomas Soome }
10948c65ebfc7SToomas Soome 
10949c65ebfc7SToomas Soome // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10950c65ebfc7SToomas Soome // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10951c65ebfc7SToomas Soome // names. In that case, we give a default timeout of 5 seconds
10952c65ebfc7SToomas Soome #define DEFAULT_MCAST_TIMEOUT   5
GetTimeoutForMcastQuestion(mDNS * m,DNSQuestion * question)10953c65ebfc7SToomas Soome mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10954c65ebfc7SToomas Soome {
10955c65ebfc7SToomas Soome     McastResolver *curmatch = mDNSNULL;
10956c65ebfc7SToomas Soome     int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10957c65ebfc7SToomas Soome     McastResolver *curr;
10958c65ebfc7SToomas Soome     int bettermatch, currcount;
10959c65ebfc7SToomas Soome     for (curr = m->McastResolvers; curr; curr = curr->next)
10960c65ebfc7SToomas Soome     {
10961c65ebfc7SToomas Soome         currcount = CountLabels(&curr->domain);
10962c65ebfc7SToomas Soome         bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10963c65ebfc7SToomas Soome         // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10964c65ebfc7SToomas Soome         // the timeout value from the first one
10965c65ebfc7SToomas Soome         if (bettermatch == 1)
10966c65ebfc7SToomas Soome         {
10967c65ebfc7SToomas Soome             curmatch = curr;
10968c65ebfc7SToomas Soome             bestmatchlen = currcount;
10969c65ebfc7SToomas Soome         }
10970c65ebfc7SToomas Soome     }
10971c65ebfc7SToomas Soome     LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10972c65ebfc7SToomas Soome             curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10973c65ebfc7SToomas Soome     return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10974c65ebfc7SToomas Soome }
10975c65ebfc7SToomas Soome 
10976c65ebfc7SToomas Soome // Returns true if it is a Domain Enumeration Query
DomainEnumQuery(const domainname * qname)10977c65ebfc7SToomas Soome mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10978c65ebfc7SToomas Soome {
10979c65ebfc7SToomas Soome     const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10980c65ebfc7SToomas Soome                                        (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10981c65ebfc7SToomas Soome     const domainname *d = qname;
10982c65ebfc7SToomas Soome     const mDNSu8 *label;
10983c65ebfc7SToomas Soome     int i = 0;
10984c65ebfc7SToomas Soome 
10985c65ebfc7SToomas Soome     // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10986c65ebfc7SToomas Soome     if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10987c65ebfc7SToomas Soome 
10988c65ebfc7SToomas Soome     label = (const mDNSu8 *)d;
10989c65ebfc7SToomas Soome     while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10990c65ebfc7SToomas Soome     {
10991c65ebfc7SToomas Soome         if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10992c65ebfc7SToomas Soome         i++;
10993c65ebfc7SToomas Soome     }
10994c65ebfc7SToomas Soome     if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
10995c65ebfc7SToomas Soome     {
10996c65ebfc7SToomas Soome         debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
10997c65ebfc7SToomas Soome         return mDNSfalse;
10998c65ebfc7SToomas Soome     }
10999c65ebfc7SToomas Soome     debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
11000c65ebfc7SToomas Soome 
11001c65ebfc7SToomas Soome     // CountLabels already verified the number of labels
11002c65ebfc7SToomas Soome     d = (const domainname *)(d->c + 1 + d->c[0]);   // Second Label
11003c65ebfc7SToomas Soome     label = (const mDNSu8 *)d;
11004c65ebfc7SToomas Soome     if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
11005c65ebfc7SToomas Soome     {
11006c65ebfc7SToomas Soome         debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
11007c65ebfc7SToomas Soome         return(mDNSfalse);
11008c65ebfc7SToomas Soome     }
11009c65ebfc7SToomas Soome     debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
11010c65ebfc7SToomas Soome 
11011c65ebfc7SToomas Soome     d = (const domainname *)(d->c + 1 + d->c[0]);   // Third Label
11012c65ebfc7SToomas Soome     label = (const mDNSu8 *)d;
11013c65ebfc7SToomas Soome     if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
11014c65ebfc7SToomas Soome     {
11015c65ebfc7SToomas Soome         debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
11016c65ebfc7SToomas Soome         return(mDNSfalse);
11017c65ebfc7SToomas Soome     }
11018c65ebfc7SToomas Soome     debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
11019c65ebfc7SToomas Soome 
11020c65ebfc7SToomas Soome     debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
11021c65ebfc7SToomas Soome 
11022c65ebfc7SToomas Soome     return mDNStrue;
11023c65ebfc7SToomas Soome }
11024c65ebfc7SToomas Soome 
11025*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11026c65ebfc7SToomas Soome // Note: InterfaceID is the InterfaceID of the question
DNSServerMatch(DNSServer * d,mDNSInterfaceID InterfaceID,mDNSs32 ServiceID)11027c65ebfc7SToomas Soome mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11028c65ebfc7SToomas Soome {
11029c65ebfc7SToomas Soome     // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11030*472cd20dSToomas Soome     // with scopeType set to kScopeNone)
11031c65ebfc7SToomas Soome     //
11032c65ebfc7SToomas Soome     // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11033*472cd20dSToomas Soome     // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11034c65ebfc7SToomas Soome     //
11035c65ebfc7SToomas Soome     // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11036*472cd20dSToomas Soome     // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11037c65ebfc7SToomas Soome     //
11038c65ebfc7SToomas Soome     // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11039c65ebfc7SToomas Soome     // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11040c65ebfc7SToomas Soome     //
11041c65ebfc7SToomas Soome     // If the first condition fails, following are the possible cases (the notes below are using
11042c65ebfc7SToomas Soome     // InterfaceID for discussion and the same holds good for ServiceID):
11043c65ebfc7SToomas Soome     //
11044c65ebfc7SToomas Soome     // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11045c65ebfc7SToomas Soome     //   as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11046c65ebfc7SToomas Soome     //
11047c65ebfc7SToomas Soome     // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11048c65ebfc7SToomas Soome     //   unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11049c65ebfc7SToomas Soome     //   would fail in this case.
11050c65ebfc7SToomas Soome     //
11051c65ebfc7SToomas Soome     // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11052c65ebfc7SToomas Soome     //   should match (Refer to (2) above).
11053c65ebfc7SToomas Soome 
11054*472cd20dSToomas Soome     if (((d->scopeType == kScopeNone) && (!InterfaceID && ServiceID == -1))  ||
11055*472cd20dSToomas Soome         ((d->scopeType == kScopeInterfaceID) && d->interface == InterfaceID) ||
11056*472cd20dSToomas Soome         ((d->scopeType == kScopeServiceID) && d->serviceID == ServiceID))
11057c65ebfc7SToomas Soome     {
11058c65ebfc7SToomas Soome         return mDNStrue;
11059c65ebfc7SToomas Soome     }
11060c65ebfc7SToomas Soome     return mDNSfalse;
11061c65ebfc7SToomas Soome }
11062c65ebfc7SToomas Soome 
11063c65ebfc7SToomas Soome // Sets all the Valid DNS servers for a question
SetValidDNSServers(mDNS * m,DNSQuestion * question)11064c65ebfc7SToomas Soome mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
11065c65ebfc7SToomas Soome {
11066c65ebfc7SToomas Soome     int bestmatchlen = -1, namecount = CountLabels(&question->qname);
11067c65ebfc7SToomas Soome     DNSServer *curr;
11068c65ebfc7SToomas Soome     int bettermatch, currcount;
11069c65ebfc7SToomas Soome     int index = 0;
11070c65ebfc7SToomas Soome     mDNSu32 timeout = 0;
11071c65ebfc7SToomas Soome     mDNSBool DEQuery;
11072c65ebfc7SToomas Soome 
11073c65ebfc7SToomas Soome     question->validDNSServers = zeroOpaque128;
11074c65ebfc7SToomas Soome     DEQuery = DomainEnumQuery(&question->qname);
11075c65ebfc7SToomas Soome     for (curr = m->DNSServers; curr; curr = curr->next)
11076c65ebfc7SToomas Soome     {
11077*472cd20dSToomas Soome         debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scopeType);
11078c65ebfc7SToomas Soome         // skip servers that will soon be deleted
11079*472cd20dSToomas Soome         if (curr->flags & DNSServerFlag_Delete)
11080c65ebfc7SToomas Soome         {
11081*472cd20dSToomas Soome             debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11082c65ebfc7SToomas Soome             continue;
11083c65ebfc7SToomas Soome         }
11084c65ebfc7SToomas Soome 
11085c65ebfc7SToomas Soome         // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11086c65ebfc7SToomas Soome         // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11087c65ebfc7SToomas Soome         // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11088c65ebfc7SToomas Soome         // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11089c65ebfc7SToomas Soome         // match the scoped entries by mistake.
11090c65ebfc7SToomas Soome         //
11091c65ebfc7SToomas Soome         // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11092c65ebfc7SToomas Soome 
11093c65ebfc7SToomas Soome         // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11094*472cd20dSToomas Soome         if (((curr->scopeType == kScopeInterfaceID) && (curr->interface == mDNSInterface_Any)) ||
11095*472cd20dSToomas Soome             ((curr->scopeType == kScopeServiceID) && (curr->serviceID <= 0)))
11096c65ebfc7SToomas Soome         {
11097*472cd20dSToomas Soome             LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11098*472cd20dSToomas Soome                 (int)curr->scopeType, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
11099c65ebfc7SToomas Soome             continue;
11100c65ebfc7SToomas Soome         }
11101c65ebfc7SToomas Soome 
11102c65ebfc7SToomas Soome         currcount = CountLabels(&curr->domain);
11103*472cd20dSToomas Soome         if ((!DEQuery || !curr->isCell) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
11104c65ebfc7SToomas Soome         {
11105c65ebfc7SToomas Soome             bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11106c65ebfc7SToomas Soome 
11107c65ebfc7SToomas Soome             // If we found a better match (bettermatch == 1) then clear all the bits
11108c65ebfc7SToomas Soome             // corresponding to the old DNSServers that we have may set before and start fresh.
11109c65ebfc7SToomas Soome             // If we find an equal match, then include that DNSServer also by setting the corresponding
11110c65ebfc7SToomas Soome             // bit
11111c65ebfc7SToomas Soome             if ((bettermatch == 1) || (bettermatch == 0))
11112c65ebfc7SToomas Soome             {
11113c65ebfc7SToomas Soome                 bestmatchlen = currcount;
11114c65ebfc7SToomas Soome                 if (bettermatch)
11115c65ebfc7SToomas Soome                 {
11116c65ebfc7SToomas Soome                     debugf("SetValidDNSServers: Resetting all the bits");
11117c65ebfc7SToomas Soome                     question->validDNSServers = zeroOpaque128;
11118c65ebfc7SToomas Soome                     timeout = 0;
11119c65ebfc7SToomas Soome                 }
11120c65ebfc7SToomas Soome                 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11121*472cd20dSToomas Soome                        " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scopeType, index, curr->timeout,
11122c65ebfc7SToomas Soome                        curr->interface);
11123c65ebfc7SToomas Soome                 timeout += curr->timeout;
11124c65ebfc7SToomas Soome                 if (DEQuery)
11125*472cd20dSToomas Soome                     debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->isCell);
11126c65ebfc7SToomas Soome                 bit_set_opaque128(question->validDNSServers, index);
11127c65ebfc7SToomas Soome             }
11128c65ebfc7SToomas Soome         }
11129c65ebfc7SToomas Soome         index++;
11130c65ebfc7SToomas Soome     }
11131c65ebfc7SToomas Soome     question->noServerResponse = 0;
11132c65ebfc7SToomas Soome 
11133*472cd20dSToomas Soome     debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11134c65ebfc7SToomas Soome            question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
11135c65ebfc7SToomas Soome     // If there are no matching resolvers, then use the default timeout value.
11136*472cd20dSToomas Soome     return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
11137c65ebfc7SToomas Soome }
11138c65ebfc7SToomas Soome 
11139c65ebfc7SToomas Soome // Get the Best server that matches a name. If you find penalized servers, look for the one
11140c65ebfc7SToomas Soome // that will come out of the penalty box soon
GetBestServer(mDNS * m,const domainname * name,mDNSInterfaceID InterfaceID,mDNSs32 ServiceID,mDNSOpaque128 validBits,int * selected,mDNSBool nameMatch)11141c65ebfc7SToomas Soome mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits,
11142c65ebfc7SToomas Soome     int *selected, mDNSBool nameMatch)
11143c65ebfc7SToomas Soome {
11144c65ebfc7SToomas Soome     DNSServer *curmatch = mDNSNULL;
11145c65ebfc7SToomas Soome     int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
11146c65ebfc7SToomas Soome     DNSServer *curr;
11147c65ebfc7SToomas Soome     mDNSs32 bestPenaltyTime, currPenaltyTime;
11148c65ebfc7SToomas Soome     int bettermatch, currcount;
11149c65ebfc7SToomas Soome     int index = 0;
11150c65ebfc7SToomas Soome     int currindex = -1;
11151c65ebfc7SToomas Soome 
11152c65ebfc7SToomas Soome     debugf("GetBestServer: ValidDNSServer bits  0x%x%x", validBits.l[1], validBits.l[0]);
11153c65ebfc7SToomas Soome     bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
11154c65ebfc7SToomas Soome     for (curr = m->DNSServers; curr; curr = curr->next)
11155c65ebfc7SToomas Soome     {
11156c65ebfc7SToomas Soome         // skip servers that will soon be deleted
11157*472cd20dSToomas Soome         if (curr->flags & DNSServerFlag_Delete)
11158c65ebfc7SToomas Soome         {
11159*472cd20dSToomas Soome             debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11160c65ebfc7SToomas Soome             continue;
11161c65ebfc7SToomas Soome         }
11162c65ebfc7SToomas Soome 
11163c65ebfc7SToomas Soome         // Check if this is a valid DNSServer
11164c65ebfc7SToomas Soome         if (!bit_get_opaque64(validBits, index))
11165c65ebfc7SToomas Soome         {
11166c65ebfc7SToomas Soome             debugf("GetBestServer: continuing for index %d", index);
11167c65ebfc7SToomas Soome             index++;
11168c65ebfc7SToomas Soome             continue;
11169c65ebfc7SToomas Soome         }
11170c65ebfc7SToomas Soome 
11171c65ebfc7SToomas Soome         currcount = CountLabels(&curr->domain);
11172c65ebfc7SToomas Soome         currPenaltyTime = PenaltyTimeForServer(m, curr);
11173c65ebfc7SToomas Soome 
11174c65ebfc7SToomas Soome         debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11175c65ebfc7SToomas Soome                &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
11176c65ebfc7SToomas Soome 
11177c65ebfc7SToomas Soome         // If there are multiple best servers for a given question, we will pick the first one
11178c65ebfc7SToomas Soome         // if none of them are penalized. If some of them are penalized in that list, we pick
11179c65ebfc7SToomas Soome         // the least penalized one. BetterMatchForName walks through all best matches and
11180c65ebfc7SToomas Soome         // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11181c65ebfc7SToomas Soome         // in the list when there are no penalized servers and least one among them
11182c65ebfc7SToomas Soome         // when there are some penalized servers.
11183c65ebfc7SToomas Soome 
11184c65ebfc7SToomas Soome         if (DNSServerMatch(curr, InterfaceID, ServiceID))
11185c65ebfc7SToomas Soome         {
11186c65ebfc7SToomas Soome 
11187c65ebfc7SToomas Soome             // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11188c65ebfc7SToomas Soome             // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11189c65ebfc7SToomas Soome             // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11190c65ebfc7SToomas Soome             // part and still do some redundant steps e.g., InterfaceID match
11191c65ebfc7SToomas Soome 
11192c65ebfc7SToomas Soome             if (nameMatch)
11193c65ebfc7SToomas Soome                 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
11194c65ebfc7SToomas Soome             else
11195c65ebfc7SToomas Soome                 bettermatch = 0;
11196c65ebfc7SToomas Soome 
11197c65ebfc7SToomas Soome             // If we found a better match (bettermatch == 1) then we don't need to
11198c65ebfc7SToomas Soome             // compare penalty times. But if we found an equal match, then we compare
11199c65ebfc7SToomas Soome             // the penalty times to pick a better match
11200c65ebfc7SToomas Soome 
11201c65ebfc7SToomas Soome             if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
11202c65ebfc7SToomas Soome             {
11203c65ebfc7SToomas Soome                 currindex = index;
11204c65ebfc7SToomas Soome                 curmatch = curr;
11205c65ebfc7SToomas Soome                 bestmatchlen = currcount;
11206c65ebfc7SToomas Soome                 bestPenaltyTime = currPenaltyTime;
11207c65ebfc7SToomas Soome             }
11208c65ebfc7SToomas Soome         }
11209c65ebfc7SToomas Soome         index++;
11210c65ebfc7SToomas Soome     }
11211c65ebfc7SToomas Soome     if (selected) *selected = currindex;
11212c65ebfc7SToomas Soome     return curmatch;
11213c65ebfc7SToomas Soome }
11214c65ebfc7SToomas Soome 
11215c65ebfc7SToomas Soome // Look up a DNS Server, matching by name and InterfaceID
GetServerForName(mDNS * m,const domainname * name,mDNSInterfaceID InterfaceID,mDNSs32 ServiceID)11216c65ebfc7SToomas Soome mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11217c65ebfc7SToomas Soome {
11218c65ebfc7SToomas Soome     DNSServer *curmatch = mDNSNULL;
11219c65ebfc7SToomas Soome     char *ifname = mDNSNULL;    // for logging purposes only
11220c65ebfc7SToomas Soome     mDNSOpaque128 allValid;
11221c65ebfc7SToomas Soome 
11222*472cd20dSToomas Soome     if (InterfaceID == mDNSInterface_LocalOnly)
11223c65ebfc7SToomas Soome         InterfaceID = mDNSNULL;
11224c65ebfc7SToomas Soome 
11225c65ebfc7SToomas Soome     if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
11226c65ebfc7SToomas Soome 
11227c65ebfc7SToomas Soome     // By passing in all ones, we make sure that every DNS server is considered
11228c65ebfc7SToomas Soome     allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF;
11229c65ebfc7SToomas Soome 
11230c65ebfc7SToomas Soome     curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
11231c65ebfc7SToomas Soome 
11232c65ebfc7SToomas Soome     if (curmatch != mDNSNULL)
112333b436d06SToomas Soome         LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr,
11234c65ebfc7SToomas Soome                 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11235c65ebfc7SToomas Soome                 InterfaceID, name);
11236c65ebfc7SToomas Soome     else
112373b436d06SToomas Soome         LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name);
11238c65ebfc7SToomas Soome 
11239c65ebfc7SToomas Soome     return(curmatch);
11240c65ebfc7SToomas Soome }
11241c65ebfc7SToomas Soome 
11242c65ebfc7SToomas Soome // Look up a DNS Server for a question within its valid DNSServer bits
GetServerForQuestion(mDNS * m,DNSQuestion * question)11243c65ebfc7SToomas Soome mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
11244c65ebfc7SToomas Soome {
11245c65ebfc7SToomas Soome     DNSServer *curmatch = mDNSNULL;
11246c65ebfc7SToomas Soome     char *ifname = mDNSNULL;    // for logging purposes only
11247c65ebfc7SToomas Soome     mDNSInterfaceID InterfaceID = question->InterfaceID;
11248c65ebfc7SToomas Soome     const domainname *name = &question->qname;
11249c65ebfc7SToomas Soome     int currindex;
11250c65ebfc7SToomas Soome 
11251*472cd20dSToomas Soome     if (InterfaceID == mDNSInterface_LocalOnly)
11252c65ebfc7SToomas Soome         InterfaceID = mDNSNULL;
11253c65ebfc7SToomas Soome 
11254c65ebfc7SToomas Soome     if (InterfaceID)
11255c65ebfc7SToomas Soome         ifname = InterfaceNameForID(m, InterfaceID);
11256c65ebfc7SToomas Soome 
11257c65ebfc7SToomas Soome     if (!mDNSOpaque128IsZero(&question->validDNSServers))
11258c65ebfc7SToomas Soome     {
11259c65ebfc7SToomas Soome         curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
11260c65ebfc7SToomas Soome         if (currindex != -1)
11261c65ebfc7SToomas Soome             bit_clr_opaque128(question->validDNSServers, currindex);
11262c65ebfc7SToomas Soome     }
11263c65ebfc7SToomas Soome 
11264c65ebfc7SToomas Soome     if (curmatch != mDNSNULL)
11265c65ebfc7SToomas Soome     {
11266*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11267*472cd20dSToomas Soome                "[R%d->Q%d] GetServerForQuestion: %p DNS server (%p) " PRI_IP_ADDR ":%d (Penalty Time Left %d) (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11268*472cd20dSToomas Soome                question->request_id, mDNSVal16(question->TargetQID), question, curmatch, &curmatch->addr,
11269*472cd20dSToomas Soome                mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0),
11270*472cd20dSToomas Soome                ifname ? ifname : "None", InterfaceID, question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11271c65ebfc7SToomas Soome     }
11272c65ebfc7SToomas Soome     else
11273c65ebfc7SToomas Soome     {
11274*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11275*472cd20dSToomas Soome                "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11276*472cd20dSToomas Soome                question->request_id, mDNSVal16(question->TargetQID), question, ifname ? ifname : "None", InterfaceID,
11277*472cd20dSToomas Soome                question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11278c65ebfc7SToomas Soome     }
11279c65ebfc7SToomas Soome 
11280c65ebfc7SToomas Soome     return(curmatch);
11281c65ebfc7SToomas Soome }
11282*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11283c65ebfc7SToomas Soome 
11284c65ebfc7SToomas Soome // Called in normal client context (lock not held)
LLQNATCallback(mDNS * m,NATTraversalInfo * n)11285c65ebfc7SToomas Soome mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
11286c65ebfc7SToomas Soome {
11287c65ebfc7SToomas Soome     DNSQuestion *q;
11288c65ebfc7SToomas Soome     mDNS_Lock(m);
11289c65ebfc7SToomas Soome     LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
11290c65ebfc7SToomas Soome     n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
11291c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next)
11292c65ebfc7SToomas Soome         if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
11293c65ebfc7SToomas Soome             startLLQHandshake(m, q);    // If ExternalPort is zero, will do StartLLQPolling instead
11294c65ebfc7SToomas Soome     mDNS_Unlock(m);
11295c65ebfc7SToomas Soome }
11296c65ebfc7SToomas Soome 
11297c65ebfc7SToomas Soome // This function takes the DNSServer as a separate argument because sometimes the
11298*472cd20dSToomas Soome // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11299c65ebfc7SToomas Soome // status before switching to it.
11300*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
ShouldSuppressUnicastQuery(const DNSQuestion * const q,const mdns_dns_service_t dnsservice)11301*472cd20dSToomas Soome mDNSexport mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const mdns_dns_service_t dnsservice)
11302*472cd20dSToomas Soome #else
11303*472cd20dSToomas Soome mDNSlocal mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const DNSServer *const server)
11304*472cd20dSToomas Soome #endif
11305c65ebfc7SToomas Soome {
11306*472cd20dSToomas Soome     mDNSBool suppress = mDNSfalse;
11307*472cd20dSToomas Soome     const char *reason = mDNSNULL;
11308c65ebfc7SToomas Soome 
11309*472cd20dSToomas Soome     if (q->BlockedByPolicy)
11310c65ebfc7SToomas Soome     {
11311*472cd20dSToomas Soome         suppress = mDNStrue;
11312*472cd20dSToomas Soome         reason   = " (blocked by policy)";
11313c65ebfc7SToomas Soome     }
11314*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11315*472cd20dSToomas Soome     else if (!dnsservice)
11316c65ebfc7SToomas Soome     {
11317*472cd20dSToomas Soome         if (!q->IsUnicastDotLocal)
11318c65ebfc7SToomas Soome         {
11319*472cd20dSToomas Soome             suppress = mDNStrue;
11320*472cd20dSToomas Soome             reason   = " (no DNS service)";
11321c65ebfc7SToomas Soome         }
113223b436d06SToomas Soome     }
11323*472cd20dSToomas Soome #else
11324*472cd20dSToomas Soome     else if (!server)
11325c65ebfc7SToomas Soome     {
11326*472cd20dSToomas Soome         if (!q->IsUnicastDotLocal)
11327*472cd20dSToomas Soome         {
11328*472cd20dSToomas Soome             suppress = mDNStrue;
11329*472cd20dSToomas Soome             reason   = " (no DNS server)";
11330c65ebfc7SToomas Soome         }
11331c65ebfc7SToomas Soome     }
11332c65ebfc7SToomas Soome #endif
11333*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11334*472cd20dSToomas Soome     else if ((q->flags & kDNSServiceFlagsDenyCellular) && mdns_dns_service_interface_is_cellular(dnsservice))
11335*472cd20dSToomas Soome #else
11336*472cd20dSToomas Soome     else if ((q->flags & kDNSServiceFlagsDenyCellular) && server->isCell)
11337*472cd20dSToomas Soome #endif
11338*472cd20dSToomas Soome     {
11339*472cd20dSToomas Soome         suppress = mDNStrue;
11340*472cd20dSToomas Soome         reason   = " (interface is cellular)";
11341*472cd20dSToomas Soome     }
11342*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11343*472cd20dSToomas Soome     else if ((q->flags & kDNSServiceFlagsDenyExpensive) && mdns_dns_service_interface_is_expensive(dnsservice))
11344*472cd20dSToomas Soome #else
11345*472cd20dSToomas Soome     else if ((q->flags & kDNSServiceFlagsDenyExpensive) && server->isExpensive)
11346*472cd20dSToomas Soome #endif
11347*472cd20dSToomas Soome     {
11348*472cd20dSToomas Soome         suppress = mDNStrue;
11349*472cd20dSToomas Soome         reason   = " (interface is expensive)";
11350*472cd20dSToomas Soome     }
11351*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11352*472cd20dSToomas Soome     else if ((q->flags & kDNSServiceFlagsDenyConstrained) && mdns_dns_service_interface_is_constrained(dnsservice))
11353*472cd20dSToomas Soome #else
11354*472cd20dSToomas Soome     else if ((q->flags & kDNSServiceFlagsDenyConstrained) && server->isConstrained)
11355*472cd20dSToomas Soome #endif
11356*472cd20dSToomas Soome     {
11357*472cd20dSToomas Soome         suppress = mDNStrue;
11358*472cd20dSToomas Soome         reason   = " (interface is constrained)";
11359*472cd20dSToomas Soome     }
11360*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11361*472cd20dSToomas Soome     else if (q->SuppressUnusable && !DNS64IsQueryingARecord(q->dns64.state))
11362*472cd20dSToomas Soome #else
11363*472cd20dSToomas Soome     else if (q->SuppressUnusable)
11364*472cd20dSToomas Soome #endif
11365*472cd20dSToomas Soome     {
11366*472cd20dSToomas Soome         if (q->qtype == kDNSType_A)
11367*472cd20dSToomas Soome         {
11368*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11369*472cd20dSToomas Soome             if (!mdns_dns_service_a_queries_advised(dnsservice))
11370*472cd20dSToomas Soome #else
11371*472cd20dSToomas Soome             if (!server->usableA)
11372*472cd20dSToomas Soome #endif
11373*472cd20dSToomas Soome             {
11374*472cd20dSToomas Soome                 suppress = mDNStrue;
11375*472cd20dSToomas Soome                 reason   = " (A records are unusable)";
11376*472cd20dSToomas Soome             }
11377*472cd20dSToomas Soome             // If the server's configuration allows A record queries, suppress this query if
11378*472cd20dSToomas Soome             //     1. the interface associated with the server is CLAT46; and
11379*472cd20dSToomas Soome             //     2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11380*472cd20dSToomas Soome             // See <rdar://problem/42672030> for more info.
11381*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11382*472cd20dSToomas Soome             else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && mdns_dns_service_interface_is_clat46(dnsservice))
11383*472cd20dSToomas Soome #else
11384*472cd20dSToomas Soome             else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && server->isCLAT46)
11385*472cd20dSToomas Soome #endif
11386*472cd20dSToomas Soome             {
11387*472cd20dSToomas Soome                 suppress = mDNStrue;
11388*472cd20dSToomas Soome                 reason   = " (CLAT46 A records are unusable)";
11389*472cd20dSToomas Soome             }
11390*472cd20dSToomas Soome         }
11391*472cd20dSToomas Soome         else if (q->qtype == kDNSType_AAAA)
11392*472cd20dSToomas Soome         {
11393*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11394*472cd20dSToomas Soome             if (!mdns_dns_service_aaaa_queries_advised(dnsservice))
11395*472cd20dSToomas Soome #else
11396*472cd20dSToomas Soome             if (!server->usableAAAA)
11397*472cd20dSToomas Soome #endif
11398*472cd20dSToomas Soome             {
11399*472cd20dSToomas Soome                 suppress = mDNStrue;
11400*472cd20dSToomas Soome                 reason   = " (AAAA records are unusable)";
11401*472cd20dSToomas Soome             }
11402*472cd20dSToomas Soome         }
11403*472cd20dSToomas Soome     }
11404*472cd20dSToomas Soome     if (suppress)
11405*472cd20dSToomas Soome     {
11406*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11407*472cd20dSToomas Soome             "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME " " PUB_S PUB_S,
11408*472cd20dSToomas Soome             mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), reason ? reason : "");
11409*472cd20dSToomas Soome     }
11410*472cd20dSToomas Soome     return suppress;
11411c65ebfc7SToomas Soome }
11412c65ebfc7SToomas Soome 
ShouldSuppressQuery(DNSQuestion * q)11413*472cd20dSToomas Soome mDNSlocal mDNSBool ShouldSuppressQuery(DNSQuestion *q)
11414c65ebfc7SToomas Soome {
11415*472cd20dSToomas Soome     // Multicast queries are never suppressed.
11416*472cd20dSToomas Soome     if (mDNSOpaque16IsZero(q->TargetQID))
11417c65ebfc7SToomas Soome     {
11418c65ebfc7SToomas Soome         return mDNSfalse;
11419c65ebfc7SToomas Soome     }
11420*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11421*472cd20dSToomas Soome     return (ShouldSuppressUnicastQuery(q, q->dnsservice));
11422*472cd20dSToomas Soome #else
11423*472cd20dSToomas Soome     return (ShouldSuppressUnicastQuery(q, q->qDNSServer));
11424*472cd20dSToomas Soome #endif
11425c65ebfc7SToomas Soome }
11426c65ebfc7SToomas Soome 
CacheRecordRmvEventsForCurrentQuestion(mDNS * const m,DNSQuestion * q)11427c65ebfc7SToomas Soome mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11428c65ebfc7SToomas Soome {
11429*472cd20dSToomas Soome     CacheRecord *cr;
11430c65ebfc7SToomas Soome     CacheGroup *cg;
11431c65ebfc7SToomas Soome 
11432c65ebfc7SToomas Soome     cg = CacheGroupForName(m, q->qnamehash, &q->qname);
11433*472cd20dSToomas Soome     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
11434c65ebfc7SToomas Soome     {
11435c65ebfc7SToomas Soome         // Don't deliver RMV events for negative records
11436*472cd20dSToomas Soome         if (cr->resrec.RecordType == kDNSRecordTypePacketNegative)
11437c65ebfc7SToomas Soome         {
11438*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11439*472cd20dSToomas Soome                       "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S " Suppressing RMV events for question %p " PRI_DM_NAME " (" PUB_S "), CRActiveQuestion %p, CurrentAnswers %d",
11440*472cd20dSToomas Soome                       q->request_id, mDNSVal16(q->TargetQID), CRDisplayString(m, cr), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), cr->CRActiveQuestion, q->CurrentAnswers);
11441c65ebfc7SToomas Soome             continue;
11442c65ebfc7SToomas Soome         }
11443c65ebfc7SToomas Soome 
11444*472cd20dSToomas Soome         if (SameNameCacheRecordAnswersQuestion(cr, q))
11445c65ebfc7SToomas Soome         {
11446c65ebfc7SToomas Soome             LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11447*472cd20dSToomas Soome                     q->qname.c, CRDisplayString(m, cr), q->LOAddressAnswers);
11448c65ebfc7SToomas Soome 
11449c65ebfc7SToomas Soome             q->CurrentAnswers--;
11450*472cd20dSToomas Soome             if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11451*472cd20dSToomas Soome             if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11452*472cd20dSToomas Soome             AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
11453c65ebfc7SToomas Soome             if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
11454c65ebfc7SToomas Soome         }
11455c65ebfc7SToomas Soome     }
11456c65ebfc7SToomas Soome }
11457c65ebfc7SToomas Soome 
IsQuestionNew(mDNS * const m,DNSQuestion * question)11458c65ebfc7SToomas Soome mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11459c65ebfc7SToomas Soome {
11460c65ebfc7SToomas Soome     DNSQuestion *q;
11461c65ebfc7SToomas Soome     for (q = m->NewQuestions; q; q = q->next)
11462c65ebfc7SToomas Soome         if (q == question) return mDNStrue;
11463c65ebfc7SToomas Soome     return mDNSfalse;
11464c65ebfc7SToomas Soome }
11465c65ebfc7SToomas Soome 
11466*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
LocalRecordRmvEventsForQuestion(mDNS * const m,DNSQuestion * q)11467*472cd20dSToomas Soome mDNSexport mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11468*472cd20dSToomas Soome #else
11469c65ebfc7SToomas Soome mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11470*472cd20dSToomas Soome #endif
11471c65ebfc7SToomas Soome {
11472c65ebfc7SToomas Soome     AuthRecord *rr;
11473c65ebfc7SToomas Soome     AuthGroup *ag;
11474c65ebfc7SToomas Soome 
11475c65ebfc7SToomas Soome     if (m->CurrentQuestion)
11476c65ebfc7SToomas Soome         LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11477c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11478c65ebfc7SToomas Soome 
11479c65ebfc7SToomas Soome     if (IsQuestionNew(m, q))
11480c65ebfc7SToomas Soome     {
11481c65ebfc7SToomas Soome         LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11482c65ebfc7SToomas Soome         return mDNStrue;
11483c65ebfc7SToomas Soome     }
11484c65ebfc7SToomas Soome     m->CurrentQuestion = q;
11485c65ebfc7SToomas Soome     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
11486c65ebfc7SToomas Soome     if (ag)
11487c65ebfc7SToomas Soome     {
11488c65ebfc7SToomas Soome         for (rr = ag->members; rr; rr=rr->next)
11489c65ebfc7SToomas Soome             // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11490c65ebfc7SToomas Soome             if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11491c65ebfc7SToomas Soome             {
11492c65ebfc7SToomas Soome                 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11493c65ebfc7SToomas Soome                         ARDisplayString(m, rr));
11494c65ebfc7SToomas Soome                 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11495c65ebfc7SToomas Soome                 {
11496c65ebfc7SToomas Soome                     LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11497c65ebfc7SToomas Soome                            " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11498c65ebfc7SToomas Soome                            q->CurrentAnswers, q->LOAddressAnswers);
11499c65ebfc7SToomas Soome                     continue;
11500c65ebfc7SToomas Soome                 }
11501c65ebfc7SToomas Soome                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv);      // MUST NOT dereference q again
11502c65ebfc7SToomas Soome                 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11503c65ebfc7SToomas Soome             }
11504c65ebfc7SToomas Soome     }
11505c65ebfc7SToomas Soome     m->CurrentQuestion = mDNSNULL;
11506c65ebfc7SToomas Soome     return mDNStrue;
11507c65ebfc7SToomas Soome }
11508c65ebfc7SToomas Soome 
11509c65ebfc7SToomas Soome // Returns false if the question got deleted while delivering the RMV events
11510c65ebfc7SToomas Soome // The caller should handle the case
CacheRecordRmvEventsForQuestion(mDNS * const m,DNSQuestion * q)11511c65ebfc7SToomas Soome mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11512c65ebfc7SToomas Soome {
11513c65ebfc7SToomas Soome     if (m->CurrentQuestion)
11514c65ebfc7SToomas Soome         LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11515c65ebfc7SToomas Soome                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11516c65ebfc7SToomas Soome 
11517c65ebfc7SToomas Soome     // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11518c65ebfc7SToomas Soome     // If this question was answered using local auth records, then you can't deliver RMVs using cache
11519c65ebfc7SToomas Soome     if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11520c65ebfc7SToomas Soome     {
11521c65ebfc7SToomas Soome         m->CurrentQuestion = q;
11522c65ebfc7SToomas Soome         CacheRecordRmvEventsForCurrentQuestion(m, q);
11523c65ebfc7SToomas Soome         if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11524c65ebfc7SToomas Soome         m->CurrentQuestion = mDNSNULL;
11525c65ebfc7SToomas Soome     }
11526c65ebfc7SToomas Soome     else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11527c65ebfc7SToomas Soome     return mDNStrue;
11528c65ebfc7SToomas Soome }
11529c65ebfc7SToomas Soome 
SuppressStatusChanged(mDNS * const m,DNSQuestion * q,DNSQuestion ** restart)11530c65ebfc7SToomas Soome mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11531c65ebfc7SToomas Soome {
11532c65ebfc7SToomas Soome     // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11533c65ebfc7SToomas Soome     // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11534c65ebfc7SToomas Soome     // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11535*472cd20dSToomas Soome     if (q->Suppressed)
11536c65ebfc7SToomas Soome     {
11537*472cd20dSToomas Soome         q->Suppressed = mDNSfalse;
11538c65ebfc7SToomas Soome         if (!CacheRecordRmvEventsForQuestion(m, q))
11539c65ebfc7SToomas Soome         {
11540*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11541*472cd20dSToomas Soome                 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11542*472cd20dSToomas Soome                 q->request_id, mDNSVal16(q->TargetQID));
11543c65ebfc7SToomas Soome             return;
11544c65ebfc7SToomas Soome         }
11545*472cd20dSToomas Soome         q->Suppressed = mDNStrue;
11546c65ebfc7SToomas Soome     }
11547c65ebfc7SToomas Soome 
11548c65ebfc7SToomas Soome     // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11549*472cd20dSToomas Soome     // and Suppressed status does not mean anything for these questions. As we are going to stop the
11550c65ebfc7SToomas Soome     // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11551c65ebfc7SToomas Soome     // the restart will not be a duplicate ADD
11552c65ebfc7SToomas Soome     if (!LocalRecordRmvEventsForQuestion(m, q))
11553c65ebfc7SToomas Soome     {
11554*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11555*472cd20dSToomas Soome             "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11556*472cd20dSToomas Soome             q->request_id, mDNSVal16(q->TargetQID));
11557c65ebfc7SToomas Soome         return;
11558c65ebfc7SToomas Soome     }
11559c65ebfc7SToomas Soome 
11560c65ebfc7SToomas Soome     // There are two cases here.
11561c65ebfc7SToomas Soome     //
11562c65ebfc7SToomas Soome     // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11563c65ebfc7SToomas Soome     // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11564c65ebfc7SToomas Soome     // because when we get the response, if we had entries in the cache already, it will not answer
11565c65ebfc7SToomas Soome     // this question if the cache entry did not change. Hence, we need to restart
11566c65ebfc7SToomas Soome     // the query so that it can be answered from the cache.
11567c65ebfc7SToomas Soome     //
11568c65ebfc7SToomas Soome     // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11569c65ebfc7SToomas Soome     // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11570*472cd20dSToomas Soome     // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11571c65ebfc7SToomas Soome     // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11572*472cd20dSToomas Soome     // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11573c65ebfc7SToomas Soome     // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11574c65ebfc7SToomas Soome     // the question is not suppressed, we don't want two active questions sending packets on the wire.
11575c65ebfc7SToomas Soome     // This affects both efficiency and also the current design where there is only one active question
11576c65ebfc7SToomas Soome     // pointed to from a cache entry.
11577c65ebfc7SToomas Soome     //
11578c65ebfc7SToomas Soome     // We restart queries in a two step process by first calling stop and build a temporary list which we
11579c65ebfc7SToomas Soome     // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11580c65ebfc7SToomas Soome     // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11581c65ebfc7SToomas Soome     // will soon become the real question) including q->ThisQInterval which might be zero if it was
11582c65ebfc7SToomas Soome     // suppressed before. At the end when we have restarted all questions, none of them is active as each
11583c65ebfc7SToomas Soome     // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11584c65ebfc7SToomas Soome     //
11585c65ebfc7SToomas Soome     // It is much cleaner and less error prone to build a list of questions and restart at the end.
11586c65ebfc7SToomas Soome 
11587*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11588*472cd20dSToomas Soome         "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME " (" PUB_S ")",
11589*472cd20dSToomas Soome         q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
11590c65ebfc7SToomas Soome     mDNS_StopQuery_internal(m, q);
11591c65ebfc7SToomas Soome     q->next = *restart;
11592c65ebfc7SToomas Soome     *restart = q;
11593c65ebfc7SToomas Soome }
11594c65ebfc7SToomas Soome 
11595c65ebfc7SToomas Soome // The caller should hold the lock
CheckSuppressUnusableQuestions(mDNS * const m)11596c65ebfc7SToomas Soome mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11597c65ebfc7SToomas Soome {
11598c65ebfc7SToomas Soome     DNSQuestion *q;
11599c65ebfc7SToomas Soome     DNSQuestion *restart = mDNSNULL;
11600c65ebfc7SToomas Soome 
11601c65ebfc7SToomas Soome     // We look through all questions including new questions. During network change events,
11602c65ebfc7SToomas Soome     // we potentially restart questions here in this function that ends up as new questions,
11603c65ebfc7SToomas Soome     // which may be suppressed at this instance. Before it is handled we get another network
11604c65ebfc7SToomas Soome     // event that changes the status e.g., address becomes available. If we did not process
11605*472cd20dSToomas Soome     // new questions, we would never change its Suppressed status.
11606c65ebfc7SToomas Soome     //
11607c65ebfc7SToomas Soome     // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11608c65ebfc7SToomas Soome     // application callback can potentially stop the current question (detected by CurrentQuestion) or
11609c65ebfc7SToomas Soome     // *any* other question which could be the next one that we may process here. RestartQuestion
11610c65ebfc7SToomas Soome     // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11611c65ebfc7SToomas Soome     // if the "next" question is stopped while the CurrentQuestion is stopped
11612c65ebfc7SToomas Soome     if (m->RestartQuestion)
11613c65ebfc7SToomas Soome         LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11614c65ebfc7SToomas Soome                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11615c65ebfc7SToomas Soome     m->RestartQuestion = m->Questions;
11616c65ebfc7SToomas Soome     while (m->RestartQuestion)
11617c65ebfc7SToomas Soome     {
11618c65ebfc7SToomas Soome         q = m->RestartQuestion;
11619c65ebfc7SToomas Soome         m->RestartQuestion = q->next;
11620c65ebfc7SToomas Soome         if (q->SuppressUnusable)
11621c65ebfc7SToomas Soome         {
11622*472cd20dSToomas Soome             const mDNSBool old = q->Suppressed;
11623*472cd20dSToomas Soome             q->Suppressed = ShouldSuppressQuery(q);
11624*472cd20dSToomas Soome             if (q->Suppressed != old)
11625c65ebfc7SToomas Soome             {
11626c65ebfc7SToomas Soome                 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11627c65ebfc7SToomas Soome                 // followed by a negative cache response. Temporarily turn off suppression so that
11628c65ebfc7SToomas Soome                 // AnswerCurrentQuestionWithResourceRecord can answer the question
11629c65ebfc7SToomas Soome                 SuppressStatusChanged(m, q, &restart);
11630c65ebfc7SToomas Soome             }
11631c65ebfc7SToomas Soome         }
11632c65ebfc7SToomas Soome     }
11633c65ebfc7SToomas Soome     while (restart)
11634c65ebfc7SToomas Soome     {
11635c65ebfc7SToomas Soome         q = restart;
11636c65ebfc7SToomas Soome         restart = restart->next;
11637c65ebfc7SToomas Soome         q->next = mDNSNULL;
11638c65ebfc7SToomas Soome         LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11639c65ebfc7SToomas Soome         mDNS_StartQuery_internal(m, q);
11640c65ebfc7SToomas Soome     }
11641c65ebfc7SToomas Soome }
11642c65ebfc7SToomas Soome 
11643*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
RestartUnicastQuestions(mDNS * const m)11644c65ebfc7SToomas Soome mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11645c65ebfc7SToomas Soome {
11646c65ebfc7SToomas Soome     DNSQuestion *q;
11647*472cd20dSToomas Soome     DNSQuestion *restartList = mDNSNULL;
11648c65ebfc7SToomas Soome 
11649c65ebfc7SToomas Soome     if (m->RestartQuestion)
11650c65ebfc7SToomas Soome         LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11651c65ebfc7SToomas Soome                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11652c65ebfc7SToomas Soome     m->RestartQuestion = m->Questions;
11653c65ebfc7SToomas Soome     while (m->RestartQuestion)
11654c65ebfc7SToomas Soome     {
11655c65ebfc7SToomas Soome         q = m->RestartQuestion;
11656c65ebfc7SToomas Soome         m->RestartQuestion = q->next;
11657c65ebfc7SToomas Soome         if (q->Restart)
11658c65ebfc7SToomas Soome         {
11659c65ebfc7SToomas Soome             if (mDNSOpaque16IsZero(q->TargetQID))
11660c65ebfc7SToomas Soome                 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11661c65ebfc7SToomas Soome 
11662*472cd20dSToomas Soome             q->Restart = mDNSfalse;
11663*472cd20dSToomas Soome             SuppressStatusChanged(m, q, &restartList);
11664c65ebfc7SToomas Soome         }
11665c65ebfc7SToomas Soome     }
11666*472cd20dSToomas Soome     while ((q = restartList) != mDNSNULL)
11667c65ebfc7SToomas Soome     {
11668*472cd20dSToomas Soome         restartList = q->next;
11669c65ebfc7SToomas Soome         q->next = mDNSNULL;
11670*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11671*472cd20dSToomas Soome             "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME " (" PUB_S ")",
11672*472cd20dSToomas Soome              q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
11673c65ebfc7SToomas Soome         mDNS_StartQuery_internal(m, q);
11674c65ebfc7SToomas Soome     }
11675c65ebfc7SToomas Soome }
11676*472cd20dSToomas Soome #endif
11677c65ebfc7SToomas Soome 
11678c65ebfc7SToomas Soome // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11679c65ebfc7SToomas Soome // DNS Question that are already set by the client before calling mDNS_StartQuery()
ValidateParameters(mDNS * const m,DNSQuestion * const question)11680c65ebfc7SToomas Soome mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11681c65ebfc7SToomas Soome {
11682c65ebfc7SToomas Soome     if (!ValidateDomainName(&question->qname))
11683c65ebfc7SToomas Soome     {
11684c65ebfc7SToomas Soome         LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11685c65ebfc7SToomas Soome         return(mStatus_Invalid);
11686c65ebfc7SToomas Soome     }
11687c65ebfc7SToomas Soome 
11688c65ebfc7SToomas Soome     // If this question is referencing a specific interface, verify it exists
11689*472cd20dSToomas Soome     if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID))
11690c65ebfc7SToomas Soome     {
11691c65ebfc7SToomas Soome         NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11692c65ebfc7SToomas Soome         if (!intf)
11693c65ebfc7SToomas Soome             LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11694*472cd20dSToomas Soome                     IIDPrintable(question->InterfaceID), question->qname.c, DNSTypeName(question->qtype));
11695c65ebfc7SToomas Soome     }
11696c65ebfc7SToomas Soome 
11697c65ebfc7SToomas Soome     return(mStatus_NoError);
11698c65ebfc7SToomas Soome }
11699c65ebfc7SToomas Soome 
11700c65ebfc7SToomas Soome // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
117013b436d06SToomas Soome // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
InitDNSConfig(mDNS * const m,DNSQuestion * const question)11702c65ebfc7SToomas Soome mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11703c65ebfc7SToomas Soome {
11704c65ebfc7SToomas Soome     // First reset all DNS Configuration
11705*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11706*472cd20dSToomas Soome     mdns_forget(&question->dnsservice);
11707*472cd20dSToomas Soome #else
11708c65ebfc7SToomas Soome     question->qDNSServer          = mDNSNULL;
11709c65ebfc7SToomas Soome     question->validDNSServers     = zeroOpaque128;
11710*472cd20dSToomas Soome     question->triedAllServersOnce = mDNSfalse;
11711*472cd20dSToomas Soome     question->noServerResponse    = mDNSfalse;
11712*472cd20dSToomas Soome #endif
11713c65ebfc7SToomas Soome     question->StopTime            = (question->TimeoutQuestion) ? question->StopTime : 0;
11714*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11715c65ebfc7SToomas Soome     mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
117163b436d06SToomas Soome     question->metrics.expiredAnswerState = (question->allowExpired != AllowExpired_None) ? ExpiredAnswer_Allowed : ExpiredAnswer_None;
11717c65ebfc7SToomas Soome #endif
11718c65ebfc7SToomas Soome 
11719c65ebfc7SToomas Soome     // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11720c65ebfc7SToomas Soome     if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion)
11721c65ebfc7SToomas Soome         return;
11722c65ebfc7SToomas Soome     // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11723c65ebfc7SToomas Soome     if (!mDNSOpaque16IsZero(question->TargetQID))
11724c65ebfc7SToomas Soome     {
11725*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11726*472cd20dSToomas Soome         mDNSu32 timeout = 30;
11727*472cd20dSToomas Soome #else
11728c65ebfc7SToomas Soome         mDNSu32 timeout = SetValidDNSServers(m, question);
11729*472cd20dSToomas Soome #endif
11730c65ebfc7SToomas Soome         // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11731c65ebfc7SToomas Soome         // So if a question is restarted when a network change occurs, the StopTime is not reset.
11732c65ebfc7SToomas Soome         // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11733c65ebfc7SToomas Soome         // it gets a full timeout value even if the original question times out earlier.
11734c65ebfc7SToomas Soome         if (question->TimeoutQuestion && !question->StopTime)
11735c65ebfc7SToomas Soome         {
11736c65ebfc7SToomas Soome             question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11737*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11738*472cd20dSToomas Soome                 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11739*472cd20dSToomas Soome                 mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11740c65ebfc7SToomas Soome         }
11741c65ebfc7SToomas Soome 
11742*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11743*472cd20dSToomas Soome         Querier_SetDNSServiceForQuestion(question);
11744*472cd20dSToomas Soome #else
11745c65ebfc7SToomas Soome         question->qDNSServer = GetServerForQuestion(m, question);
11746*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
11747*472cd20dSToomas Soome             "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME " " PUB_S " Timeout %d, DNS Server " PRI_IP_ADDR ":%d",
11748*472cd20dSToomas Soome             question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname),
11749*472cd20dSToomas Soome             DNSTypeName(question->qtype), timeout, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11750c65ebfc7SToomas Soome             mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11751*472cd20dSToomas Soome #endif
11752c65ebfc7SToomas Soome     }
11753c65ebfc7SToomas Soome     else if (question->TimeoutQuestion && !question->StopTime)
11754c65ebfc7SToomas Soome     {
11755c65ebfc7SToomas Soome         // If the question is to be timed out and its a multicast, local-only or P2P case,
11756c65ebfc7SToomas Soome         // then set it's stop time.
11757c65ebfc7SToomas Soome         mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ?
11758c65ebfc7SToomas Soome                             DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question);
11759c65ebfc7SToomas Soome         question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11760*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11761*472cd20dSToomas Soome                   "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11762*472cd20dSToomas Soome                   question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11763c65ebfc7SToomas Soome     }
11764c65ebfc7SToomas Soome     // Set StopTime here since it is a part of DNS Configuration
11765c65ebfc7SToomas Soome     if (question->StopTime)
11766c65ebfc7SToomas Soome         SetNextQueryStopTime(m, question);
11767c65ebfc7SToomas Soome     // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11768c65ebfc7SToomas Soome     // will never be transmitted on the wire.
11769c65ebfc7SToomas Soome     if (!(LocalOnlyOrP2PInterface(question->InterfaceID)))
11770c65ebfc7SToomas Soome         SetNextQueryTime(m,question);
11771c65ebfc7SToomas Soome }
11772c65ebfc7SToomas Soome 
11773c65ebfc7SToomas Soome // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11774c65ebfc7SToomas Soome // state fields of the DNS Question. These are independent of the Client layer.
InitCommonState(mDNS * const m,DNSQuestion * const question)117753b436d06SToomas Soome mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question)
11776c65ebfc7SToomas Soome {
11777c65ebfc7SToomas Soome     int i;
11778c65ebfc7SToomas Soome 
11779c65ebfc7SToomas Soome     // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11780c65ebfc7SToomas Soome     // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11781c65ebfc7SToomas Soome     // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11782c65ebfc7SToomas Soome     // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11783c65ebfc7SToomas Soome     // that to go out immediately.
11784c65ebfc7SToomas Soome     question->next              = mDNSNULL;
11785c65ebfc7SToomas Soome     // ThisQInterval should be initialized before any memory allocations occur. If malloc
11786c65ebfc7SToomas Soome     // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11787c65ebfc7SToomas Soome     // the question list to check if ThisQInterval is negative which means the question has been
11788c65ebfc7SToomas Soome     // stopped and can't be on the list. The question is already on the list and ThisQInterval
11789c65ebfc7SToomas Soome     // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11790c65ebfc7SToomas Soome     // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11791*472cd20dSToomas Soome     // turned ON which can allocate memory e.g., base64 encoding.
11792c65ebfc7SToomas Soome     question->ThisQInterval     = InitialQuestionInterval;                  // MUST be > zero for an active question
11793c65ebfc7SToomas Soome     question->qnamehash         = DomainNameHashValue(&question->qname);
117943b436d06SToomas Soome     question->DelayAnswering    = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0;
11795c65ebfc7SToomas Soome     question->LastQTime         = m->timenow;
11796c65ebfc7SToomas Soome     question->ExpectUnicastResp = 0;
11797c65ebfc7SToomas Soome     question->LastAnswerPktNum  = m->PktNum;
11798c65ebfc7SToomas Soome     question->RecentAnswerPkts  = 0;
11799c65ebfc7SToomas Soome     question->CurrentAnswers    = 0;
11800c65ebfc7SToomas Soome 
11801c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
11802c65ebfc7SToomas Soome 
11803c65ebfc7SToomas Soome // Initial browse threshold used by Finder.
11804c65ebfc7SToomas Soome #define mDNSFinderBrowseThreshold 20
11805c65ebfc7SToomas Soome 
11806c65ebfc7SToomas Soome     // Set the threshold at which we move to a passive browse state,
11807c65ebfc7SToomas Soome     // not actively sending queries.
11808c65ebfc7SToomas Soome     if (question->flags & kDNSServiceFlagsThresholdOne)
11809c65ebfc7SToomas Soome         question->BrowseThreshold   = 1;
11810c65ebfc7SToomas Soome     else if (question->flags & kDNSServiceFlagsThresholdFinder)
11811c65ebfc7SToomas Soome         question->BrowseThreshold   = mDNSFinderBrowseThreshold;
11812c65ebfc7SToomas Soome     else
11813c65ebfc7SToomas Soome         question->BrowseThreshold   = 0;
11814c65ebfc7SToomas Soome 
11815c65ebfc7SToomas Soome #else   // APPLE_OSX_mDNSResponder
11816c65ebfc7SToomas Soome    question->BrowseThreshold   = 0;
11817c65ebfc7SToomas Soome #endif  // APPLE_OSX_mDNSResponder
11818c65ebfc7SToomas Soome     question->CachedAnswerNeedsUpdate = mDNSfalse;
11819c65ebfc7SToomas Soome 
11820c65ebfc7SToomas Soome     question->LargeAnswers      = 0;
11821c65ebfc7SToomas Soome     question->UniqueAnswers     = 0;
11822c65ebfc7SToomas Soome     question->LOAddressAnswers  = 0;
11823c65ebfc7SToomas Soome     question->FlappingInterface1 = mDNSNULL;
11824c65ebfc7SToomas Soome     question->FlappingInterface2 = mDNSNULL;
11825c65ebfc7SToomas Soome 
11826*472cd20dSToomas Soome     // mDNSPlatformGetDNSRoutePolicy() and InitDNSConfig() may set a DNSQuestion's BlockedByPolicy value,
11827*472cd20dSToomas Soome     // so they should be called before calling ShouldSuppressQuery(), which checks BlockedByPolicy.
11828*472cd20dSToomas Soome     question->BlockedByPolicy = mDNSfalse;
11829*472cd20dSToomas Soome 
11830c65ebfc7SToomas Soome     // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11831c65ebfc7SToomas Soome     // since we would already have the question->ServiceID in that case.
11832c65ebfc7SToomas Soome     if (!(question->flags & kDNSServiceFlagsServiceIndex))
11833c65ebfc7SToomas Soome     {
11834c65ebfc7SToomas Soome         question->ServiceID = -1;
11835*472cd20dSToomas Soome #if APPLE_OSX_mDNSResponder
11836*472cd20dSToomas Soome         if (!(question->flags & kDNSServiceFlagsPathEvaluationDone) || question->ForcePathEval)
11837*472cd20dSToomas Soome         {
11838*472cd20dSToomas Soome             if (question->flags & kDNSServiceFlagsPathEvaluationDone)
11839*472cd20dSToomas Soome             {
11840*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11841*472cd20dSToomas Soome                     "[R%u->Q%u] Forcing another path evaluation", question->request_id, mDNSVal16(question->TargetQID));
11842*472cd20dSToomas Soome             }
11843*472cd20dSToomas Soome             question->ForcePathEval = mDNSfalse;
11844*472cd20dSToomas Soome             mDNSPlatformGetDNSRoutePolicy(question);
11845*472cd20dSToomas Soome         }
11846c65ebfc7SToomas Soome #endif
11847c65ebfc7SToomas Soome     }
11848c65ebfc7SToomas Soome     else
11849c65ebfc7SToomas Soome         LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11850c65ebfc7SToomas Soome                 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11851c65ebfc7SToomas Soome 
11852c65ebfc7SToomas Soome     InitDNSConfig(m, question);
11853c65ebfc7SToomas Soome     question->AuthInfo          = GetAuthInfoForQuestion(m, question);
11854*472cd20dSToomas Soome     question->Suppressed        = ShouldSuppressQuery(question);
11855c65ebfc7SToomas Soome     question->NextInDQList      = mDNSNULL;
11856c65ebfc7SToomas Soome     question->SendQNow          = mDNSNULL;
11857c65ebfc7SToomas Soome     question->SendOnAll         = mDNSfalse;
11858c65ebfc7SToomas Soome     question->RequestUnicast    = kDefaultRequestUnicastCount;
11859c65ebfc7SToomas Soome 
11860c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
11861c65ebfc7SToomas Soome     // Set the QU bit in the first query for the following options.
11862c65ebfc7SToomas Soome     if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder))
11863c65ebfc7SToomas Soome     {
11864c65ebfc7SToomas Soome         question->RequestUnicast    = SET_QU_IN_FIRST_QUERY;
11865c65ebfc7SToomas Soome         LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11866c65ebfc7SToomas Soome             DNSTypeName(question->qtype));
11867c65ebfc7SToomas Soome     }
11868c65ebfc7SToomas Soome #endif  // APPLE_OSX_mDNSResponder
11869c65ebfc7SToomas Soome 
11870c65ebfc7SToomas Soome     question->LastQTxTime       = m->timenow;
11871c65ebfc7SToomas Soome     question->CNAMEReferrals    = 0;
11872c65ebfc7SToomas Soome 
11873c65ebfc7SToomas Soome     question->WakeOnResolveCount = 0;
11874c65ebfc7SToomas Soome     if (question->WakeOnResolve)
11875c65ebfc7SToomas Soome     {
11876c65ebfc7SToomas Soome         question->WakeOnResolveCount = InitialWakeOnResolveCount;
11877c65ebfc7SToomas Soome     }
11878c65ebfc7SToomas Soome 
11879c65ebfc7SToomas Soome     for (i=0; i<DupSuppressInfoSize; i++)
11880c65ebfc7SToomas Soome         question->DupSuppress[i].InterfaceID = mDNSNULL;
11881c65ebfc7SToomas Soome 
11882*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11883*472cd20dSToomas Soome     question->Restart = mDNSfalse;
11884*472cd20dSToomas Soome #endif
11885c65ebfc7SToomas Soome 
11886c65ebfc7SToomas Soome     debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11887c65ebfc7SToomas Soome             question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11888c65ebfc7SToomas Soome             NextQSendTime(question) - m->timenow,
11889c65ebfc7SToomas Soome             question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11890c65ebfc7SToomas Soome             question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11891c65ebfc7SToomas Soome 
11892c65ebfc7SToomas Soome     if (question->DelayAnswering)
11893c65ebfc7SToomas Soome         LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11894c65ebfc7SToomas Soome                  question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11895c65ebfc7SToomas Soome }
11896c65ebfc7SToomas Soome 
11897c65ebfc7SToomas Soome // Excludes the DNS Config fields which are already handled by InitDNSConfig()
InitWABState(DNSQuestion * const question)11898c65ebfc7SToomas Soome mDNSlocal void InitWABState(DNSQuestion *const question)
11899c65ebfc7SToomas Soome {
11900c65ebfc7SToomas Soome     // We'll create our question->LocalSocket on demand, if needed.
11901c65ebfc7SToomas Soome     // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11902c65ebfc7SToomas Soome     // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11903c65ebfc7SToomas Soome     // NAT mapping for receiving inbound add/remove events.
11904c65ebfc7SToomas Soome     question->LocalSocket       = mDNSNULL;
11905*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11906*472cd20dSToomas Soome     mdns_querier_forget(&question->querier);
11907*472cd20dSToomas Soome #else
11908c65ebfc7SToomas Soome     question->unansweredQueries = 0;
11909*472cd20dSToomas Soome #endif
11910c65ebfc7SToomas Soome     question->nta               = mDNSNULL;
11911c65ebfc7SToomas Soome     question->servAddr          = zeroAddr;
11912c65ebfc7SToomas Soome     question->servPort          = zeroIPPort;
11913c65ebfc7SToomas Soome     question->tcp               = mDNSNULL;
11914c65ebfc7SToomas Soome     question->NoAnswer          = NoAnswer_Normal;
11915c65ebfc7SToomas Soome }
11916c65ebfc7SToomas Soome 
InitLLQNATState(mDNS * const m)11917c65ebfc7SToomas Soome mDNSlocal void InitLLQNATState(mDNS *const m)
11918c65ebfc7SToomas Soome {
11919c65ebfc7SToomas Soome     // If we don't have our NAT mapping active, start it now
11920c65ebfc7SToomas Soome     if (!m->LLQNAT.clientCallback)
11921c65ebfc7SToomas Soome     {
11922c65ebfc7SToomas Soome         m->LLQNAT.Protocol       = NATOp_MapUDP;
11923c65ebfc7SToomas Soome         m->LLQNAT.IntPort        = m->UnicastPort4;
11924c65ebfc7SToomas Soome         m->LLQNAT.RequestedPort  = m->UnicastPort4;
11925c65ebfc7SToomas Soome         m->LLQNAT.clientCallback = LLQNATCallback;
11926c65ebfc7SToomas Soome         m->LLQNAT.clientContext  = (void*)1; // Means LLQ NAT Traversal just started
11927c65ebfc7SToomas Soome         mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11928c65ebfc7SToomas Soome     }
11929c65ebfc7SToomas Soome }
11930c65ebfc7SToomas Soome 
InitLLQState(DNSQuestion * const question)11931c65ebfc7SToomas Soome mDNSlocal void InitLLQState(DNSQuestion *const question)
11932c65ebfc7SToomas Soome {
11933*472cd20dSToomas Soome     question->state             = LLQ_Init;
11934c65ebfc7SToomas Soome     question->ReqLease          = 0;
11935c65ebfc7SToomas Soome     question->expire            = 0;
11936c65ebfc7SToomas Soome     question->ntries            = 0;
11937c65ebfc7SToomas Soome     question->id                = zeroOpaque64;
11938c65ebfc7SToomas Soome }
11939c65ebfc7SToomas Soome 
11940c65ebfc7SToomas Soome // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11941c65ebfc7SToomas Soome // DNSSEC & DNS Proxy fields of the DNS Question.
InitDNSSECProxyState(mDNS * const m,DNSQuestion * const question)11942c65ebfc7SToomas Soome mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11943c65ebfc7SToomas Soome {
11944c65ebfc7SToomas Soome     (void) m;
11945c65ebfc7SToomas Soome     question->responseFlags = zeroID;
11946c65ebfc7SToomas Soome }
11947c65ebfc7SToomas Soome 
11948c65ebfc7SToomas Soome // Once the question is completely initialized including the duplicate logic, this function
11949c65ebfc7SToomas Soome // is called to finalize the unicast question which requires flushing the cache if needed,
11950c65ebfc7SToomas Soome // activating the query etc.
FinalizeUnicastQuestion(mDNS * const m,DNSQuestion * question)119513b436d06SToomas Soome mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question)
11952c65ebfc7SToomas Soome {
11953c65ebfc7SToomas Soome     // Ensure DNS related info of duplicate question is same as the orig question
11954c65ebfc7SToomas Soome     if (question->DuplicateOf)
11955c65ebfc7SToomas Soome     {
11956*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11957*472cd20dSToomas Soome         const DNSQuestion *const duplicateOf = question->DuplicateOf;
11958*472cd20dSToomas Soome         mdns_replace(&question->dnsservice, duplicateOf->dnsservice);
11959*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11960*472cd20dSToomas Soome            "[R%u->DupQ%u->Q%u] Duplicate question " PRI_DM_NAME " (" PUB_S ")",
11961*472cd20dSToomas Soome            question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(duplicateOf->TargetQID),
11962*472cd20dSToomas Soome            DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11963*472cd20dSToomas Soome #else
11964c65ebfc7SToomas Soome         question->validDNSServers = question->DuplicateOf->validDNSServers;
11965c65ebfc7SToomas Soome         // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11966c65ebfc7SToomas Soome         // then we log a line as it could indicate an issue
11967c65ebfc7SToomas Soome         if (question->DuplicateOf->qDNSServer == mDNSNULL)
11968c65ebfc7SToomas Soome         {
11969c65ebfc7SToomas Soome             if (question->qDNSServer)
11970*472cd20dSToomas Soome             {
11971*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11972*472cd20dSToomas Soome                        "[R%d->Q%d] FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(" PRI_IP_ADDR ":%d) but original question(%p) has no DNS Server! " PRI_DM_NAME " (" PUB_S ")",
11973*472cd20dSToomas Soome                        question->request_id, mDNSVal16(question->TargetQID), question,
11974*472cd20dSToomas Soome                        question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11975*472cd20dSToomas Soome                        mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort), question->DuplicateOf,
11976*472cd20dSToomas Soome                        DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11977*472cd20dSToomas Soome             }
11978c65ebfc7SToomas Soome         }
11979c65ebfc7SToomas Soome         question->qDNSServer = question->DuplicateOf->qDNSServer;
11980*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11981*472cd20dSToomas Soome                "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME " (" PUB_S "), DNS Server " PRI_IP_ADDR ":%d",
11982*472cd20dSToomas Soome                question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID),
11983*472cd20dSToomas Soome                question, question->DuplicateOf, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype),
11984c65ebfc7SToomas Soome                question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11985c65ebfc7SToomas Soome                mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11986*472cd20dSToomas Soome #endif
11987c65ebfc7SToomas Soome     }
11988c65ebfc7SToomas Soome 
11989c65ebfc7SToomas Soome     ActivateUnicastQuery(m, question, mDNSfalse);
11990c65ebfc7SToomas Soome 
11991c65ebfc7SToomas Soome     if (question->LongLived)
11992c65ebfc7SToomas Soome     {
11993c65ebfc7SToomas Soome         // Unlike other initializations, InitLLQNATState should be done after
11994c65ebfc7SToomas Soome         // we determine that it is a unicast question.  LongLived is set for
11995c65ebfc7SToomas Soome         // both multicast and unicast browse questions but we should initialize
11996c65ebfc7SToomas Soome         // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11997c65ebfc7SToomas Soome         // start the NAT traversal that is not needed.
11998c65ebfc7SToomas Soome         InitLLQNATState(m);
11999c65ebfc7SToomas Soome     }
12000c65ebfc7SToomas Soome }
12001c65ebfc7SToomas Soome 
mDNS_StartQuery_internal(mDNS * const m,DNSQuestion * const question)12002c65ebfc7SToomas Soome mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
12003c65ebfc7SToomas Soome {
12004c65ebfc7SToomas Soome     DNSQuestion **q;
12005c65ebfc7SToomas Soome     mStatus vStatus;
12006c65ebfc7SToomas Soome 
12007c65ebfc7SToomas Soome     // First check for cache space (can't do queries if there is no cache space allocated)
12008c65ebfc7SToomas Soome     if (m->rrcache_size == 0)
12009c65ebfc7SToomas Soome         return(mStatus_NoCache);
12010c65ebfc7SToomas Soome 
12011c65ebfc7SToomas Soome     vStatus = ValidateParameters(m, question);
12012c65ebfc7SToomas Soome     if (vStatus)
12013c65ebfc7SToomas Soome         return(vStatus);
12014c65ebfc7SToomas Soome 
12015c65ebfc7SToomas Soome #ifdef USE_LIBIDN
12016c65ebfc7SToomas Soome     // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12017c65ebfc7SToomas Soome     // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12018*472cd20dSToomas Soome     // This applies to the top label (TLD) only
12019*472cd20dSToomas Soome     // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12020c65ebfc7SToomas Soome     if (IsHighASCIILabel(LastLabel(&question->qname)))
12021c65ebfc7SToomas Soome     {
12022c65ebfc7SToomas Soome         domainname newname;
12023c65ebfc7SToomas Soome         if (PerformNextPunycodeConversion(question, &newname))
12024c65ebfc7SToomas Soome             AssignDomainName(&question->qname, &newname);
12025c65ebfc7SToomas Soome     }
12026c65ebfc7SToomas Soome #endif // USE_LIBIDN
12027c65ebfc7SToomas Soome 
12028c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
12029*472cd20dSToomas Soome     question->TargetQID = Question_uDNS(question) ? mDNS_NewMessageID(m) : zeroID;
12030*472cd20dSToomas Soome #else
12031*472cd20dSToomas Soome     question->TargetQID = zeroID;
12032*472cd20dSToomas Soome #endif
12033c65ebfc7SToomas Soome     debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12034c65ebfc7SToomas Soome 
12035c65ebfc7SToomas Soome     // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12036c65ebfc7SToomas Soome     q = &m->Questions;
12037c65ebfc7SToomas Soome     if (LocalOnlyOrP2PInterface(question->InterfaceID))
12038c65ebfc7SToomas Soome         q = &m->LocalOnlyQuestions;
12039c65ebfc7SToomas Soome     while (*q && *q != question)
12040c65ebfc7SToomas Soome         q=&(*q)->next;
12041c65ebfc7SToomas Soome 
12042c65ebfc7SToomas Soome     if (*q)
12043c65ebfc7SToomas Soome     {
12044c65ebfc7SToomas Soome         LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12045c65ebfc7SToomas Soome                 question->qname.c, DNSTypeName(question->qtype), question);
12046c65ebfc7SToomas Soome         return(mStatus_AlreadyRegistered);
12047c65ebfc7SToomas Soome     }
12048c65ebfc7SToomas Soome     *q = question;
12049c65ebfc7SToomas Soome 
12050c65ebfc7SToomas Soome     // Intialize the question. The only ordering constraint we have today is that
12051c65ebfc7SToomas Soome     // InitDNSSECProxyState should be called after the DNS server is selected (in
12052c65ebfc7SToomas Soome     // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12053c65ebfc7SToomas Soome     // validation.
12054c65ebfc7SToomas Soome 
120553b436d06SToomas Soome     InitCommonState(m, question);
12056c65ebfc7SToomas Soome     InitWABState(question);
12057c65ebfc7SToomas Soome     InitLLQState(question);
12058c65ebfc7SToomas Soome     InitDNSSECProxyState(m, question);
12059c65ebfc7SToomas Soome 
12060c65ebfc7SToomas Soome     // FindDuplicateQuestion should be called last after all the intialization
12061c65ebfc7SToomas Soome     // as the duplicate logic could be potentially based on any field in the
12062c65ebfc7SToomas Soome     // question.
12063c65ebfc7SToomas Soome     question->DuplicateOf  = FindDuplicateQuestion(m, question);
12064c65ebfc7SToomas Soome     if (question->DuplicateOf)
12065c65ebfc7SToomas Soome         question->AuthInfo = question->DuplicateOf->AuthInfo;
12066c65ebfc7SToomas Soome 
12067c65ebfc7SToomas Soome     if (LocalOnlyOrP2PInterface(question->InterfaceID))
12068c65ebfc7SToomas Soome     {
12069c65ebfc7SToomas Soome         if (!m->NewLocalOnlyQuestions)
12070c65ebfc7SToomas Soome             m->NewLocalOnlyQuestions = question;
12071c65ebfc7SToomas Soome     }
12072c65ebfc7SToomas Soome     else
12073c65ebfc7SToomas Soome     {
12074c65ebfc7SToomas Soome         if (!m->NewQuestions)
12075c65ebfc7SToomas Soome             m->NewQuestions = question;
12076c65ebfc7SToomas Soome 
12077c65ebfc7SToomas Soome         // If the question's id is non-zero, then it's Wide Area
12078c65ebfc7SToomas Soome         // MUST NOT do this Wide Area setup until near the end of
12079c65ebfc7SToomas Soome         // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12080c65ebfc7SToomas Soome         // NS, etc.) and if we haven't finished setting up our own question and setting
12081c65ebfc7SToomas Soome         // m->NewQuestions if necessary then we could end up recursively re-entering
12082c65ebfc7SToomas Soome         // this routine with the question list data structures in an inconsistent state.
12083c65ebfc7SToomas Soome         if (!mDNSOpaque16IsZero(question->TargetQID))
12084c65ebfc7SToomas Soome         {
120853b436d06SToomas Soome             FinalizeUnicastQuestion(m, question);
12086c65ebfc7SToomas Soome         }
12087c65ebfc7SToomas Soome         else
12088c65ebfc7SToomas Soome         {
12089*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12090c65ebfc7SToomas Soome             m->NumAllInterfaceQuestions++;
12091*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12092*472cd20dSToomas Soome                 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12093*472cd20dSToomas Soome                 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12094c65ebfc7SToomas Soome             if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12095c65ebfc7SToomas Soome             {
12096c65ebfc7SToomas Soome                 m->NextBonjourDisableTime = 0;
12097c65ebfc7SToomas Soome                 if (m->BonjourEnabled == 0)
12098c65ebfc7SToomas Soome                 {
12099c65ebfc7SToomas Soome                     // Enable Bonjour immediately by scheduling network changed processing where
12100c65ebfc7SToomas Soome                     // we will join the multicast group on each active interface.
12101c65ebfc7SToomas Soome                     m->BonjourEnabled = 1;
12102c65ebfc7SToomas Soome                     m->NetworkChanged = m->timenow;
12103c65ebfc7SToomas Soome                 }
12104c65ebfc7SToomas Soome             }
12105*472cd20dSToomas Soome #endif
121063b436d06SToomas Soome             if (question->WakeOnResolve)
12107c65ebfc7SToomas Soome             {
12108c65ebfc7SToomas Soome                 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
121093b436d06SToomas Soome                 mDNS_PurgeBeforeResolve(m, question);
12110c65ebfc7SToomas Soome             }
12111c65ebfc7SToomas Soome         }
12112c65ebfc7SToomas Soome     }
12113c65ebfc7SToomas Soome 
12114c65ebfc7SToomas Soome     return(mStatus_NoError);
12115c65ebfc7SToomas Soome }
12116c65ebfc7SToomas Soome 
12117c65ebfc7SToomas Soome // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
CancelGetZoneData(mDNS * const m,ZoneData * nta)12118c65ebfc7SToomas Soome mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
12119c65ebfc7SToomas Soome {
12120c65ebfc7SToomas Soome     debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
12121c65ebfc7SToomas Soome     // This function may be called anytime to free the zone information.The question may or may not have stopped.
12122c65ebfc7SToomas Soome     // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12123c65ebfc7SToomas Soome     // call it again
12124c65ebfc7SToomas Soome     if (nta->question.ThisQInterval != -1)
12125c65ebfc7SToomas Soome     {
12126c65ebfc7SToomas Soome         mDNS_StopQuery_internal(m, &nta->question);
12127c65ebfc7SToomas Soome         if (nta->question.ThisQInterval != -1)
12128c65ebfc7SToomas Soome             LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
12129c65ebfc7SToomas Soome     }
12130c65ebfc7SToomas Soome     mDNSPlatformMemFree(nta);
12131c65ebfc7SToomas Soome }
12132c65ebfc7SToomas Soome 
mDNS_StopQuery_internal(mDNS * const m,DNSQuestion * const question)12133c65ebfc7SToomas Soome mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
12134c65ebfc7SToomas Soome {
12135c65ebfc7SToomas Soome     CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12136*472cd20dSToomas Soome     CacheRecord *cr;
12137c65ebfc7SToomas Soome     DNSQuestion **qp = &m->Questions;
12138c65ebfc7SToomas Soome 
12139c65ebfc7SToomas Soome     //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12140c65ebfc7SToomas Soome 
12141c65ebfc7SToomas Soome     if (LocalOnlyOrP2PInterface(question->InterfaceID))
12142c65ebfc7SToomas Soome         qp = &m->LocalOnlyQuestions;
12143c65ebfc7SToomas Soome     while (*qp && *qp != question) qp=&(*qp)->next;
12144c65ebfc7SToomas Soome     if (*qp) *qp = (*qp)->next;
12145c65ebfc7SToomas Soome     else
12146c65ebfc7SToomas Soome     {
12147c65ebfc7SToomas Soome #if !ForceAlerts
12148c65ebfc7SToomas Soome         if (question->ThisQInterval >= 0)   // Only log error message if the query was supposed to be active
12149c65ebfc7SToomas Soome #endif
12150c65ebfc7SToomas Soome         LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
12151c65ebfc7SToomas Soome         return(mStatus_BadReferenceErr);
12152c65ebfc7SToomas Soome     }
12153c65ebfc7SToomas Soome 
12154*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12155c65ebfc7SToomas Soome     if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID))
12156c65ebfc7SToomas Soome     {
12157c65ebfc7SToomas Soome         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12158c65ebfc7SToomas Soome             m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
12159c65ebfc7SToomas Soome         m->NumAllInterfaceQuestions--;
12160*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12161*472cd20dSToomas Soome             "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12162*472cd20dSToomas Soome             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12163c65ebfc7SToomas Soome     }
12164*472cd20dSToomas Soome #endif
12165c65ebfc7SToomas Soome 
12166*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12167*472cd20dSToomas Soome     if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.firstQueryTime != 0))
12168*472cd20dSToomas Soome     {
12169*472cd20dSToomas Soome         mDNSu32 querySendCount = question->metrics.querySendCount;
12170*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12171*472cd20dSToomas Soome         if (question->querier)
12172*472cd20dSToomas Soome         {
12173*472cd20dSToomas Soome             querySendCount += mdns_querier_get_send_count(question->querier);
12174*472cd20dSToomas Soome         }
12175*472cd20dSToomas Soome #endif
12176*472cd20dSToomas Soome         if (querySendCount > 0)
12177c65ebfc7SToomas Soome         {
12178c65ebfc7SToomas Soome             const domainname *  queryName;
12179c65ebfc7SToomas Soome             mDNSBool            isForCell;
12180c65ebfc7SToomas Soome             mDNSu32             durationMs;
12181c65ebfc7SToomas Soome 
12182c65ebfc7SToomas Soome             queryName  = question->metrics.originalQName ? question->metrics.originalQName : &question->qname;
12183*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12184*472cd20dSToomas Soome             isForCell = (question->dnsservice && mdns_dns_service_interface_is_cellular(question->dnsservice));
12185*472cd20dSToomas Soome #else
12186*472cd20dSToomas Soome             isForCell  = (question->qDNSServer && question->qDNSServer->isCell);
12187*472cd20dSToomas Soome #endif
12188c65ebfc7SToomas Soome             durationMs = ((m->timenow - question->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
12189*472cd20dSToomas Soome             MetricsUpdateDNSQueryStats(queryName, question->qtype, mDNSNULL, querySendCount,
12190*472cd20dSToomas Soome                 question->metrics.expiredAnswerState, question->metrics.dnsOverTCPState, durationMs, isForCell);
12191*472cd20dSToomas Soome         }
12192c65ebfc7SToomas Soome     }
12193c65ebfc7SToomas Soome #endif
12194c65ebfc7SToomas Soome     // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12195c65ebfc7SToomas Soome     UpdateQuestionDuplicates(m, question);
12196c65ebfc7SToomas Soome     // But don't trash ThisQInterval until afterwards.
12197c65ebfc7SToomas Soome     question->ThisQInterval = -1;
12198c65ebfc7SToomas Soome 
12199c65ebfc7SToomas Soome     // If there are any cache records referencing this as their active question, then see if there is any
12200c65ebfc7SToomas Soome     // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12201*472cd20dSToomas Soome     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12202c65ebfc7SToomas Soome     {
12203*472cd20dSToomas Soome         if (cr->CRActiveQuestion == question)
12204c65ebfc7SToomas Soome         {
12205c65ebfc7SToomas Soome             DNSQuestion *q;
12206c65ebfc7SToomas Soome             DNSQuestion *replacement = mDNSNULL;
12207c65ebfc7SToomas Soome             // If we find an active question that is answered by this cached record, use it as the cache record's
12208c65ebfc7SToomas Soome             // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12209c65ebfc7SToomas Soome             // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12210c65ebfc7SToomas Soome             // via CacheRecordRmv() when the cache record expires.
12211c65ebfc7SToomas Soome             for (q = m->Questions; q && (q != m->NewQuestions); q = q->next)
12212c65ebfc7SToomas Soome             {
12213*472cd20dSToomas Soome                 if (!q->DuplicateOf && !q->Suppressed && CacheRecordAnswersQuestion(cr, q))
12214c65ebfc7SToomas Soome                 {
12215c65ebfc7SToomas Soome                     if (q->ThisQInterval > 0)
12216c65ebfc7SToomas Soome                     {
12217c65ebfc7SToomas Soome                         replacement = q;
12218c65ebfc7SToomas Soome                         break;
12219c65ebfc7SToomas Soome                     }
12220c65ebfc7SToomas Soome                     else if (!replacement)
12221c65ebfc7SToomas Soome                     {
12222c65ebfc7SToomas Soome                         replacement = q;
12223c65ebfc7SToomas Soome                     }
12224c65ebfc7SToomas Soome                 }
12225c65ebfc7SToomas Soome             }
12226c65ebfc7SToomas Soome             if (replacement)
12227c65ebfc7SToomas Soome                 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12228*472cd20dSToomas Soome                        "CurrentAnswers %d, Suppressed %d", replacement, CRDisplayString(m,cr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->Suppressed);
12229*472cd20dSToomas Soome             cr->CRActiveQuestion = replacement;    // Question used to be active; new value may or may not be null
12230c65ebfc7SToomas Soome             if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count
12231c65ebfc7SToomas Soome         }
12232c65ebfc7SToomas Soome     }
12233c65ebfc7SToomas Soome 
12234c65ebfc7SToomas Soome     // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12235c65ebfc7SToomas Soome     // bump its pointer forward one question.
12236c65ebfc7SToomas Soome     if (m->CurrentQuestion == question)
12237c65ebfc7SToomas Soome     {
12238c65ebfc7SToomas Soome         debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12239c65ebfc7SToomas Soome                question->qname.c, DNSTypeName(question->qtype));
12240c65ebfc7SToomas Soome         m->CurrentQuestion = question->next;
12241c65ebfc7SToomas Soome     }
12242c65ebfc7SToomas Soome 
12243c65ebfc7SToomas Soome     if (m->NewQuestions == question)
12244c65ebfc7SToomas Soome     {
12245c65ebfc7SToomas Soome         debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12246c65ebfc7SToomas Soome                question->qname.c, DNSTypeName(question->qtype));
12247c65ebfc7SToomas Soome         m->NewQuestions = question->next;
12248c65ebfc7SToomas Soome     }
12249c65ebfc7SToomas Soome 
12250c65ebfc7SToomas Soome     if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
12251c65ebfc7SToomas Soome 
12252c65ebfc7SToomas Soome     if (m->RestartQuestion == question)
12253c65ebfc7SToomas Soome     {
12254c65ebfc7SToomas Soome         LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12255c65ebfc7SToomas Soome                question->qname.c, DNSTypeName(question->qtype));
12256c65ebfc7SToomas Soome         m->RestartQuestion = question->next;
12257c65ebfc7SToomas Soome     }
12258c65ebfc7SToomas Soome 
12259c65ebfc7SToomas Soome     // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12260c65ebfc7SToomas Soome     question->next = mDNSNULL;
12261c65ebfc7SToomas Soome 
12262c65ebfc7SToomas Soome     // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12263c65ebfc7SToomas Soome 
12264c65ebfc7SToomas Soome     // And finally, cancel any associated GetZoneData operation that's still running.
12265c65ebfc7SToomas Soome     // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12266c65ebfc7SToomas Soome     // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12267c65ebfc7SToomas Soome     // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12268c65ebfc7SToomas Soome     // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12269c65ebfc7SToomas Soome     if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
12270c65ebfc7SToomas Soome     if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
12271*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12272*472cd20dSToomas Soome     Querier_HandleStoppedDNSQuestion(question);
12273*472cd20dSToomas Soome #endif
12274c65ebfc7SToomas Soome     if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
12275c65ebfc7SToomas Soome     {
12276c65ebfc7SToomas Soome         // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12277c65ebfc7SToomas Soome         DNSQuestion *q;
12278c65ebfc7SToomas Soome         for (q = m->Questions; q; q=q->next)
12279c65ebfc7SToomas Soome             if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
12280c65ebfc7SToomas Soome         if (!q)
12281c65ebfc7SToomas Soome         {
12282c65ebfc7SToomas Soome             if (!m->LLQNAT.clientCallback)       // Should never happen, but just in case...
12283c65ebfc7SToomas Soome             {
12284c65ebfc7SToomas Soome                 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12285c65ebfc7SToomas Soome             }
12286c65ebfc7SToomas Soome             else
12287c65ebfc7SToomas Soome             {
12288c65ebfc7SToomas Soome                 LogInfo("Stopping LLQNAT");
12289c65ebfc7SToomas Soome                 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
12290c65ebfc7SToomas Soome                 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
12291c65ebfc7SToomas Soome             }
12292c65ebfc7SToomas Soome         }
12293c65ebfc7SToomas Soome 
12294c65ebfc7SToomas Soome         // If necessary, tell server it can delete this LLQ state
12295c65ebfc7SToomas Soome         if (question->state == LLQ_Established)
12296c65ebfc7SToomas Soome         {
12297c65ebfc7SToomas Soome             question->ReqLease = 0;
12298c65ebfc7SToomas Soome             sendLLQRefresh(m, question);
12299c65ebfc7SToomas Soome             // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12300c65ebfc7SToomas Soome             // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12301c65ebfc7SToomas Soome             // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12302c65ebfc7SToomas Soome             // we let that run out its natural course and complete asynchronously.
12303c65ebfc7SToomas Soome             if (question->tcp)
12304c65ebfc7SToomas Soome             {
12305c65ebfc7SToomas Soome                 question->tcp->question = mDNSNULL;
12306c65ebfc7SToomas Soome                 question->tcp           = mDNSNULL;
12307c65ebfc7SToomas Soome             }
12308c65ebfc7SToomas Soome         }
12309*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12310*472cd20dSToomas Soome         else if (question->dnsPushServer != mDNSNULL)
12311c65ebfc7SToomas Soome         {
12312*472cd20dSToomas Soome             UnSubscribeToDNSPushNotificationServer(m, question);
12313c65ebfc7SToomas Soome         }
12314c65ebfc7SToomas Soome #endif
12315c65ebfc7SToomas Soome     }
12316c65ebfc7SToomas Soome     // wait until we send the refresh above which needs the nta
12317c65ebfc7SToomas Soome     if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
12318c65ebfc7SToomas Soome 
12319*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12320*472cd20dSToomas Soome     uDNSMetricsClear(&question->metrics);
12321c65ebfc7SToomas Soome #endif
12322c65ebfc7SToomas Soome 
12323*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12324c65ebfc7SToomas Soome     DNS64ResetState(question);
12325c65ebfc7SToomas Soome #endif
12326c65ebfc7SToomas Soome 
12327c65ebfc7SToomas Soome     return(mStatus_NoError);
12328c65ebfc7SToomas Soome }
12329c65ebfc7SToomas Soome 
mDNS_StartQuery(mDNS * const m,DNSQuestion * const question)12330c65ebfc7SToomas Soome mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
12331c65ebfc7SToomas Soome {
12332c65ebfc7SToomas Soome     mStatus status;
12333c65ebfc7SToomas Soome     mDNS_Lock(m);
12334c65ebfc7SToomas Soome     status = mDNS_StartQuery_internal(m, question);
12335c65ebfc7SToomas Soome     mDNS_Unlock(m);
12336c65ebfc7SToomas Soome     return(status);
12337c65ebfc7SToomas Soome }
12338c65ebfc7SToomas Soome 
mDNS_StopQuery(mDNS * const m,DNSQuestion * const question)12339c65ebfc7SToomas Soome mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
12340c65ebfc7SToomas Soome {
12341c65ebfc7SToomas Soome     mStatus status;
12342c65ebfc7SToomas Soome     mDNS_Lock(m);
12343c65ebfc7SToomas Soome     status = mDNS_StopQuery_internal(m, question);
12344c65ebfc7SToomas Soome     mDNS_Unlock(m);
12345c65ebfc7SToomas Soome     return(status);
12346c65ebfc7SToomas Soome }
12347c65ebfc7SToomas Soome 
12348c65ebfc7SToomas Soome // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12349c65ebfc7SToomas Soome // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12350c65ebfc7SToomas Soome // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12351c65ebfc7SToomas Soome // specifically to catch and report if the client callback does try to make API calls
mDNS_StopQueryWithRemoves(mDNS * const m,DNSQuestion * const question)12352c65ebfc7SToomas Soome mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12353c65ebfc7SToomas Soome {
12354c65ebfc7SToomas Soome     mStatus status;
12355c65ebfc7SToomas Soome     DNSQuestion *qq;
12356c65ebfc7SToomas Soome     mDNS_Lock(m);
12357c65ebfc7SToomas Soome 
12358c65ebfc7SToomas Soome     // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12359c65ebfc7SToomas Soome     for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12360c65ebfc7SToomas Soome 
12361c65ebfc7SToomas Soome     status = mDNS_StopQuery_internal(m, question);
12362c65ebfc7SToomas Soome     if (status == mStatus_NoError && !qq)
12363c65ebfc7SToomas Soome     {
12364*472cd20dSToomas Soome         const CacheRecord *cr;
12365c65ebfc7SToomas Soome         CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12366c65ebfc7SToomas Soome         LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12367*472cd20dSToomas Soome         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12368*472cd20dSToomas Soome         {
12369*472cd20dSToomas Soome             if (cr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameCacheRecordAnswersQuestion(cr, question))
12370c65ebfc7SToomas Soome             {
12371c65ebfc7SToomas Soome                 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12372c65ebfc7SToomas Soome                 if (question->QuestionCallback)
12373*472cd20dSToomas Soome                     question->QuestionCallback(m, question, &cr->resrec, QC_rmv);
12374*472cd20dSToomas Soome             }
12375c65ebfc7SToomas Soome         }
12376c65ebfc7SToomas Soome     }
12377c65ebfc7SToomas Soome     mDNS_Unlock(m);
12378c65ebfc7SToomas Soome     return(status);
12379c65ebfc7SToomas Soome }
12380c65ebfc7SToomas Soome 
mDNS_Reconfirm(mDNS * const m,CacheRecord * const cr)12381c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12382c65ebfc7SToomas Soome {
12383c65ebfc7SToomas Soome     mStatus status;
12384c65ebfc7SToomas Soome     mDNS_Lock(m);
12385c65ebfc7SToomas Soome     status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
123863b436d06SToomas Soome     if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12387c65ebfc7SToomas Soome     mDNS_Unlock(m);
12388c65ebfc7SToomas Soome     return(status);
12389c65ebfc7SToomas Soome }
12390c65ebfc7SToomas Soome 
mDNS_ReconfirmByValue(mDNS * const m,ResourceRecord * const rr)12391c65ebfc7SToomas Soome mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12392c65ebfc7SToomas Soome {
12393c65ebfc7SToomas Soome     mStatus status = mStatus_BadReferenceErr;
12394c65ebfc7SToomas Soome     CacheRecord *cr;
12395c65ebfc7SToomas Soome     mDNS_Lock(m);
12396c65ebfc7SToomas Soome     cr = FindIdenticalRecordInCache(m, rr);
12397c65ebfc7SToomas Soome     debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12398c65ebfc7SToomas Soome     if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
123993b436d06SToomas Soome     if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12400c65ebfc7SToomas Soome     mDNS_Unlock(m);
12401c65ebfc7SToomas Soome     return(status);
12402c65ebfc7SToomas Soome }
12403c65ebfc7SToomas Soome 
mDNS_StartBrowse_internal(mDNS * const m,DNSQuestion * const question,const domainname * const srv,const domainname * const domain,const mDNSInterfaceID InterfaceID,mDNSu32 flags,mDNSBool ForceMCast,mDNSBool useBackgroundTrafficClass,mDNSQuestionCallback * Callback,void * Context)12404c65ebfc7SToomas Soome mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12405c65ebfc7SToomas Soome                                             const domainname *const srv, const domainname *const domain,
12406*472cd20dSToomas Soome                                             const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12407c65ebfc7SToomas Soome                                             mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12408c65ebfc7SToomas Soome                                             mDNSQuestionCallback *Callback, void *Context)
12409c65ebfc7SToomas Soome {
12410c65ebfc7SToomas Soome     question->InterfaceID      = InterfaceID;
12411c65ebfc7SToomas Soome     question->flags            = flags;
12412c65ebfc7SToomas Soome     question->qtype            = kDNSType_PTR;
12413c65ebfc7SToomas Soome     question->qclass           = kDNSClass_IN;
12414c65ebfc7SToomas Soome     question->LongLived        = mDNStrue;
12415c65ebfc7SToomas Soome     question->ExpectUnique     = mDNSfalse;
12416c65ebfc7SToomas Soome     question->ForceMCast       = ForceMCast;
12417c65ebfc7SToomas Soome     question->ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
12418c65ebfc7SToomas Soome     question->SuppressUnusable = mDNSfalse;
12419*472cd20dSToomas Soome     question->AppendSearchDomains = mDNSfalse;
12420c65ebfc7SToomas Soome     question->TimeoutQuestion  = 0;
12421c65ebfc7SToomas Soome     question->WakeOnResolve    = 0;
12422*472cd20dSToomas Soome     question->UseBackgroundTraffic = useBackgroundTrafficClass;
12423c65ebfc7SToomas Soome     question->ProxyQuestion    = 0;
12424c65ebfc7SToomas Soome     question->QuestionCallback = Callback;
12425c65ebfc7SToomas Soome     question->QuestionContext  = Context;
12426c65ebfc7SToomas Soome 
12427c65ebfc7SToomas Soome     if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12428c65ebfc7SToomas Soome         return(mStatus_BadParamErr);
12429c65ebfc7SToomas Soome 
12430c65ebfc7SToomas Soome     return(mDNS_StartQuery_internal(m, question));
12431c65ebfc7SToomas Soome }
12432c65ebfc7SToomas Soome 
mDNS_StartBrowse(mDNS * const m,DNSQuestion * const question,const domainname * const srv,const domainname * const domain,const mDNSInterfaceID InterfaceID,mDNSu32 flags,mDNSBool ForceMCast,mDNSBool useBackgroundTrafficClass,mDNSQuestionCallback * Callback,void * Context)12433c65ebfc7SToomas Soome mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12434c65ebfc7SToomas Soome                                     const domainname *const srv, const domainname *const domain,
12435*472cd20dSToomas Soome                                     const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12436c65ebfc7SToomas Soome                                     mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12437c65ebfc7SToomas Soome                                     mDNSQuestionCallback *Callback, void *Context)
12438c65ebfc7SToomas Soome {
12439c65ebfc7SToomas Soome     mStatus status;
12440c65ebfc7SToomas Soome     mDNS_Lock(m);
12441*472cd20dSToomas Soome     status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12442c65ebfc7SToomas Soome     mDNS_Unlock(m);
12443c65ebfc7SToomas Soome     return(status);
12444c65ebfc7SToomas Soome }
12445c65ebfc7SToomas Soome 
12446c65ebfc7SToomas Soome 
mDNS_GetDomains(mDNS * const m,DNSQuestion * const question,mDNS_DomainType DomainType,const domainname * dom,const mDNSInterfaceID InterfaceID,mDNSQuestionCallback * Callback,void * Context)12447c65ebfc7SToomas Soome mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12448c65ebfc7SToomas Soome                                    const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12449c65ebfc7SToomas Soome {
12450c65ebfc7SToomas Soome     question->InterfaceID      = InterfaceID;
12451c65ebfc7SToomas Soome     question->flags            = 0;
12452c65ebfc7SToomas Soome     question->qtype            = kDNSType_PTR;
12453c65ebfc7SToomas Soome     question->qclass           = kDNSClass_IN;
12454c65ebfc7SToomas Soome     question->LongLived        = mDNSfalse;
12455c65ebfc7SToomas Soome     question->ExpectUnique     = mDNSfalse;
12456c65ebfc7SToomas Soome     question->ForceMCast       = mDNSfalse;
12457c65ebfc7SToomas Soome     question->ReturnIntermed   = mDNSfalse;
12458c65ebfc7SToomas Soome     question->SuppressUnusable = mDNSfalse;
12459*472cd20dSToomas Soome     question->AppendSearchDomains = mDNSfalse;
12460c65ebfc7SToomas Soome     question->TimeoutQuestion  = 0;
12461c65ebfc7SToomas Soome     question->WakeOnResolve    = 0;
12462*472cd20dSToomas Soome     question->UseBackgroundTraffic = mDNSfalse;
12463c65ebfc7SToomas Soome     question->ProxyQuestion    = 0;
12464c65ebfc7SToomas Soome     question->pid              = mDNSPlatformGetPID();
12465c65ebfc7SToomas Soome     question->euid             = 0;
12466c65ebfc7SToomas Soome     question->QuestionCallback = Callback;
12467c65ebfc7SToomas Soome     question->QuestionContext  = Context;
12468c65ebfc7SToomas Soome     if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12469c65ebfc7SToomas Soome     if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12470c65ebfc7SToomas Soome     if (!dom) dom = &localdomain;
12471c65ebfc7SToomas Soome     if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12472c65ebfc7SToomas Soome     return(mDNS_StartQuery(m, question));
12473c65ebfc7SToomas Soome }
12474c65ebfc7SToomas Soome 
12475c65ebfc7SToomas Soome // ***************************************************************************
12476c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
12477c65ebfc7SToomas Soome #pragma mark -
12478c65ebfc7SToomas Soome #pragma mark - Responder Functions
12479c65ebfc7SToomas Soome #endif
12480c65ebfc7SToomas Soome 
mDNS_Register(mDNS * const m,AuthRecord * const rr)12481c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12482c65ebfc7SToomas Soome {
12483c65ebfc7SToomas Soome     mStatus status;
12484c65ebfc7SToomas Soome     mDNS_Lock(m);
12485c65ebfc7SToomas Soome     status = mDNS_Register_internal(m, rr);
12486c65ebfc7SToomas Soome     mDNS_Unlock(m);
12487c65ebfc7SToomas Soome     return(status);
12488c65ebfc7SToomas Soome }
12489c65ebfc7SToomas Soome 
mDNS_Update(mDNS * const m,AuthRecord * const rr,mDNSu32 newttl,const mDNSu16 newrdlength,RData * const newrdata,mDNSRecordUpdateCallback * Callback)12490c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12491c65ebfc7SToomas Soome                                const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12492c65ebfc7SToomas Soome {
12493c65ebfc7SToomas Soome     if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12494c65ebfc7SToomas Soome     {
12495c65ebfc7SToomas Soome         LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12496c65ebfc7SToomas Soome         return(mStatus_Invalid);
12497c65ebfc7SToomas Soome     }
12498c65ebfc7SToomas Soome 
12499c65ebfc7SToomas Soome     mDNS_Lock(m);
12500c65ebfc7SToomas Soome 
12501c65ebfc7SToomas Soome     // If TTL is unspecified, leave TTL unchanged
12502c65ebfc7SToomas Soome     if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12503c65ebfc7SToomas Soome 
12504c65ebfc7SToomas Soome     // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12505c65ebfc7SToomas Soome     if (rr->NewRData)
12506c65ebfc7SToomas Soome     {
12507c65ebfc7SToomas Soome         RData *n = rr->NewRData;
12508c65ebfc7SToomas Soome         rr->NewRData = mDNSNULL;                            // Clear the NewRData pointer ...
12509c65ebfc7SToomas Soome         if (rr->UpdateCallback)
12510c65ebfc7SToomas Soome             rr->UpdateCallback(m, rr, n, rr->newrdlength);  // ...and let the client free this memory, if necessary
12511c65ebfc7SToomas Soome     }
12512c65ebfc7SToomas Soome 
12513c65ebfc7SToomas Soome     rr->NewRData             = newrdata;
12514c65ebfc7SToomas Soome     rr->newrdlength          = newrdlength;
12515c65ebfc7SToomas Soome     rr->UpdateCallback       = Callback;
12516c65ebfc7SToomas Soome 
12517c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
12518c65ebfc7SToomas Soome     if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12519c65ebfc7SToomas Soome     {
12520c65ebfc7SToomas Soome         mStatus status = uDNS_UpdateRecord(m, rr);
12521c65ebfc7SToomas Soome         // The caller frees the memory on error, don't retain stale pointers
12522c65ebfc7SToomas Soome         if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12523c65ebfc7SToomas Soome         mDNS_Unlock(m);
12524c65ebfc7SToomas Soome         return(status);
12525c65ebfc7SToomas Soome     }
12526c65ebfc7SToomas Soome #endif
12527c65ebfc7SToomas Soome 
12528c65ebfc7SToomas Soome     if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12529c65ebfc7SToomas Soome                             rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12530c65ebfc7SToomas Soome         CompleteRDataUpdate(m, rr);
12531c65ebfc7SToomas Soome     else
12532c65ebfc7SToomas Soome     {
12533c65ebfc7SToomas Soome         rr->AnnounceCount = InitialAnnounceCount;
12534c65ebfc7SToomas Soome         InitializeLastAPTime(m, rr);
12535c65ebfc7SToomas Soome         while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12536c65ebfc7SToomas Soome         if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12537c65ebfc7SToomas Soome         if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12538c65ebfc7SToomas Soome         if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12539c65ebfc7SToomas Soome         if (rr->UpdateCredits <= 5)
12540c65ebfc7SToomas Soome         {
12541c65ebfc7SToomas Soome             mDNSu32 delay = 6 - rr->UpdateCredits;      // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12542c65ebfc7SToomas Soome             if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12543c65ebfc7SToomas Soome             rr->ThisAPInterval *= 4;
12544c65ebfc7SToomas Soome             rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12545c65ebfc7SToomas Soome             LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12546c65ebfc7SToomas Soome                    rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12547c65ebfc7SToomas Soome         }
12548c65ebfc7SToomas Soome         rr->resrec.rroriginalttl = newttl;
12549c65ebfc7SToomas Soome     }
12550c65ebfc7SToomas Soome 
12551c65ebfc7SToomas Soome     mDNS_Unlock(m);
12552c65ebfc7SToomas Soome     return(mStatus_NoError);
12553c65ebfc7SToomas Soome }
12554c65ebfc7SToomas Soome 
12555c65ebfc7SToomas Soome // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12556c65ebfc7SToomas Soome // the record list and/or question list.
12557c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
mDNS_Deregister(mDNS * const m,AuthRecord * const rr)12558c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12559c65ebfc7SToomas Soome {
12560c65ebfc7SToomas Soome     mStatus status;
12561c65ebfc7SToomas Soome     mDNS_Lock(m);
12562c65ebfc7SToomas Soome     status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12563c65ebfc7SToomas Soome     mDNS_Unlock(m);
12564c65ebfc7SToomas Soome     return(status);
12565c65ebfc7SToomas Soome }
12566c65ebfc7SToomas Soome 
12567c65ebfc7SToomas Soome // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12568c65ebfc7SToomas Soome mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12569*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12570*472cd20dSToomas Soome mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *m, AuthRecord *rr, mStatus result);
12571*472cd20dSToomas Soome #endif
12572c65ebfc7SToomas Soome 
GetInterfaceAddressRecord(NetworkInterfaceInfo * intf,mDNSBool forRandHostname)12573*472cd20dSToomas Soome mDNSlocal AuthRecord *GetInterfaceAddressRecord(NetworkInterfaceInfo *intf, mDNSBool forRandHostname)
12574*472cd20dSToomas Soome {
12575*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12576*472cd20dSToomas Soome         return(forRandHostname ? &intf->RR_AddrRand : &intf->RR_A);
12577*472cd20dSToomas Soome #else
12578*472cd20dSToomas Soome         (void)forRandHostname; // Unused.
12579*472cd20dSToomas Soome         return(&intf->RR_A);
12580*472cd20dSToomas Soome #endif
12581*472cd20dSToomas Soome }
12582*472cd20dSToomas Soome 
GetFirstAddressRecordEx(const mDNS * const m,const mDNSBool forRandHostname)12583*472cd20dSToomas Soome mDNSlocal AuthRecord *GetFirstAddressRecordEx(const mDNS *const m, const mDNSBool forRandHostname)
12584c65ebfc7SToomas Soome {
12585c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
12586c65ebfc7SToomas Soome     for (intf = m->HostInterfaces; intf; intf = intf->next)
12587*472cd20dSToomas Soome     {
12588*472cd20dSToomas Soome         if (!intf->Advertise) continue;
12589*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12590*472cd20dSToomas Soome         if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
12591*472cd20dSToomas Soome #endif
12592*472cd20dSToomas Soome         return(GetInterfaceAddressRecord(intf, forRandHostname));
12593c65ebfc7SToomas Soome     }
12594*472cd20dSToomas Soome     return(mDNSNULL);
12595*472cd20dSToomas Soome }
12596*472cd20dSToomas Soome #define GetFirstAddressRecord(M)    GetFirstAddressRecordEx(M, mDNSfalse)
12597c65ebfc7SToomas Soome 
12598c65ebfc7SToomas Soome // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12599c65ebfc7SToomas Soome // (It's a set of records, not a set of interfaces.)
12600*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
AdvertiseInterface(mDNS * const m,NetworkInterfaceInfo * set,mDNSBool useRandomizedHostname)12601*472cd20dSToomas Soome mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool useRandomizedHostname)
12602*472cd20dSToomas Soome #else
12603c65ebfc7SToomas Soome mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12604*472cd20dSToomas Soome #endif
12605c65ebfc7SToomas Soome {
12606*472cd20dSToomas Soome     const domainname *hostname;
12607*472cd20dSToomas Soome     mDNSRecordCallback *hostnameCallback;
12608*472cd20dSToomas Soome     AuthRecord *addrAR;
12609*472cd20dSToomas Soome     AuthRecord *ptrAR;
12610*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12611*472cd20dSToomas Soome     const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12612*472cd20dSToomas Soome #endif
12613*472cd20dSToomas Soome     mDNSu8 addrRecordType;
12614c65ebfc7SToomas Soome     char buffer[MAX_REVERSE_MAPPING_NAME];
12615c65ebfc7SToomas Soome 
12616*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12617*472cd20dSToomas Soome     if (interfaceIsAWDL || useRandomizedHostname)
12618c65ebfc7SToomas Soome     {
12619*472cd20dSToomas Soome         hostname         = &m->RandomizedHostname;
12620*472cd20dSToomas Soome         hostnameCallback = mDNS_RandomizedHostNameCallback;
12621*472cd20dSToomas Soome     }
12622*472cd20dSToomas Soome     else
12623*472cd20dSToomas Soome #endif
12624*472cd20dSToomas Soome     {
12625*472cd20dSToomas Soome         hostname         = &m->MulticastHostname;
12626*472cd20dSToomas Soome         hostnameCallback = mDNS_HostNameCallback;
12627c65ebfc7SToomas Soome     }
12628c65ebfc7SToomas Soome 
12629*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12630*472cd20dSToomas Soome     if (!interfaceIsAWDL && useRandomizedHostname)
12631*472cd20dSToomas Soome     {
12632*472cd20dSToomas Soome         addrAR = &set->RR_AddrRand;
12633*472cd20dSToomas Soome         ptrAR  = mDNSNULL;
12634*472cd20dSToomas Soome     }
12635*472cd20dSToomas Soome     else
12636*472cd20dSToomas Soome #endif
12637*472cd20dSToomas Soome     {
12638*472cd20dSToomas Soome         addrAR = &set->RR_A;
12639*472cd20dSToomas Soome         ptrAR  = &set->RR_PTR;
12640*472cd20dSToomas Soome     }
12641*472cd20dSToomas Soome     if (addrAR->resrec.RecordType != kDNSRecordTypeUnregistered) return;
12642c65ebfc7SToomas Soome 
12643*472cd20dSToomas Soome     addrRecordType = set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
12644*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12645*472cd20dSToomas Soome     if (hostname == &m->RandomizedHostname) addrRecordType = kDNSRecordTypeKnownUnique;
12646*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12647*472cd20dSToomas Soome         "AdvertiseInterface: Advertising " PUB_S " hostname on interface " PUB_S,
12648*472cd20dSToomas Soome         (hostname == &m->RandomizedHostname) ? "randomized" : "normal", set->ifname);
12649*472cd20dSToomas Soome #else
12650*472cd20dSToomas Soome     LogInfo("AdvertiseInterface: Advertising for ifname %s", set->ifname);
12651*472cd20dSToomas Soome #endif
12652c65ebfc7SToomas Soome 
12653c65ebfc7SToomas Soome     // Send dynamic update for non-linklocal IPv4 Addresses
12654*472cd20dSToomas Soome     mDNS_SetupResourceRecord(addrAR, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, addrRecordType, AuthRecordAny, hostnameCallback, set);
12655*472cd20dSToomas Soome     if (ptrAR) mDNS_SetupResourceRecord(ptrAR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12656c65ebfc7SToomas Soome 
12657c65ebfc7SToomas Soome #if ANSWER_REMOTE_HOSTNAME_QUERIES
12658*472cd20dSToomas Soome     addrAR->AllowRemoteQuery = mDNStrue;
12659*472cd20dSToomas Soome     if (ptrAR) ptrAR->AllowRemoteQuery = mDNStrue;
12660c65ebfc7SToomas Soome #endif
12661c65ebfc7SToomas Soome     // 1. Set up Address record to map from host name ("foo.local.") to IP address
12662c65ebfc7SToomas Soome     // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12663*472cd20dSToomas Soome     AssignDomainName(&addrAR->namestorage, hostname);
12664c65ebfc7SToomas Soome     if (set->ip.type == mDNSAddrType_IPv4)
12665c65ebfc7SToomas Soome     {
12666*472cd20dSToomas Soome         addrAR->resrec.rrtype        = kDNSType_A;
12667*472cd20dSToomas Soome         addrAR->resrec.rdata->u.ipv4 = set->ip.ip.v4;
12668c65ebfc7SToomas Soome         // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12669c65ebfc7SToomas Soome         mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12670c65ebfc7SToomas Soome                       set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12671c65ebfc7SToomas Soome     }
12672c65ebfc7SToomas Soome     else if (set->ip.type == mDNSAddrType_IPv6)
12673c65ebfc7SToomas Soome     {
12674c65ebfc7SToomas Soome         int i;
12675*472cd20dSToomas Soome         addrAR->resrec.rrtype        = kDNSType_AAAA;
12676*472cd20dSToomas Soome         addrAR->resrec.rdata->u.ipv6 = set->ip.ip.v6;
12677c65ebfc7SToomas Soome         for (i = 0; i < 16; i++)
12678c65ebfc7SToomas Soome         {
12679c65ebfc7SToomas Soome             static const char hexValues[] = "0123456789ABCDEF";
12680c65ebfc7SToomas Soome             buffer[i * 4    ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12681c65ebfc7SToomas Soome             buffer[i * 4 + 1] = '.';
12682c65ebfc7SToomas Soome             buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12683c65ebfc7SToomas Soome             buffer[i * 4 + 3] = '.';
12684c65ebfc7SToomas Soome         }
12685c65ebfc7SToomas Soome         mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12686c65ebfc7SToomas Soome     }
12687c65ebfc7SToomas Soome 
12688*472cd20dSToomas Soome     if (ptrAR)
12689*472cd20dSToomas Soome     {
12690*472cd20dSToomas Soome         MakeDomainNameFromDNSNameString(&ptrAR->namestorage, buffer);
12691*472cd20dSToomas Soome         ptrAR->AutoTarget = Target_AutoHost;    // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12692*472cd20dSToomas Soome         ptrAR->ForceMCast = mDNStrue;           // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12693*472cd20dSToomas Soome     }
12694c65ebfc7SToomas Soome 
12695*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12696*472cd20dSToomas Soome     addrAR->RRSet = interfaceIsAWDL ? addrAR : GetFirstAddressRecordEx(m, useRandomizedHostname);
12697*472cd20dSToomas Soome #else
12698*472cd20dSToomas Soome     addrAR->RRSet = GetFirstAddressRecord(m);
12699*472cd20dSToomas Soome #endif
12700*472cd20dSToomas Soome     if (!addrAR->RRSet) addrAR->RRSet = addrAR;
12701*472cd20dSToomas Soome     mDNS_Register_internal(m, addrAR);
12702*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Initialized RRSet for " PRI_S, ARDisplayString(m, addrAR));
12703*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "RRSet:                " PRI_S, ARDisplayString(m, addrAR->RRSet));
12704*472cd20dSToomas Soome     if (ptrAR) mDNS_Register_internal(m, ptrAR);
12705c65ebfc7SToomas Soome 
12706*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12707c65ebfc7SToomas Soome     // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12708c65ebfc7SToomas Soome     D2D_start_advertising_interface(set);
12709*472cd20dSToomas Soome #endif
12710*472cd20dSToomas Soome }
12711c65ebfc7SToomas Soome 
AdvertiseInterfaceIfNeeded(mDNS * const m,NetworkInterfaceInfo * set)12712*472cd20dSToomas Soome mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set)
12713c65ebfc7SToomas Soome {
12714*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12715*472cd20dSToomas Soome     if (mDNSPlatformInterfaceIsAWDL(set->InterfaceID))
12716*472cd20dSToomas Soome     {
12717*472cd20dSToomas Soome         if ((m->AutoTargetAWDLIncludedCount > 0) || (m->AutoTargetAWDLOnlyCount > 0))
12718*472cd20dSToomas Soome         {
12719*472cd20dSToomas Soome             AdvertiseInterface(m, set, mDNSfalse);
12720*472cd20dSToomas Soome         }
12721c65ebfc7SToomas Soome     }
12722c65ebfc7SToomas Soome     else
12723c65ebfc7SToomas Soome     {
12724*472cd20dSToomas Soome         if (m->AutoTargetServices          > 0) AdvertiseInterface(m, set, mDNSfalse);
12725*472cd20dSToomas Soome         if (m->AutoTargetAWDLIncludedCount > 0) AdvertiseInterface(m, set, mDNStrue);
12726c65ebfc7SToomas Soome     }
12727*472cd20dSToomas Soome #else
12728*472cd20dSToomas Soome     if (m->AutoTargetServices > 0) AdvertiseInterface(m, set);
12729*472cd20dSToomas Soome #endif
12730c65ebfc7SToomas Soome }
12731c65ebfc7SToomas Soome 
DeadvertiseInterface(mDNS * const m,NetworkInterfaceInfo * set,DeadvertiseFlags flags)12732*472cd20dSToomas Soome mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags)
12733c65ebfc7SToomas Soome {
12734*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12735*472cd20dSToomas Soome     const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12736*472cd20dSToomas Soome #endif
12737c65ebfc7SToomas Soome 
12738c65ebfc7SToomas Soome     // Unregister these records.
12739c65ebfc7SToomas Soome     // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12740c65ebfc7SToomas Soome     // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12741c65ebfc7SToomas Soome     // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12742c65ebfc7SToomas Soome     // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12743*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12744*472cd20dSToomas Soome     if ((!interfaceIsAWDL && (flags & kDeadvertiseFlag_NormalHostname)) ||
12745*472cd20dSToomas Soome         ( interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname)))
12746*472cd20dSToomas Soome #else
12747*472cd20dSToomas Soome     if (flags & kDeadvertiseFlag_NormalHostname)
12748*472cd20dSToomas Soome #endif
12749*472cd20dSToomas Soome     {
12750*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12751*472cd20dSToomas Soome             "DeadvertiseInterface: Deadvertising " PUB_S " hostname on interface " PUB_S,
12752*472cd20dSToomas Soome             (flags & kDeadvertiseFlag_RandHostname) ? "randomized" : "normal", set->ifname);
12753*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12754*472cd20dSToomas Soome         D2D_stop_advertising_interface(set);
12755*472cd20dSToomas Soome #endif
12756c65ebfc7SToomas Soome         if (set->RR_A.resrec.RecordType)   mDNS_Deregister_internal(m, &set->RR_A,   mDNS_Dereg_normal);
12757c65ebfc7SToomas Soome         if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12758c65ebfc7SToomas Soome     }
12759*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12760*472cd20dSToomas Soome     if (!interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname))
12761c65ebfc7SToomas Soome     {
12762*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12763*472cd20dSToomas Soome             "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S, set->ifname);
12764*472cd20dSToomas Soome         AuthRecord *const ar = &set->RR_AddrRand;
12765*472cd20dSToomas Soome         if (ar->resrec.RecordType) mDNS_Deregister_internal(m, ar, mDNS_Dereg_normal);
12766c65ebfc7SToomas Soome     }
12767*472cd20dSToomas Soome #endif
12768c65ebfc7SToomas Soome }
12769c65ebfc7SToomas Soome 
12770c65ebfc7SToomas Soome // Change target host name for record.
UpdateTargetHostName(mDNS * const m,AuthRecord * const rr)12771c65ebfc7SToomas Soome mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr)
12772c65ebfc7SToomas Soome {
12773*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12774c65ebfc7SToomas Soome     // If this record was also registered with any D2D plugins, stop advertising
12775c65ebfc7SToomas Soome     // the version with the old host name.
12776c65ebfc7SToomas Soome     D2D_stop_advertising_record(rr);
12777c65ebfc7SToomas Soome #endif
12778c65ebfc7SToomas Soome 
12779c65ebfc7SToomas Soome     SetTargetToHostName(m, rr);
12780c65ebfc7SToomas Soome 
12781*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12782c65ebfc7SToomas Soome     // Advertise the record with the updated host name with the D2D plugins if appropriate.
12783c65ebfc7SToomas Soome     D2D_start_advertising_record(rr);
12784c65ebfc7SToomas Soome #endif
12785c65ebfc7SToomas Soome }
12786c65ebfc7SToomas Soome 
DeadvertiseAllInterfaceRecords(mDNS * const m,DeadvertiseFlags flags)12787*472cd20dSToomas Soome mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m, DeadvertiseFlags flags)
12788*472cd20dSToomas Soome {
12789*472cd20dSToomas Soome     NetworkInterfaceInfo *intf;
12790*472cd20dSToomas Soome     for (intf = m->HostInterfaces; intf; intf = intf->next)
12791*472cd20dSToomas Soome     {
12792*472cd20dSToomas Soome         if (intf->Advertise) DeadvertiseInterface(m, intf, flags);
12793*472cd20dSToomas Soome     }
12794*472cd20dSToomas Soome }
12795*472cd20dSToomas Soome 
mDNS_SetFQDN(mDNS * const m)12796c65ebfc7SToomas Soome mDNSexport void mDNS_SetFQDN(mDNS *const m)
12797c65ebfc7SToomas Soome {
12798c65ebfc7SToomas Soome     domainname newmname;
12799c65ebfc7SToomas Soome     AuthRecord *rr;
12800c65ebfc7SToomas Soome     newmname.c[0] = 0;
12801c65ebfc7SToomas Soome 
12802c65ebfc7SToomas Soome     if (!AppendDomainLabel(&newmname, &m->hostlabel))  { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12803c65ebfc7SToomas Soome     if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12804c65ebfc7SToomas Soome 
12805c65ebfc7SToomas Soome     mDNS_Lock(m);
12806c65ebfc7SToomas Soome 
12807c65ebfc7SToomas Soome     if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12808c65ebfc7SToomas Soome     else
12809c65ebfc7SToomas Soome     {
12810c65ebfc7SToomas Soome         AssignDomainName(&m->MulticastHostname, &newmname);
12811*472cd20dSToomas Soome         DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_NormalHostname);
12812*472cd20dSToomas Soome         AdvertiseNecessaryInterfaceRecords(m);
12813c65ebfc7SToomas Soome     }
12814c65ebfc7SToomas Soome 
12815c65ebfc7SToomas Soome     // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12816c65ebfc7SToomas Soome     for (rr = m->ResourceRecords;  rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12817c65ebfc7SToomas Soome     for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12818c65ebfc7SToomas Soome 
12819c65ebfc7SToomas Soome     mDNS_Unlock(m);
12820c65ebfc7SToomas Soome }
12821c65ebfc7SToomas Soome 
mDNS_HostNameCallback(mDNS * const m,AuthRecord * const rr,mStatus result)12822c65ebfc7SToomas Soome mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12823c65ebfc7SToomas Soome {
12824c65ebfc7SToomas Soome     (void)rr;   // Unused parameter
12825c65ebfc7SToomas Soome 
12826c65ebfc7SToomas Soome     #if MDNS_DEBUGMSGS
12827c65ebfc7SToomas Soome     {
12828c65ebfc7SToomas Soome         char *msg = "Unknown result";
12829c65ebfc7SToomas Soome         if      (result == mStatus_NoError) msg = "Name registered";
12830c65ebfc7SToomas Soome         else if (result == mStatus_NameConflict) msg = "Name conflict";
12831c65ebfc7SToomas Soome         debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12832c65ebfc7SToomas Soome     }
12833c65ebfc7SToomas Soome     #endif
12834c65ebfc7SToomas Soome 
12835c65ebfc7SToomas Soome     if (result == mStatus_NoError)
12836c65ebfc7SToomas Soome     {
12837c65ebfc7SToomas Soome         // Notify the client that the host name is successfully registered
12838c65ebfc7SToomas Soome         if (m->MainCallback)
12839c65ebfc7SToomas Soome             m->MainCallback(m, mStatus_NoError);
12840c65ebfc7SToomas Soome     }
12841c65ebfc7SToomas Soome     else if (result == mStatus_NameConflict)
12842c65ebfc7SToomas Soome     {
12843c65ebfc7SToomas Soome         domainlabel oldlabel = m->hostlabel;
12844c65ebfc7SToomas Soome 
12845c65ebfc7SToomas Soome         // 1. First give the client callback a chance to pick a new name
12846c65ebfc7SToomas Soome         if (m->MainCallback)
12847c65ebfc7SToomas Soome             m->MainCallback(m, mStatus_NameConflict);
12848c65ebfc7SToomas Soome 
12849c65ebfc7SToomas Soome         // 2. If the client callback didn't do it, add (or increment) an index ourselves
12850c65ebfc7SToomas Soome         // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12851c65ebfc7SToomas Soome         // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12852c65ebfc7SToomas Soome         if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12853c65ebfc7SToomas Soome             IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12854c65ebfc7SToomas Soome 
12855c65ebfc7SToomas Soome         // 3. Generate the FQDNs from the hostlabel,
12856c65ebfc7SToomas Soome         // and make sure all SRV records, etc., are updated to reference our new hostname
12857c65ebfc7SToomas Soome         mDNS_SetFQDN(m);
12858c65ebfc7SToomas Soome         LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12859c65ebfc7SToomas Soome     }
12860c65ebfc7SToomas Soome     else if (result == mStatus_MemFree)
12861c65ebfc7SToomas Soome     {
12862c65ebfc7SToomas Soome         // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12863c65ebfc7SToomas Soome         // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12864c65ebfc7SToomas Soome         debugf("mDNS_HostNameCallback: MemFree (ignored)");
12865c65ebfc7SToomas Soome     }
12866c65ebfc7SToomas Soome     else
12867c65ebfc7SToomas Soome         LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result,  rr->resrec.name->c);
12868c65ebfc7SToomas Soome }
12869c65ebfc7SToomas Soome 
12870*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
mDNS_RandomizedHostNameCallback(mDNS * const m,AuthRecord * const addrRecord,const mStatus result)12871*472cd20dSToomas Soome mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *const m, AuthRecord *const addrRecord, const mStatus result)
12872*472cd20dSToomas Soome {
12873*472cd20dSToomas Soome     (void)addrRecord;   // Unused parameter
12874*472cd20dSToomas Soome 
12875*472cd20dSToomas Soome     if (result == mStatus_NameConflict)
12876*472cd20dSToomas Soome     {
12877*472cd20dSToomas Soome         AuthRecord *rr;
12878*472cd20dSToomas Soome         domainlabel newUUIDLabel;
12879*472cd20dSToomas Soome 
12880*472cd20dSToomas Soome         GetRandomUUIDLabel(&newUUIDLabel);
12881*472cd20dSToomas Soome         if (SameDomainLabel(newUUIDLabel.c, m->RandomizedHostname.c))
12882*472cd20dSToomas Soome         {
12883*472cd20dSToomas Soome             IncrementLabelSuffix(&newUUIDLabel, mDNSfalse);
12884*472cd20dSToomas Soome         }
12885*472cd20dSToomas Soome 
12886*472cd20dSToomas Soome         mDNS_Lock(m);
12887*472cd20dSToomas Soome 
12888*472cd20dSToomas Soome         m->RandomizedHostname.c[0] = 0;
12889*472cd20dSToomas Soome         AppendDomainLabel(&m->RandomizedHostname, &newUUIDLabel);
12890*472cd20dSToomas Soome         AppendLiteralLabelString(&m->RandomizedHostname, "local");
12891*472cd20dSToomas Soome 
12892*472cd20dSToomas Soome         DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_RandHostname);
12893*472cd20dSToomas Soome         AdvertiseNecessaryInterfaceRecords(m);
12894*472cd20dSToomas Soome         for (rr = m->ResourceRecords; rr; rr = rr->next)
12895*472cd20dSToomas Soome         {
12896*472cd20dSToomas Soome             if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12897*472cd20dSToomas Soome         }
12898*472cd20dSToomas Soome         for (rr = m->DuplicateRecords; rr; rr = rr->next)
12899*472cd20dSToomas Soome         {
12900*472cd20dSToomas Soome             if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12901*472cd20dSToomas Soome         }
12902*472cd20dSToomas Soome 
12903*472cd20dSToomas Soome         mDNS_Unlock(m);
12904*472cd20dSToomas Soome     }
12905*472cd20dSToomas Soome }
12906*472cd20dSToomas Soome #endif
12907*472cd20dSToomas Soome 
UpdateInterfaceProtocols(mDNS * const m,NetworkInterfaceInfo * active)12908c65ebfc7SToomas Soome mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12909c65ebfc7SToomas Soome {
12910c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
12911c65ebfc7SToomas Soome     active->IPv4Available = mDNSfalse;
12912c65ebfc7SToomas Soome     active->IPv6Available = mDNSfalse;
12913c65ebfc7SToomas Soome     for (intf = m->HostInterfaces; intf; intf = intf->next)
12914c65ebfc7SToomas Soome         if (intf->InterfaceID == active->InterfaceID)
12915c65ebfc7SToomas Soome         {
12916c65ebfc7SToomas Soome             if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12917c65ebfc7SToomas Soome             if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12918c65ebfc7SToomas Soome         }
12919c65ebfc7SToomas Soome }
12920c65ebfc7SToomas Soome 
RestartRecordGetZoneData(mDNS * const m)12921c65ebfc7SToomas Soome mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12922c65ebfc7SToomas Soome {
12923c65ebfc7SToomas Soome     AuthRecord *rr;
12924c65ebfc7SToomas Soome     LogInfo("RestartRecordGetZoneData: ResourceRecords");
12925c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr=rr->next)
12926c65ebfc7SToomas Soome         if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12927c65ebfc7SToomas Soome         {
12928c65ebfc7SToomas Soome             debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12929c65ebfc7SToomas Soome             // Zero out the updateid so that if we have a pending response from the server, it won't
12930c65ebfc7SToomas Soome             // be accepted as a valid response. If we accept the response, we might free the new "nta"
12931c65ebfc7SToomas Soome             if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12932c65ebfc7SToomas Soome             rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12933c65ebfc7SToomas Soome         }
12934c65ebfc7SToomas Soome }
12935c65ebfc7SToomas Soome 
InitializeNetWakeState(mDNS * const m,NetworkInterfaceInfo * set)12936c65ebfc7SToomas Soome mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12937c65ebfc7SToomas Soome {
12938c65ebfc7SToomas Soome     int i;
12939c65ebfc7SToomas Soome     // We initialize ThisQInterval to -1 indicating that the question has not been started
12940c65ebfc7SToomas Soome     // yet. If the question (browse) is started later during interface registration, it will
12941c65ebfc7SToomas Soome     // be stopped during interface deregistration. We can't sanity check to see if the
12942c65ebfc7SToomas Soome     // question has been stopped or not before initializing it to -1 because we need to
12943c65ebfc7SToomas Soome     // initialize it to -1 the very first time.
12944c65ebfc7SToomas Soome 
12945c65ebfc7SToomas Soome     set->NetWakeBrowse.ThisQInterval = -1;
12946c65ebfc7SToomas Soome     for (i=0; i<3; i++)
12947c65ebfc7SToomas Soome     {
12948c65ebfc7SToomas Soome         set->NetWakeResolve[i].ThisQInterval = -1;
12949c65ebfc7SToomas Soome         set->SPSAddr[i].type = mDNSAddrType_None;
12950c65ebfc7SToomas Soome     }
12951c65ebfc7SToomas Soome     set->NextSPSAttempt     = -1;
12952c65ebfc7SToomas Soome     set->NextSPSAttemptTime = m->timenow;
12953c65ebfc7SToomas Soome }
12954c65ebfc7SToomas Soome 
mDNS_ActivateNetWake_internal(mDNS * const m,NetworkInterfaceInfo * set)12955c65ebfc7SToomas Soome mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12956c65ebfc7SToomas Soome {
12957c65ebfc7SToomas Soome     NetworkInterfaceInfo *p = m->HostInterfaces;
12958c65ebfc7SToomas Soome     while (p && p != set) p=p->next;
12959c65ebfc7SToomas Soome     if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12960c65ebfc7SToomas Soome 
12961c65ebfc7SToomas Soome     if (set->InterfaceActive)
12962c65ebfc7SToomas Soome     {
12963c65ebfc7SToomas Soome         LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12964*472cd20dSToomas Soome         mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12965c65ebfc7SToomas Soome     }
12966c65ebfc7SToomas Soome }
12967c65ebfc7SToomas Soome 
mDNS_DeactivateNetWake_internal(mDNS * const m,NetworkInterfaceInfo * set)12968c65ebfc7SToomas Soome mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12969c65ebfc7SToomas Soome {
12970c65ebfc7SToomas Soome     NetworkInterfaceInfo *p = m->HostInterfaces;
12971c65ebfc7SToomas Soome     while (p && p != set) p=p->next;
12972c65ebfc7SToomas Soome     if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12973c65ebfc7SToomas Soome 
12974c65ebfc7SToomas Soome     // Note: We start the browse only if the interface is NetWake capable and we use this to
12975c65ebfc7SToomas Soome     // stop the resolves also. Hence, the resolves should not be started without the browse
12976c65ebfc7SToomas Soome     // being started i.e, resolves should not happen unless NetWake capable which is
12977c65ebfc7SToomas Soome     // guaranteed by BeginSleepProcessing.
12978c65ebfc7SToomas Soome     if (set->NetWakeBrowse.ThisQInterval >= 0)
12979c65ebfc7SToomas Soome     {
12980c65ebfc7SToomas Soome         int i;
12981c65ebfc7SToomas Soome         LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12982c65ebfc7SToomas Soome 
12983c65ebfc7SToomas Soome         // Stop our browse and resolve operations
12984c65ebfc7SToomas Soome         mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12985c65ebfc7SToomas Soome         for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12986c65ebfc7SToomas Soome 
12987c65ebfc7SToomas Soome         // Make special call to the browse callback to let it know it can to remove all records for this interface
12988c65ebfc7SToomas Soome         if (m->SPSBrowseCallback)
12989c65ebfc7SToomas Soome         {
12990c65ebfc7SToomas Soome             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
129913b436d06SToomas Soome             m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, QC_rmv);
12992c65ebfc7SToomas Soome             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
12993c65ebfc7SToomas Soome         }
12994c65ebfc7SToomas Soome 
12995c65ebfc7SToomas Soome         // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12996c65ebfc7SToomas Soome         // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12997c65ebfc7SToomas Soome         InitializeNetWakeState(m, set);
12998c65ebfc7SToomas Soome     }
12999c65ebfc7SToomas Soome }
13000c65ebfc7SToomas Soome 
mDNS_RegisterInterface(mDNS * const m,NetworkInterfaceInfo * set,InterfaceActivationSpeed activationSpeed)13001c65ebfc7SToomas Soome mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13002c65ebfc7SToomas Soome {
13003c65ebfc7SToomas Soome     AuthRecord *rr;
13004c65ebfc7SToomas Soome     mDNSBool FirstOfType = mDNStrue;
13005c65ebfc7SToomas Soome     NetworkInterfaceInfo **p = &m->HostInterfaces;
13006c65ebfc7SToomas Soome 
13007c65ebfc7SToomas Soome     if (!set->InterfaceID)
13008*472cd20dSToomas Soome     {
13009*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13010*472cd20dSToomas Soome             "Tried to register a NetworkInterfaceInfo with zero InterfaceID - ifaddr: " PRI_IP_ADDR, &set->ip);
13011*472cd20dSToomas Soome         return(mStatus_Invalid);
13012*472cd20dSToomas Soome     }
13013c65ebfc7SToomas Soome 
13014c65ebfc7SToomas Soome     if (!mDNSAddressIsValidNonZero(&set->mask))
13015*472cd20dSToomas Soome     {
13016*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13017*472cd20dSToomas Soome             "Tried to register a NetworkInterfaceInfo with invalid mask - ifaddr: " PRI_IP_ADDR ", ifmask: " PUB_IP_ADDR,
13018*472cd20dSToomas Soome             &set->ip, &set->mask);
13019*472cd20dSToomas Soome         return(mStatus_Invalid);
13020*472cd20dSToomas Soome     }
13021c65ebfc7SToomas Soome 
13022c65ebfc7SToomas Soome     mDNS_Lock(m);
13023c65ebfc7SToomas Soome 
13024c65ebfc7SToomas Soome     // Assume this interface will be active now, unless we find a duplicate already in the list
13025c65ebfc7SToomas Soome     set->InterfaceActive = mDNStrue;
13026c65ebfc7SToomas Soome     set->IPv4Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
13027c65ebfc7SToomas Soome     set->IPv6Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
13028c65ebfc7SToomas Soome 
13029c65ebfc7SToomas Soome     InitializeNetWakeState(m, set);
13030c65ebfc7SToomas Soome 
13031c65ebfc7SToomas Soome     // Scan list to see if this InterfaceID is already represented
13032c65ebfc7SToomas Soome     while (*p)
13033c65ebfc7SToomas Soome     {
13034c65ebfc7SToomas Soome         if (*p == set)
13035c65ebfc7SToomas Soome         {
13036*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13037*472cd20dSToomas Soome                 "Tried to register a NetworkInterfaceInfo that's already in the list - "
13038*472cd20dSToomas Soome                 "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip);
13039c65ebfc7SToomas Soome             mDNS_Unlock(m);
13040c65ebfc7SToomas Soome             return(mStatus_AlreadyRegistered);
13041c65ebfc7SToomas Soome         }
13042c65ebfc7SToomas Soome 
13043c65ebfc7SToomas Soome         if ((*p)->InterfaceID == set->InterfaceID)
13044c65ebfc7SToomas Soome         {
13045c65ebfc7SToomas Soome             // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13046c65ebfc7SToomas Soome             set->InterfaceActive = mDNSfalse;
13047c65ebfc7SToomas Soome             if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
13048c65ebfc7SToomas Soome             if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
13049c65ebfc7SToomas Soome             if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
13050c65ebfc7SToomas Soome         }
13051c65ebfc7SToomas Soome 
13052c65ebfc7SToomas Soome         p=&(*p)->next;
13053c65ebfc7SToomas Soome     }
13054c65ebfc7SToomas Soome 
13055c65ebfc7SToomas Soome     set->next = mDNSNULL;
13056c65ebfc7SToomas Soome     *p = set;
13057c65ebfc7SToomas Soome 
13058*472cd20dSToomas Soome     if (set->Advertise) AdvertiseInterfaceIfNeeded(m, set);
13059c65ebfc7SToomas Soome 
13060*472cd20dSToomas Soome     if (set->InterfaceActive)
13061*472cd20dSToomas Soome     {
13062*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13063*472cd20dSToomas Soome             "Interface not represented in list; marking active and retriggering queries - "
13064*472cd20dSToomas Soome             "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13065*472cd20dSToomas Soome     }
13066*472cd20dSToomas Soome     else
13067*472cd20dSToomas Soome     {
13068*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13069*472cd20dSToomas Soome             "Interface already represented in list - "
13070*472cd20dSToomas Soome             "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13071*472cd20dSToomas Soome     }
13072c65ebfc7SToomas Soome 
13073c65ebfc7SToomas Soome     if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
13074c65ebfc7SToomas Soome 
13075c65ebfc7SToomas Soome     // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13076c65ebfc7SToomas Soome     // giving the false impression that there's an active representative of this interface when there really isn't.
13077c65ebfc7SToomas Soome     // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13078c65ebfc7SToomas Soome     // even if we believe that we previously had an active representative of this interface.
13079c65ebfc7SToomas Soome     if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
13080c65ebfc7SToomas Soome     {
13081c65ebfc7SToomas Soome         DNSQuestion *q;
13082c65ebfc7SToomas Soome         // Normally, after an interface comes up, we pause half a second before beginning probing.
13083c65ebfc7SToomas Soome         // This is to guard against cases where there's rapid interface changes, where we could be confused by
13084c65ebfc7SToomas Soome         // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13085c65ebfc7SToomas Soome         // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13086c65ebfc7SToomas Soome         // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13087c65ebfc7SToomas Soome         // and think it's a conflicting answer to our probe.
13088c65ebfc7SToomas Soome         // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13089c65ebfc7SToomas Soome         mDNSs32 probedelay;
13090c65ebfc7SToomas Soome         mDNSu8 numannounce;
13091c65ebfc7SToomas Soome         switch (activationSpeed)
13092c65ebfc7SToomas Soome         {
13093c65ebfc7SToomas Soome             case FastActivation:
13094c65ebfc7SToomas Soome                 probedelay = (mDNSs32)0;
13095c65ebfc7SToomas Soome                 numannounce = InitialAnnounceCount;
13096*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13097*472cd20dSToomas Soome                     "Using fast activation for DirectLink interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13098*472cd20dSToomas Soome                     set->ifname, &set->ip);
13099c65ebfc7SToomas Soome                 break;
13100c65ebfc7SToomas Soome 
13101*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13102c65ebfc7SToomas Soome             case SlowActivation:
13103c65ebfc7SToomas Soome                 probedelay = mDNSPlatformOneSecond * 5;
13104c65ebfc7SToomas Soome                 numannounce = (mDNSu8)1;
13105*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13106*472cd20dSToomas Soome                     "Frequent transitions for interface, doing slow activation - "
13107*472cd20dSToomas Soome                     "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip);
13108c65ebfc7SToomas Soome                 m->mDNSStats.InterfaceUpFlap++;
13109c65ebfc7SToomas Soome                 break;
13110*472cd20dSToomas Soome #endif
13111c65ebfc7SToomas Soome 
13112c65ebfc7SToomas Soome             case NormalActivation:
13113c65ebfc7SToomas Soome             default:
13114c65ebfc7SToomas Soome                 probedelay = mDNSPlatformOneSecond / 2;
13115c65ebfc7SToomas Soome                 numannounce = InitialAnnounceCount;
13116c65ebfc7SToomas Soome                 break;
13117c65ebfc7SToomas Soome         }
13118c65ebfc7SToomas Soome 
13119*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13120*472cd20dSToomas Soome             "Interface probe will be delayed - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR ", probe delay: %d",
13121*472cd20dSToomas Soome             set->ifname, &set->ip, probedelay);
13122c65ebfc7SToomas Soome 
13123c65ebfc7SToomas Soome         // No probe or sending suppression on DirectLink type interfaces.
13124c65ebfc7SToomas Soome         if (activationSpeed == FastActivation)
13125c65ebfc7SToomas Soome         {
13126c65ebfc7SToomas Soome             m->SuppressSending = 0;
13127c65ebfc7SToomas Soome             m->SuppressProbes = 0;
13128c65ebfc7SToomas Soome         }
13129c65ebfc7SToomas Soome         else
13130c65ebfc7SToomas Soome         {
13131c65ebfc7SToomas Soome 	        // Use a small amount of randomness:
13132c65ebfc7SToomas Soome 	        // In the case of a network administrator turning on an Ethernet hub so that all the
13133c65ebfc7SToomas Soome 	        // connected machines establish link at exactly the same time, we don't want them all
13134c65ebfc7SToomas Soome 	        // to go and hit the network with identical queries at exactly the same moment.
13135c65ebfc7SToomas Soome 	        // We set a random delay of up to InitialQuestionInterval (1/3 second).
13136c65ebfc7SToomas Soome 	        // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13137c65ebfc7SToomas Soome 	        // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13138c65ebfc7SToomas Soome 	        // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13139c65ebfc7SToomas Soome 	        // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13140c65ebfc7SToomas Soome 	        // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13141c65ebfc7SToomas Soome             if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
13142c65ebfc7SToomas Soome 
13143c65ebfc7SToomas Soome             if (m->SuppressProbes == 0 ||
13144c65ebfc7SToomas Soome                 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
13145c65ebfc7SToomas Soome                 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
13146c65ebfc7SToomas Soome         }
13147c65ebfc7SToomas Soome 
13148c65ebfc7SToomas Soome         // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13149c65ebfc7SToomas Soome         // it here also handles the wake up case as the network link comes UP after waking causing
13150c65ebfc7SToomas Soome         // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13151c65ebfc7SToomas Soome         // that the network link comes UP after 60 seconds and we never set the OWNER option
13152c65ebfc7SToomas Soome         m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
13153*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Setting AnnounceOwner");
13154c65ebfc7SToomas Soome 
13155c65ebfc7SToomas Soome         m->mDNSStats.InterfaceUp++;
13156c65ebfc7SToomas Soome         for (q = m->Questions; q; q=q->next)                                // Scan our list of questions
13157c65ebfc7SToomas Soome         {
13158c65ebfc7SToomas Soome             if (mDNSOpaque16IsZero(q->TargetQID))
13159c65ebfc7SToomas Soome             {
13160c65ebfc7SToomas Soome                 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)      // If non-specific Q, or Q on this specific interface,
13161c65ebfc7SToomas Soome                 {                                                               // then reactivate this question
13162*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13163c65ebfc7SToomas Soome                     // If flapping, delay between first and second queries is nine seconds instead of one second
13164c65ebfc7SToomas Soome                     mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
13165c65ebfc7SToomas Soome                     mDNSs32 initial  = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
13166c65ebfc7SToomas Soome                     mDNSs32 qdelay   = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0;
13167*472cd20dSToomas Soome                     if (dodelay)
13168*472cd20dSToomas Soome                     {
13169*472cd20dSToomas Soome                         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13170*472cd20dSToomas Soome                             "No cache records expired for the question " PRI_DM_NAME " (" PUB_S ");"
13171*472cd20dSToomas Soome                             " delaying it by %d seconds", DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), qdelay);
13172*472cd20dSToomas Soome                     }
13173*472cd20dSToomas Soome #else
13174*472cd20dSToomas Soome                     mDNSs32 initial  = InitialQuestionInterval;
13175*472cd20dSToomas Soome                     mDNSs32 qdelay   = 0;
13176*472cd20dSToomas Soome #endif
13177c65ebfc7SToomas Soome 
13178c65ebfc7SToomas Soome                     if (!q->ThisQInterval || q->ThisQInterval > initial)
13179c65ebfc7SToomas Soome                     {
13180c65ebfc7SToomas Soome                         q->ThisQInterval  = initial;
13181c65ebfc7SToomas Soome                         q->RequestUnicast = kDefaultRequestUnicastCount;
13182c65ebfc7SToomas Soome                     }
13183c65ebfc7SToomas Soome                     q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
13184c65ebfc7SToomas Soome                     q->RecentAnswerPkts = 0;
13185c65ebfc7SToomas Soome                     SetNextQueryTime(m,q);
13186c65ebfc7SToomas Soome                 }
13187c65ebfc7SToomas Soome             }
13188c65ebfc7SToomas Soome         }
13189c65ebfc7SToomas Soome 
13190c65ebfc7SToomas Soome         // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13191c65ebfc7SToomas Soome         // we now need them to re-probe if necessary, and then re-announce.
13192c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
13193c65ebfc7SToomas Soome         {
13194c65ebfc7SToomas Soome             if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
13195c65ebfc7SToomas Soome             {
13196c65ebfc7SToomas Soome                 mDNSCoreRestartRegistration(m, rr, numannounce);
13197c65ebfc7SToomas Soome             }
13198c65ebfc7SToomas Soome         }
13199c65ebfc7SToomas Soome     }
13200c65ebfc7SToomas Soome 
13201c65ebfc7SToomas Soome     RestartRecordGetZoneData(m);
13202c65ebfc7SToomas Soome 
13203c65ebfc7SToomas Soome     mDNS_UpdateAllowSleep(m);
13204c65ebfc7SToomas Soome 
13205c65ebfc7SToomas Soome     mDNS_Unlock(m);
13206c65ebfc7SToomas Soome     return(mStatus_NoError);
13207c65ebfc7SToomas Soome }
13208c65ebfc7SToomas Soome 
AdjustAddressRecordSetsEx(mDNS * const m,NetworkInterfaceInfo * removedIntf,mDNSBool forRandHostname)13209*472cd20dSToomas Soome mDNSlocal void AdjustAddressRecordSetsEx(mDNS *const m, NetworkInterfaceInfo *removedIntf, mDNSBool forRandHostname)
13210*472cd20dSToomas Soome {
13211*472cd20dSToomas Soome     NetworkInterfaceInfo *intf;
13212*472cd20dSToomas Soome     const AuthRecord *oldAR;
13213*472cd20dSToomas Soome     AuthRecord *newAR;
13214*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13215*472cd20dSToomas Soome     if (mDNSPlatformInterfaceIsAWDL(removedIntf->InterfaceID)) return;
13216*472cd20dSToomas Soome #endif
13217*472cd20dSToomas Soome     oldAR = GetInterfaceAddressRecord(removedIntf, forRandHostname);
13218*472cd20dSToomas Soome     newAR = GetFirstAddressRecordEx(m, forRandHostname);
13219*472cd20dSToomas Soome     for (intf = m->HostInterfaces; intf; intf = intf->next)
13220*472cd20dSToomas Soome     {
13221*472cd20dSToomas Soome         AuthRecord *ar;
13222*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13223*472cd20dSToomas Soome         if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
13224*472cd20dSToomas Soome #endif
13225*472cd20dSToomas Soome         ar = GetInterfaceAddressRecord(intf, forRandHostname);
13226*472cd20dSToomas Soome         if (ar->RRSet == oldAR)
13227*472cd20dSToomas Soome         {
13228*472cd20dSToomas Soome             ar->RRSet = newAR ? newAR : ar;
13229*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Changed RRSet for " PRI_S, ARDisplayString(m, ar));
13230*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "New RRSet:        " PRI_S, ARDisplayString(m, ar->RRSet));
13231*472cd20dSToomas Soome         }
13232*472cd20dSToomas Soome     }
13233*472cd20dSToomas Soome }
13234*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13235*472cd20dSToomas Soome #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue)
13236*472cd20dSToomas Soome #endif
13237*472cd20dSToomas Soome #define AdjustAddressRecordSets(M, REMOVED_INTF)                AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse)
13238*472cd20dSToomas Soome 
13239c65ebfc7SToomas Soome // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13240c65ebfc7SToomas Soome // the record list and/or question list.
13241c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
mDNS_DeregisterInterface(mDNS * const m,NetworkInterfaceInfo * set,InterfaceActivationSpeed activationSpeed)13242c65ebfc7SToomas Soome mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13243c65ebfc7SToomas Soome {
13244*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13245*472cd20dSToomas Soome     (void)activationSpeed;   // Unused parameter
13246*472cd20dSToomas Soome #endif
13247c65ebfc7SToomas Soome     NetworkInterfaceInfo **p = &m->HostInterfaces;
13248c65ebfc7SToomas Soome     mDNSBool revalidate = mDNSfalse;
13249c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf;
13250c65ebfc7SToomas Soome 
13251c65ebfc7SToomas Soome     mDNS_Lock(m);
13252c65ebfc7SToomas Soome 
13253c65ebfc7SToomas Soome     // Find this record in our list
13254c65ebfc7SToomas Soome     while (*p && *p != set) p=&(*p)->next;
13255*472cd20dSToomas Soome     if (!*p)
13256*472cd20dSToomas Soome     {
13257*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "NetworkInterfaceInfo not found in list");
13258*472cd20dSToomas Soome         mDNS_Unlock(m);
13259*472cd20dSToomas Soome         return;
13260*472cd20dSToomas Soome     }
13261c65ebfc7SToomas Soome 
13262c65ebfc7SToomas Soome     mDNS_DeactivateNetWake_internal(m, set);
13263c65ebfc7SToomas Soome 
13264c65ebfc7SToomas Soome     // Unlink this record from our list
13265c65ebfc7SToomas Soome     *p = (*p)->next;
13266c65ebfc7SToomas Soome     set->next = mDNSNULL;
13267c65ebfc7SToomas Soome 
13268c65ebfc7SToomas Soome     if (!set->InterfaceActive)
13269c65ebfc7SToomas Soome     {
13270c65ebfc7SToomas Soome         // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13271c65ebfc7SToomas Soome         for (intf = m->HostInterfaces; intf; intf = intf->next)
13272c65ebfc7SToomas Soome             if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13273c65ebfc7SToomas Soome                 UpdateInterfaceProtocols(m, intf);
13274c65ebfc7SToomas Soome     }
13275c65ebfc7SToomas Soome     else
13276c65ebfc7SToomas Soome     {
13277c65ebfc7SToomas Soome         intf = FirstInterfaceForID(m, set->InterfaceID);
13278c65ebfc7SToomas Soome         if (intf)
13279c65ebfc7SToomas Soome         {
13280*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13281*472cd20dSToomas Soome                 "Another representative of InterfaceID exists - ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13282*472cd20dSToomas Soome                 IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13283c65ebfc7SToomas Soome             if (intf->InterfaceActive)
13284*472cd20dSToomas Soome             {
13285*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13286*472cd20dSToomas Soome                     "intf->InterfaceActive already set for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13287*472cd20dSToomas Soome                     set->ifname, &set->ip);
13288*472cd20dSToomas Soome             }
13289c65ebfc7SToomas Soome             intf->InterfaceActive = mDNStrue;
13290c65ebfc7SToomas Soome             UpdateInterfaceProtocols(m, intf);
13291c65ebfc7SToomas Soome 
13292c65ebfc7SToomas Soome             if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13293c65ebfc7SToomas Soome 
13294c65ebfc7SToomas Soome             // See if another representative *of the same type* exists. If not, we mave have gone from
13295c65ebfc7SToomas Soome             // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13296c65ebfc7SToomas Soome             for (intf = m->HostInterfaces; intf; intf = intf->next)
13297c65ebfc7SToomas Soome                 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13298c65ebfc7SToomas Soome                     break;
13299c65ebfc7SToomas Soome             if (!intf) revalidate = mDNStrue;
13300c65ebfc7SToomas Soome         }
13301c65ebfc7SToomas Soome         else
13302c65ebfc7SToomas Soome         {
13303c65ebfc7SToomas Soome             mDNSu32 slot;
13304c65ebfc7SToomas Soome             CacheGroup *cg;
13305c65ebfc7SToomas Soome             CacheRecord *rr;
13306c65ebfc7SToomas Soome             DNSQuestion *q;
13307*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13308*472cd20dSToomas Soome             mDNSu32     cacheHitMulticastCount = 0;
13309*472cd20dSToomas Soome             mDNSu32     cacheMissMulticastCount = 0;
13310*472cd20dSToomas Soome             mDNSu32     cacheHitUnicastCount = 0;
13311*472cd20dSToomas Soome             mDNSu32     cacheMissUnicastCount = 0;
13312*472cd20dSToomas Soome #endif
13313*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13314*472cd20dSToomas Soome                 "Last representative of InterfaceID deregistered; marking questions etc. dormant - "
13315*472cd20dSToomas Soome                 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13316*472cd20dSToomas Soome                 IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13317c65ebfc7SToomas Soome 
13318c65ebfc7SToomas Soome             m->mDNSStats.InterfaceDown++;
13319c65ebfc7SToomas Soome 
13320*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13321c65ebfc7SToomas Soome             if (set->McastTxRx && (activationSpeed == SlowActivation))
13322c65ebfc7SToomas Soome             {
13323*472cd20dSToomas Soome                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13324*472cd20dSToomas Soome                     "Frequent transitions for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13325*472cd20dSToomas Soome                     set->ifname, &set->ip);
13326c65ebfc7SToomas Soome                 m->mDNSStats.InterfaceDownFlap++;
13327c65ebfc7SToomas Soome             }
13328*472cd20dSToomas Soome #endif
13329c65ebfc7SToomas Soome 
13330c65ebfc7SToomas Soome             // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13331c65ebfc7SToomas Soome             // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13332c65ebfc7SToomas Soome             for (q = m->Questions; q; q=q->next)
13333c65ebfc7SToomas Soome             {
13334*472cd20dSToomas Soome                 if (mDNSOpaque16IsZero(q->TargetQID))                   // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13335*472cd20dSToomas Soome                 {
13336c65ebfc7SToomas Soome                     if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13337c65ebfc7SToomas Soome                     if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13338c65ebfc7SToomas Soome                     {
13339c65ebfc7SToomas Soome                         q->FlappingInterface2 = q->FlappingInterface1;
13340c65ebfc7SToomas Soome                         q->FlappingInterface1 = set->InterfaceID;       // Keep history of the last two interfaces to go away
13341c65ebfc7SToomas Soome                     }
13342c65ebfc7SToomas Soome                 }
13343*472cd20dSToomas Soome             }
13344c65ebfc7SToomas Soome 
13345c65ebfc7SToomas Soome             // 2. Flush any cache records received on this interface
13346c65ebfc7SToomas Soome             revalidate = mDNSfalse;     // Don't revalidate if we're flushing the records
13347c65ebfc7SToomas Soome             FORALL_CACHERECORDS(slot, cg, rr)
13348c65ebfc7SToomas Soome             {
13349c65ebfc7SToomas Soome                 if (rr->resrec.InterfaceID == set->InterfaceID)
13350c65ebfc7SToomas Soome                 {
13351*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13352c65ebfc7SToomas Soome                     // If this interface is deemed flapping,
13353c65ebfc7SToomas Soome                     // postpone deleting the cache records in case the interface comes back again
13354c65ebfc7SToomas Soome                     if (set->McastTxRx && (activationSpeed == SlowActivation))
13355c65ebfc7SToomas Soome                     {
13356c65ebfc7SToomas Soome                         // For a flapping interface we want these records to go away after
13357c65ebfc7SToomas Soome                         // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13358c65ebfc7SToomas Soome                         mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13359c65ebfc7SToomas Soome                         // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13360c65ebfc7SToomas Soome                         // if the interface does come back, any relevant questions will be reactivated anyway
13361c65ebfc7SToomas Soome                         rr->UnansweredQueries = MaxUnansweredQueries;
13362c65ebfc7SToomas Soome                     }
13363c65ebfc7SToomas Soome                     else
13364*472cd20dSToomas Soome #endif
13365c65ebfc7SToomas Soome                     {
13366*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13367*472cd20dSToomas Soome                         if (rr->LastCachedAnswerTime)
13368*472cd20dSToomas Soome                         {
13369*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13370*472cd20dSToomas Soome                             if (rr->resrec.dnsservice)  cacheHitUnicastCount++;
13371*472cd20dSToomas Soome #else
13372*472cd20dSToomas Soome                             if (rr->resrec.rDNSServer)  cacheHitUnicastCount++;
13373*472cd20dSToomas Soome #endif
13374*472cd20dSToomas Soome                             else                        cacheHitMulticastCount++;
13375*472cd20dSToomas Soome                         }
13376*472cd20dSToomas Soome                         else
13377*472cd20dSToomas Soome                         {
13378*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13379*472cd20dSToomas Soome                             if (rr->resrec.dnsservice)  cacheMissUnicastCount++;
13380*472cd20dSToomas Soome #else
13381*472cd20dSToomas Soome                             if (rr->resrec.rDNSServer)  cacheMissUnicastCount++;
13382*472cd20dSToomas Soome #endif
13383*472cd20dSToomas Soome                             else                        cacheMissMulticastCount++;
13384*472cd20dSToomas Soome                         }
13385*472cd20dSToomas Soome #endif
13386c65ebfc7SToomas Soome                         mDNS_PurgeCacheResourceRecord(m, rr);
13387c65ebfc7SToomas Soome                     }
13388c65ebfc7SToomas Soome                 }
13389c65ebfc7SToomas Soome             }
13390*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13391*472cd20dSToomas Soome             dnssd_analytics_update_cache_usage_counts(cacheHitMulticastCount, cacheMissMulticastCount, cacheHitUnicastCount, cacheMissUnicastCount);
13392*472cd20dSToomas Soome #endif
13393c65ebfc7SToomas Soome         }
13394c65ebfc7SToomas Soome     }
13395c65ebfc7SToomas Soome 
13396c65ebfc7SToomas Soome     // If we still have address records referring to this one, update them.
13397c65ebfc7SToomas Soome     // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13398*472cd20dSToomas Soome     // so the call to AdjustAddressRecordSets*() won’t accidentally find it.
13399*472cd20dSToomas Soome     AdjustAddressRecordSets(m, set);
13400*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13401*472cd20dSToomas Soome     AdjustAddressRecordSetsForRandHostname(m, set);
13402*472cd20dSToomas Soome #endif
13403c65ebfc7SToomas Soome 
13404c65ebfc7SToomas Soome     // If we were advertising on this interface, deregister those address and reverse-lookup records now
13405*472cd20dSToomas Soome     if (set->Advertise) DeadvertiseInterface(m, set, kDeadvertiseFlag_All);
13406c65ebfc7SToomas Soome 
13407c65ebfc7SToomas Soome     // If we have any cache records received on this interface that went away, then re-verify them.
13408c65ebfc7SToomas Soome     // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13409c65ebfc7SToomas Soome     // giving the false impression that there's an active representative of this interface when there really isn't.
13410c65ebfc7SToomas Soome     // Don't need to do this when shutting down, because *all* interfaces are about to go away
13411c65ebfc7SToomas Soome     if (revalidate && !m->ShutdownTime)
13412c65ebfc7SToomas Soome     {
13413c65ebfc7SToomas Soome         mDNSu32 slot;
13414c65ebfc7SToomas Soome         CacheGroup *cg;
13415c65ebfc7SToomas Soome         CacheRecord *rr;
13416c65ebfc7SToomas Soome         FORALL_CACHERECORDS(slot, cg, rr)
13417c65ebfc7SToomas Soome         if (rr->resrec.InterfaceID == set->InterfaceID)
13418c65ebfc7SToomas Soome             mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13419c65ebfc7SToomas Soome     }
13420c65ebfc7SToomas Soome 
13421c65ebfc7SToomas Soome     mDNS_UpdateAllowSleep(m);
13422c65ebfc7SToomas Soome 
13423c65ebfc7SToomas Soome     mDNS_Unlock(m);
13424c65ebfc7SToomas Soome }
13425c65ebfc7SToomas Soome 
ServiceCallback(mDNS * const m,AuthRecord * const rr,mStatus result)13426c65ebfc7SToomas Soome mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13427c65ebfc7SToomas Soome {
13428c65ebfc7SToomas Soome     ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13429c65ebfc7SToomas Soome     (void)m;    // Unused parameter
13430c65ebfc7SToomas Soome 
13431c65ebfc7SToomas Soome     #if MDNS_DEBUGMSGS
13432c65ebfc7SToomas Soome     {
13433c65ebfc7SToomas Soome         char *msg = "Unknown result";
13434c65ebfc7SToomas Soome         if      (result == mStatus_NoError) msg = "Name Registered";
13435c65ebfc7SToomas Soome         else if (result == mStatus_NameConflict) msg = "Name Conflict";
13436c65ebfc7SToomas Soome         else if (result == mStatus_MemFree) msg = "Memory Free";
13437c65ebfc7SToomas Soome         debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13438c65ebfc7SToomas Soome     }
13439c65ebfc7SToomas Soome     #endif
13440c65ebfc7SToomas Soome 
13441c65ebfc7SToomas Soome     // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13442c65ebfc7SToomas Soome     if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13443c65ebfc7SToomas Soome 
13444c65ebfc7SToomas Soome     // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13445c65ebfc7SToomas Soome     if (result == mStatus_NameConflict)
13446c65ebfc7SToomas Soome     {
13447c65ebfc7SToomas Soome         sr->Conflict = mDNStrue;                // Record that this service set had a conflict
13448c65ebfc7SToomas Soome         mDNS_DeregisterService(m, sr);          // Unlink the records from our list
13449c65ebfc7SToomas Soome         return;
13450c65ebfc7SToomas Soome     }
13451c65ebfc7SToomas Soome 
13452c65ebfc7SToomas Soome     if (result == mStatus_MemFree)
13453c65ebfc7SToomas Soome     {
13454c65ebfc7SToomas Soome         // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13455c65ebfc7SToomas Soome         // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13456c65ebfc7SToomas Soome         // every record is finished cleaning up.
13457c65ebfc7SToomas Soome         mDNSu32 i;
13458c65ebfc7SToomas Soome         ExtraResourceRecord *e = sr->Extras;
13459c65ebfc7SToomas Soome 
13460c65ebfc7SToomas Soome         if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13461c65ebfc7SToomas Soome         if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13462c65ebfc7SToomas Soome         if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13463c65ebfc7SToomas Soome         if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13464c65ebfc7SToomas Soome         for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13465c65ebfc7SToomas Soome 
13466c65ebfc7SToomas Soome         while (e)
13467c65ebfc7SToomas Soome         {
13468c65ebfc7SToomas Soome             if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13469c65ebfc7SToomas Soome             e = e->next;
13470c65ebfc7SToomas Soome         }
13471c65ebfc7SToomas Soome 
13472c65ebfc7SToomas Soome         // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13473c65ebfc7SToomas Soome         // then we can now report the NameConflict to the client
13474c65ebfc7SToomas Soome         if (sr->Conflict) result = mStatus_NameConflict;
13475c65ebfc7SToomas Soome 
13476c65ebfc7SToomas Soome     }
13477c65ebfc7SToomas Soome 
13478c65ebfc7SToomas Soome     LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13479c65ebfc7SToomas Soome     // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13480c65ebfc7SToomas Soome     // function is allowed to do anything, including deregistering this service and freeing its memory.
13481c65ebfc7SToomas Soome     if (sr->ServiceCallback)
13482c65ebfc7SToomas Soome         sr->ServiceCallback(m, sr, result);
13483c65ebfc7SToomas Soome }
13484c65ebfc7SToomas Soome 
NSSCallback(mDNS * const m,AuthRecord * const rr,mStatus result)13485c65ebfc7SToomas Soome mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13486c65ebfc7SToomas Soome {
13487c65ebfc7SToomas Soome     ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13488c65ebfc7SToomas Soome     if (sr->ServiceCallback)
13489c65ebfc7SToomas Soome         sr->ServiceCallback(m, sr, result);
13490c65ebfc7SToomas Soome }
13491c65ebfc7SToomas Soome 
13492c65ebfc7SToomas Soome 
13493c65ebfc7SToomas Soome // Derive AuthRecType from the kDNSServiceFlags* values.
setAuthRecType(mDNSInterfaceID InterfaceID,mDNSu32 flags)13494c65ebfc7SToomas Soome mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13495c65ebfc7SToomas Soome {
13496c65ebfc7SToomas Soome     AuthRecType artype;
13497c65ebfc7SToomas Soome 
13498c65ebfc7SToomas Soome     if (InterfaceID == mDNSInterface_LocalOnly)
13499c65ebfc7SToomas Soome         artype = AuthRecordLocalOnly;
13500c65ebfc7SToomas Soome     else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13501c65ebfc7SToomas Soome         artype = AuthRecordP2P;
13502c65ebfc7SToomas Soome     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
13503c65ebfc7SToomas Soome             && (flags & kDNSServiceFlagsIncludeAWDL))
13504c65ebfc7SToomas Soome         artype = AuthRecordAnyIncludeAWDLandP2P;
13505c65ebfc7SToomas Soome     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
13506c65ebfc7SToomas Soome         artype = AuthRecordAnyIncludeP2P;
13507c65ebfc7SToomas Soome     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
13508c65ebfc7SToomas Soome         artype = AuthRecordAnyIncludeAWDL;
13509c65ebfc7SToomas Soome     else
13510c65ebfc7SToomas Soome         artype = AuthRecordAny;
13511c65ebfc7SToomas Soome 
13512c65ebfc7SToomas Soome     return artype;
13513c65ebfc7SToomas Soome }
13514c65ebfc7SToomas Soome 
13515c65ebfc7SToomas Soome // Note:
13516c65ebfc7SToomas Soome // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13517c65ebfc7SToomas Soome // Type is service type (e.g. "_ipp._tcp.")
13518c65ebfc7SToomas Soome // Domain is fully qualified domain name (i.e. ending with a null label)
13519c65ebfc7SToomas Soome // We always register a TXT, even if it is empty (so that clients are not
13520c65ebfc7SToomas Soome // left waiting forever looking for a nonexistent record.)
13521c65ebfc7SToomas Soome // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13522c65ebfc7SToomas Soome // then the default host name (m->MulticastHostname) is automatically used
13523c65ebfc7SToomas Soome // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
mDNS_RegisterService(mDNS * const m,ServiceRecordSet * sr,const domainlabel * const name,const domainname * const type,const domainname * const domain,const domainname * const host,mDNSIPPort port,RData * const txtrdata,const mDNSu8 txtinfo[],mDNSu16 txtlen,AuthRecord * SubTypes,mDNSu32 NumSubTypes,mDNSInterfaceID InterfaceID,mDNSServiceCallback Callback,void * Context,mDNSu32 flags)13524c65ebfc7SToomas Soome mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13525c65ebfc7SToomas Soome                                         const domainlabel *const name, const domainname *const type, const domainname *const domain,
135263b436d06SToomas Soome                                         const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13527c65ebfc7SToomas Soome                                         AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13528c65ebfc7SToomas Soome                                         mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13529c65ebfc7SToomas Soome {
13530c65ebfc7SToomas Soome     mStatus err;
13531c65ebfc7SToomas Soome     mDNSu32 i;
13532c65ebfc7SToomas Soome     AuthRecType artype;
13533c65ebfc7SToomas Soome     mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13534c65ebfc7SToomas Soome 
13535c65ebfc7SToomas Soome     sr->ServiceCallback = Callback;
13536c65ebfc7SToomas Soome     sr->ServiceContext  = Context;
13537c65ebfc7SToomas Soome     sr->Conflict        = mDNSfalse;
13538c65ebfc7SToomas Soome 
13539c65ebfc7SToomas Soome     sr->Extras          = mDNSNULL;
13540c65ebfc7SToomas Soome     sr->NumSubTypes     = NumSubTypes;
13541c65ebfc7SToomas Soome     sr->SubTypes        = SubTypes;
13542c65ebfc7SToomas Soome     sr->flags           = flags;
13543c65ebfc7SToomas Soome 
13544c65ebfc7SToomas Soome     artype = setAuthRecType(InterfaceID, flags);
13545c65ebfc7SToomas Soome 
13546c65ebfc7SToomas Soome     // Initialize the AuthRecord objects to sane values
13547c65ebfc7SToomas Soome     // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13548c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13549c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared,   artype, ServiceCallback, sr);
13550c65ebfc7SToomas Soome 
13551c65ebfc7SToomas Soome     if (flags & kDNSServiceFlagsWakeOnlyService)
13552c65ebfc7SToomas Soome     {
13553c65ebfc7SToomas Soome         sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13554c65ebfc7SToomas Soome     }
13555c65ebfc7SToomas Soome 
13556*472cd20dSToomas Soome     mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, recordType, artype, ServiceCallback, sr);
135573b436d06SToomas Soome     mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr);
13558c65ebfc7SToomas Soome 
13559c65ebfc7SToomas Soome     // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13560c65ebfc7SToomas Soome     if (mDNSIPPortIsZero(port))
13561c65ebfc7SToomas Soome         return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13562c65ebfc7SToomas Soome 
13563c65ebfc7SToomas Soome     // If the caller is registering an oversized TXT record,
13564c65ebfc7SToomas Soome     // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13565c65ebfc7SToomas Soome     if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13566c65ebfc7SToomas Soome         sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13567c65ebfc7SToomas Soome 
13568c65ebfc7SToomas Soome     // Set up the record names
13569c65ebfc7SToomas Soome     // For now we only create an advisory record for the main type, not for subtypes
13570c65ebfc7SToomas Soome     // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13571c65ebfc7SToomas Soome     if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13572c65ebfc7SToomas Soome         return(mStatus_BadParamErr);
13573c65ebfc7SToomas Soome     if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13574c65ebfc7SToomas Soome     if (ConstructServiceName(&sr->RR_SRV.namestorage, name,     type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13575c65ebfc7SToomas Soome     AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13576c65ebfc7SToomas Soome 
13577c65ebfc7SToomas Soome     // 1. Set up the ADV record rdata to advertise our service type
13578c65ebfc7SToomas Soome     AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13579c65ebfc7SToomas Soome 
13580c65ebfc7SToomas Soome     // 2. Set up the PTR record rdata to point to our service name
13581c65ebfc7SToomas Soome     // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13582c65ebfc7SToomas Soome     // Note: uDNS registration code assumes that Additional1 points to the SRV record
13583c65ebfc7SToomas Soome     AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13584c65ebfc7SToomas Soome     sr->RR_PTR.Additional1 = &sr->RR_SRV;
13585c65ebfc7SToomas Soome     sr->RR_PTR.Additional2 = &sr->RR_TXT;
13586c65ebfc7SToomas Soome 
13587c65ebfc7SToomas Soome     // 2a. Set up any subtype PTRs to point to our service name
13588c65ebfc7SToomas Soome     // If the client is using subtypes, it is the client's responsibility to have
13589c65ebfc7SToomas Soome     // already set the first label of the record name to the subtype being registered
13590c65ebfc7SToomas Soome     for (i=0; i<NumSubTypes; i++)
13591c65ebfc7SToomas Soome     {
13592c65ebfc7SToomas Soome         domainname st;
13593c65ebfc7SToomas Soome         AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13594c65ebfc7SToomas Soome         st.c[1+st.c[0]] = 0;            // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13595c65ebfc7SToomas Soome         AppendDomainName(&st, type);
13596c65ebfc7SToomas Soome         mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13597c65ebfc7SToomas Soome         if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13598c65ebfc7SToomas Soome         AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13599c65ebfc7SToomas Soome         sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13600c65ebfc7SToomas Soome         sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13601c65ebfc7SToomas Soome     }
13602c65ebfc7SToomas Soome 
13603c65ebfc7SToomas Soome     // 3. Set up the SRV record rdata.
13604c65ebfc7SToomas Soome     sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13605c65ebfc7SToomas Soome     sr->RR_SRV.resrec.rdata->u.srv.weight   = 0;
13606c65ebfc7SToomas Soome     sr->RR_SRV.resrec.rdata->u.srv.port     = port;
13607c65ebfc7SToomas Soome 
13608c65ebfc7SToomas Soome     // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13609c65ebfc7SToomas Soome     if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13610c65ebfc7SToomas Soome     else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13611c65ebfc7SToomas Soome 
13612c65ebfc7SToomas Soome     // 4. Set up the TXT record rdata,
13613c65ebfc7SToomas Soome     // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13614c65ebfc7SToomas Soome     // Note: uDNS registration code assumes that DependentOn points to the SRV record
13615c65ebfc7SToomas Soome     if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13616c65ebfc7SToomas Soome     else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13617c65ebfc7SToomas Soome     {
13618c65ebfc7SToomas Soome         sr->RR_TXT.resrec.rdlength = txtlen;
13619c65ebfc7SToomas Soome         if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13620c65ebfc7SToomas Soome         mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13621c65ebfc7SToomas Soome     }
13622c65ebfc7SToomas Soome     sr->RR_TXT.DependentOn = &sr->RR_SRV;
13623c65ebfc7SToomas Soome 
13624c65ebfc7SToomas Soome     mDNS_Lock(m);
13625c65ebfc7SToomas Soome     // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13626c65ebfc7SToomas Soome     // that if the SRV cannot find a target, rest of the records that belong to this service
13627c65ebfc7SToomas Soome     // will not be activated.
13628c65ebfc7SToomas Soome     err = mDNS_Register_internal(m, &sr->RR_SRV);
13629c65ebfc7SToomas Soome     // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13630c65ebfc7SToomas Soome     // any list and hence no need to deregister. We could probably do similar checks for other
13631c65ebfc7SToomas Soome     // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13632c65ebfc7SToomas Soome     if (err)
13633c65ebfc7SToomas Soome     {
13634c65ebfc7SToomas Soome         mDNS_Unlock(m);
13635c65ebfc7SToomas Soome         return err;
13636c65ebfc7SToomas Soome     }
13637c65ebfc7SToomas Soome     if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13638c65ebfc7SToomas Soome     // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13639c65ebfc7SToomas Soome     // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13640c65ebfc7SToomas Soome     // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13641c65ebfc7SToomas Soome     // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13642c65ebfc7SToomas Soome     // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13643c65ebfc7SToomas Soome     if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13644c65ebfc7SToomas Soome     for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13645c65ebfc7SToomas Soome     if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13646c65ebfc7SToomas Soome 
13647c65ebfc7SToomas Soome     mDNS_Unlock(m);
13648c65ebfc7SToomas Soome 
13649c65ebfc7SToomas Soome     if (err) mDNS_DeregisterService(m, sr);
13650c65ebfc7SToomas Soome     return(err);
13651c65ebfc7SToomas Soome }
13652c65ebfc7SToomas Soome 
mDNS_AddRecordToService(mDNS * const m,ServiceRecordSet * sr,ExtraResourceRecord * extra,RData * rdata,mDNSu32 ttl,mDNSu32 flags)13653c65ebfc7SToomas Soome mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13654c65ebfc7SToomas Soome                                            ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 flags)
13655c65ebfc7SToomas Soome {
13656c65ebfc7SToomas Soome     ExtraResourceRecord **e;
13657c65ebfc7SToomas Soome     mStatus status;
13658c65ebfc7SToomas Soome     AuthRecType artype;
13659c65ebfc7SToomas Soome     mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13660c65ebfc7SToomas Soome     ResourceRecord *rr;
13661c65ebfc7SToomas Soome 
13662c65ebfc7SToomas Soome     artype = setAuthRecType(InterfaceID, flags);
13663c65ebfc7SToomas Soome 
13664c65ebfc7SToomas Soome     extra->next = mDNSNULL;
13665c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13666c65ebfc7SToomas Soome                              extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13667c65ebfc7SToomas Soome     AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13668c65ebfc7SToomas Soome 
13669c65ebfc7SToomas Soome     mDNS_Lock(m);
13670c65ebfc7SToomas Soome     rr = mDNSNULL;
13671c65ebfc7SToomas Soome     if (extra->r.resrec.rrtype == kDNSType_TXT)
13672c65ebfc7SToomas Soome     {
13673c65ebfc7SToomas Soome         if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec;
13674c65ebfc7SToomas Soome     }
13675c65ebfc7SToomas Soome     else if (extra->r.resrec.rrtype == kDNSType_SRV)
13676c65ebfc7SToomas Soome     {
13677c65ebfc7SToomas Soome         if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec;
13678c65ebfc7SToomas Soome     }
13679c65ebfc7SToomas Soome 
13680c65ebfc7SToomas Soome     if (!rr)
13681c65ebfc7SToomas Soome     {
13682c65ebfc7SToomas Soome         ExtraResourceRecord *srExtra;
13683c65ebfc7SToomas Soome 
13684c65ebfc7SToomas Soome         for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next)
13685c65ebfc7SToomas Soome         {
13686c65ebfc7SToomas Soome             if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask))
13687c65ebfc7SToomas Soome             {
13688c65ebfc7SToomas Soome                 rr = &srExtra->r.resrec;
13689c65ebfc7SToomas Soome                 break;
13690c65ebfc7SToomas Soome             }
13691c65ebfc7SToomas Soome         }
13692c65ebfc7SToomas Soome     }
13693c65ebfc7SToomas Soome 
13694c65ebfc7SToomas Soome     if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl))
13695c65ebfc7SToomas Soome     {
13696c65ebfc7SToomas Soome         LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13697c65ebfc7SToomas Soome             extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec));
13698c65ebfc7SToomas Soome         extra->r.resrec.rroriginalttl = rr->rroriginalttl;
13699c65ebfc7SToomas Soome     }
13700c65ebfc7SToomas Soome 
13701c65ebfc7SToomas Soome     e = &sr->Extras;
13702c65ebfc7SToomas Soome     while (*e) e = &(*e)->next;
13703c65ebfc7SToomas Soome 
13704c65ebfc7SToomas Soome     extra->r.DependentOn = &sr->RR_SRV;
13705c65ebfc7SToomas Soome 
13706c65ebfc7SToomas Soome     debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13707c65ebfc7SToomas Soome            extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13708c65ebfc7SToomas Soome 
13709c65ebfc7SToomas Soome     status = mDNS_Register_internal(m, &extra->r);
13710c65ebfc7SToomas Soome     if (status == mStatus_NoError) *e = extra;
13711c65ebfc7SToomas Soome 
13712c65ebfc7SToomas Soome     mDNS_Unlock(m);
13713c65ebfc7SToomas Soome     return(status);
13714c65ebfc7SToomas Soome }
13715c65ebfc7SToomas Soome 
mDNS_RemoveRecordFromService(mDNS * const m,ServiceRecordSet * sr,ExtraResourceRecord * extra,mDNSRecordCallback MemFreeCallback,void * Context)13716c65ebfc7SToomas Soome mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13717c65ebfc7SToomas Soome                                                 mDNSRecordCallback MemFreeCallback, void *Context)
13718c65ebfc7SToomas Soome {
13719c65ebfc7SToomas Soome     ExtraResourceRecord **e;
13720c65ebfc7SToomas Soome     mStatus status;
13721c65ebfc7SToomas Soome 
13722c65ebfc7SToomas Soome     mDNS_Lock(m);
13723c65ebfc7SToomas Soome     e = &sr->Extras;
13724c65ebfc7SToomas Soome     while (*e && *e != extra) e = &(*e)->next;
13725c65ebfc7SToomas Soome     if (!*e)
13726c65ebfc7SToomas Soome     {
13727c65ebfc7SToomas Soome         debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13728c65ebfc7SToomas Soome         status = mStatus_BadReferenceErr;
13729c65ebfc7SToomas Soome     }
13730c65ebfc7SToomas Soome     else
13731c65ebfc7SToomas Soome     {
13732c65ebfc7SToomas Soome         debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13733c65ebfc7SToomas Soome         extra->r.RecordCallback = MemFreeCallback;
13734c65ebfc7SToomas Soome         extra->r.RecordContext  = Context;
13735c65ebfc7SToomas Soome         *e = (*e)->next;
13736c65ebfc7SToomas Soome         status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13737c65ebfc7SToomas Soome     }
13738c65ebfc7SToomas Soome     mDNS_Unlock(m);
13739c65ebfc7SToomas Soome     return(status);
13740c65ebfc7SToomas Soome }
13741c65ebfc7SToomas Soome 
mDNS_RenameAndReregisterService(mDNS * const m,ServiceRecordSet * const sr,const domainlabel * newname)13742c65ebfc7SToomas Soome mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13743c65ebfc7SToomas Soome {
13744c65ebfc7SToomas Soome     // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13745c65ebfc7SToomas Soome     // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13746c65ebfc7SToomas Soome     domainlabel name1, name2;
13747c65ebfc7SToomas Soome     domainname type, domain;
13748c65ebfc7SToomas Soome     const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13749c65ebfc7SToomas Soome     ExtraResourceRecord *extras = sr->Extras;
13750c65ebfc7SToomas Soome     mStatus err;
13751c65ebfc7SToomas Soome 
13752c65ebfc7SToomas Soome     DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13753c65ebfc7SToomas Soome     if (!newname)
13754c65ebfc7SToomas Soome     {
13755c65ebfc7SToomas Soome         name2 = name1;
13756c65ebfc7SToomas Soome         IncrementLabelSuffix(&name2, mDNStrue);
13757c65ebfc7SToomas Soome         newname = &name2;
13758c65ebfc7SToomas Soome     }
13759c65ebfc7SToomas Soome 
13760c65ebfc7SToomas Soome     if (SameDomainName(&domain, &localdomain))
13761c65ebfc7SToomas Soome         debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13762c65ebfc7SToomas Soome     else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13763c65ebfc7SToomas Soome 
13764*472cd20dSToomas Soome     // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13765*472cd20dSToomas Soome     // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13766*472cd20dSToomas Soome     if (sr->RR_TXT.NewRData) CompleteRDataUpdate(m, &sr->RR_TXT);
13767c65ebfc7SToomas Soome     err = mDNS_RegisterService(m, sr, newname, &type, &domain,
137683b436d06SToomas Soome                                host, sr->RR_SRV.resrec.rdata->u.srv.port,
137693b436d06SToomas Soome                                (sr->RR_TXT.resrec.rdata != &sr->RR_TXT.rdatastorage) ? sr->RR_TXT.resrec.rdata : mDNSNULL,
137703b436d06SToomas Soome                                sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13771c65ebfc7SToomas Soome                                sr->SubTypes, sr->NumSubTypes,
13772c65ebfc7SToomas Soome                                sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13773c65ebfc7SToomas Soome 
13774c65ebfc7SToomas Soome     // mDNS_RegisterService() just reset sr->Extras to NULL.
13775c65ebfc7SToomas Soome     // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13776c65ebfc7SToomas Soome     // through the old list of extra records, and re-add them to our freshly created service registration
13777c65ebfc7SToomas Soome     while (!err && extras)
13778c65ebfc7SToomas Soome     {
13779c65ebfc7SToomas Soome         ExtraResourceRecord *e = extras;
13780c65ebfc7SToomas Soome         extras = extras->next;
13781c65ebfc7SToomas Soome         err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13782c65ebfc7SToomas Soome     }
13783c65ebfc7SToomas Soome 
13784c65ebfc7SToomas Soome     return(err);
13785c65ebfc7SToomas Soome }
13786c65ebfc7SToomas Soome 
13787c65ebfc7SToomas Soome // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13788c65ebfc7SToomas Soome // which may change the record list and/or question list.
13789c65ebfc7SToomas Soome // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
mDNS_DeregisterService_drt(mDNS * const m,ServiceRecordSet * sr,mDNS_Dereg_type drt)13790c65ebfc7SToomas Soome mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13791c65ebfc7SToomas Soome {
13792c65ebfc7SToomas Soome     // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13793c65ebfc7SToomas Soome     if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13794c65ebfc7SToomas Soome 
13795c65ebfc7SToomas Soome     if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13796c65ebfc7SToomas Soome     {
13797c65ebfc7SToomas Soome         debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13798c65ebfc7SToomas Soome         return(mStatus_BadReferenceErr);
13799c65ebfc7SToomas Soome     }
13800c65ebfc7SToomas Soome     else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13801c65ebfc7SToomas Soome     {
13802c65ebfc7SToomas Soome         LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13803c65ebfc7SToomas Soome         // Avoid race condition:
13804c65ebfc7SToomas Soome         // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13805c65ebfc7SToomas Soome         // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13806c65ebfc7SToomas Soome         // If the client happens to deregister the service in the middle of that process, then
13807c65ebfc7SToomas Soome         // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13808c65ebfc7SToomas Soome         // instead of incorrectly promoting it to mStatus_NameConflict.
13809c65ebfc7SToomas Soome         // This race condition is exposed particularly when the conformance test generates
13810c65ebfc7SToomas Soome         // a whole batch of simultaneous conflicts across a range of services all advertised
13811c65ebfc7SToomas Soome         // using the same system default name, and if we don't take this precaution then
13812c65ebfc7SToomas Soome         // we end up incrementing m->nicelabel multiple times instead of just once.
13813c65ebfc7SToomas Soome         // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13814c65ebfc7SToomas Soome         sr->Conflict = mDNSfalse;
13815c65ebfc7SToomas Soome         return(mStatus_NoError);
13816c65ebfc7SToomas Soome     }
13817c65ebfc7SToomas Soome     else
13818c65ebfc7SToomas Soome     {
13819c65ebfc7SToomas Soome         mDNSu32 i;
13820c65ebfc7SToomas Soome         mStatus status;
13821c65ebfc7SToomas Soome         ExtraResourceRecord *e;
13822c65ebfc7SToomas Soome         mDNS_Lock(m);
13823c65ebfc7SToomas Soome         e = sr->Extras;
13824c65ebfc7SToomas Soome 
13825c65ebfc7SToomas Soome         // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13826c65ebfc7SToomas Soome         // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13827c65ebfc7SToomas Soome         mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13828c65ebfc7SToomas Soome         mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13829c65ebfc7SToomas Soome         mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13830c65ebfc7SToomas Soome 
13831c65ebfc7SToomas Soome         // We deregister all of the extra records, but we leave the sr->Extras list intact
13832c65ebfc7SToomas Soome         // in case the client wants to do a RenameAndReregister and reinstate the registration
13833c65ebfc7SToomas Soome         while (e)
13834c65ebfc7SToomas Soome         {
13835c65ebfc7SToomas Soome             mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13836c65ebfc7SToomas Soome             e = e->next;
13837c65ebfc7SToomas Soome         }
13838c65ebfc7SToomas Soome 
13839c65ebfc7SToomas Soome         for (i=0; i<sr->NumSubTypes; i++)
13840c65ebfc7SToomas Soome             mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13841c65ebfc7SToomas Soome 
13842c65ebfc7SToomas Soome         status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13843c65ebfc7SToomas Soome         mDNS_Unlock(m);
13844c65ebfc7SToomas Soome         return(status);
13845c65ebfc7SToomas Soome     }
13846c65ebfc7SToomas Soome }
13847c65ebfc7SToomas Soome 
13848c65ebfc7SToomas Soome // Create a registration that asserts that no such service exists with this name.
13849c65ebfc7SToomas Soome // This can be useful where there is a given function is available through several protocols.
13850c65ebfc7SToomas Soome // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13851c65ebfc7SToomas Soome // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13852c65ebfc7SToomas Soome // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13853c65ebfc7SToomas Soome // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
mDNS_RegisterNoSuchService(mDNS * const m,AuthRecord * const rr,const domainlabel * const name,const domainname * const type,const domainname * const domain,const domainname * const host,const mDNSInterfaceID InterfaceID,mDNSRecordCallback Callback,void * Context,mDNSu32 flags)13854c65ebfc7SToomas Soome mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13855c65ebfc7SToomas Soome                                               const domainlabel *const name, const domainname *const type, const domainname *const domain,
13856c65ebfc7SToomas Soome                                               const domainname *const host,
13857c65ebfc7SToomas Soome                                               const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13858c65ebfc7SToomas Soome {
13859c65ebfc7SToomas Soome     AuthRecType artype;
13860c65ebfc7SToomas Soome 
13861c65ebfc7SToomas Soome     artype = setAuthRecType(InterfaceID, flags);
13862c65ebfc7SToomas Soome 
13863c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13864c65ebfc7SToomas Soome     if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13865c65ebfc7SToomas Soome     rr->resrec.rdata->u.srv.priority    = 0;
13866c65ebfc7SToomas Soome     rr->resrec.rdata->u.srv.weight      = 0;
13867c65ebfc7SToomas Soome     rr->resrec.rdata->u.srv.port        = zeroIPPort;
13868c65ebfc7SToomas Soome     if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13869c65ebfc7SToomas Soome     else rr->AutoTarget = Target_AutoHost;
13870c65ebfc7SToomas Soome     return(mDNS_Register(m, rr));
13871c65ebfc7SToomas Soome }
13872c65ebfc7SToomas Soome 
mDNS_AdvertiseDomains(mDNS * const m,AuthRecord * rr,mDNS_DomainType DomainType,const mDNSInterfaceID InterfaceID,char * domname)13873c65ebfc7SToomas Soome mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13874c65ebfc7SToomas Soome                                          mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13875c65ebfc7SToomas Soome {
13876c65ebfc7SToomas Soome     AuthRecType artype;
13877c65ebfc7SToomas Soome 
13878c65ebfc7SToomas Soome     if (InterfaceID == mDNSInterface_LocalOnly)
13879c65ebfc7SToomas Soome         artype = AuthRecordLocalOnly;
13880c65ebfc7SToomas Soome     else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13881c65ebfc7SToomas Soome         artype = AuthRecordP2P;
13882c65ebfc7SToomas Soome     else
13883c65ebfc7SToomas Soome         artype = AuthRecordAny;
13884c65ebfc7SToomas Soome     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13885c65ebfc7SToomas Soome     if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13886c65ebfc7SToomas Soome     if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13887c65ebfc7SToomas Soome     return(mDNS_Register(m, rr));
13888c65ebfc7SToomas Soome }
13889c65ebfc7SToomas Soome 
mDNS_IdUsedInResourceRecordsList(mDNS * const m,mDNSOpaque16 id)13890c65ebfc7SToomas Soome mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13891c65ebfc7SToomas Soome {
13892c65ebfc7SToomas Soome     AuthRecord *r;
13893c65ebfc7SToomas Soome     for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13894c65ebfc7SToomas Soome     return mDNSfalse;
13895c65ebfc7SToomas Soome }
13896c65ebfc7SToomas Soome 
mDNS_IdUsedInQuestionsList(mDNS * const m,mDNSOpaque16 id)13897c65ebfc7SToomas Soome mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13898c65ebfc7SToomas Soome {
13899c65ebfc7SToomas Soome     DNSQuestion *q;
13900c65ebfc7SToomas Soome     for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13901c65ebfc7SToomas Soome     return mDNSfalse;
13902c65ebfc7SToomas Soome }
13903c65ebfc7SToomas Soome 
mDNS_NewMessageID(mDNS * const m)13904c65ebfc7SToomas Soome mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13905c65ebfc7SToomas Soome {
13906c65ebfc7SToomas Soome     mDNSOpaque16 id;
13907c65ebfc7SToomas Soome     int i;
13908c65ebfc7SToomas Soome 
13909c65ebfc7SToomas Soome     for (i=0; i<10; i++)
13910c65ebfc7SToomas Soome     {
13911c65ebfc7SToomas Soome         id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13912c65ebfc7SToomas Soome         if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13913c65ebfc7SToomas Soome     }
13914c65ebfc7SToomas Soome 
13915c65ebfc7SToomas Soome     debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13916c65ebfc7SToomas Soome 
13917c65ebfc7SToomas Soome     return id;
13918c65ebfc7SToomas Soome }
13919c65ebfc7SToomas Soome 
13920c65ebfc7SToomas Soome // ***************************************************************************
13921c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
13922c65ebfc7SToomas Soome #pragma mark -
13923c65ebfc7SToomas Soome #pragma mark - Sleep Proxy Server
13924c65ebfc7SToomas Soome #endif
13925c65ebfc7SToomas Soome 
RestartARPProbing(mDNS * const m,AuthRecord * const rr)13926c65ebfc7SToomas Soome mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13927c65ebfc7SToomas Soome {
13928c65ebfc7SToomas Soome     // If we see an ARP from a machine we think is sleeping, then either
13929c65ebfc7SToomas Soome     // (i) the machine has woken, or
13930c65ebfc7SToomas Soome     // (ii) it's just a stray old packet from before the machine slept
13931c65ebfc7SToomas Soome     // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13932c65ebfc7SToomas Soome     // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13933c65ebfc7SToomas Soome     // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13934c65ebfc7SToomas Soome     // 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*
13935c65ebfc7SToomas Soome     // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13936c65ebfc7SToomas Soome     // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13937c65ebfc7SToomas Soome 
13938c65ebfc7SToomas Soome     rr->resrec.RecordType = kDNSRecordTypeUnique;
13939c65ebfc7SToomas Soome     rr->ProbeCount        = DefaultProbeCountForTypeUnique;
13940c65ebfc7SToomas Soome     rr->ProbeRestartCount++;
13941c65ebfc7SToomas Soome 
13942c65ebfc7SToomas Soome     // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13943c65ebfc7SToomas Soome     // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13944c65ebfc7SToomas Soome     // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13945c65ebfc7SToomas Soome     // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13946c65ebfc7SToomas Soome     // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13947c65ebfc7SToomas Soome     // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13948c65ebfc7SToomas Soome     if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13949c65ebfc7SToomas Soome         InitializeLastAPTime(m, rr);
13950c65ebfc7SToomas Soome     else
13951c65ebfc7SToomas Soome     {
13952c65ebfc7SToomas Soome         rr->AnnounceCount  = InitialAnnounceCount;
13953c65ebfc7SToomas Soome         rr->ThisAPInterval = mDNSPlatformOneSecond;
13954c65ebfc7SToomas Soome         rr->LastAPTime     = m->timenow + mDNSPlatformOneSecond * 9;    // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13955c65ebfc7SToomas Soome         SetNextAnnounceProbeTime(m, rr);
13956c65ebfc7SToomas Soome     }
13957c65ebfc7SToomas Soome }
13958c65ebfc7SToomas Soome 
mDNSCoreReceiveRawARP(mDNS * const m,const ARP_EthIP * const arp,const mDNSInterfaceID InterfaceID)13959c65ebfc7SToomas Soome mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13960c65ebfc7SToomas Soome {
13961c65ebfc7SToomas Soome     static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13962c65ebfc7SToomas Soome     AuthRecord *rr;
13963c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13964c65ebfc7SToomas Soome     if (!intf) return;
13965c65ebfc7SToomas Soome 
13966c65ebfc7SToomas Soome     mDNS_Lock(m);
13967c65ebfc7SToomas Soome 
13968c65ebfc7SToomas Soome     // Pass 1:
13969c65ebfc7SToomas Soome     // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13970c65ebfc7SToomas Soome     // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13971c65ebfc7SToomas Soome     // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13972c65ebfc7SToomas Soome     // The times we might need to react to an ARP Announcement are:
13973c65ebfc7SToomas Soome     // (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
13974c65ebfc7SToomas Soome     // (ii) if it's a conflicting Announcement from another host
13975c65ebfc7SToomas Soome     // -- and we check for these in Pass 2 below.
13976c65ebfc7SToomas Soome     if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13977c65ebfc7SToomas Soome     {
13978c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
13979c65ebfc7SToomas Soome             if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13980c65ebfc7SToomas Soome                 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13981c65ebfc7SToomas Soome             {
13982c65ebfc7SToomas Soome                 static const char msg1[] = "ARP Req from owner -- re-probing";
13983c65ebfc7SToomas Soome                 static const char msg2[] = "Ignoring  ARP Request from      ";
13984c65ebfc7SToomas Soome                 static const char msg3[] = "Creating Local ARP Cache entry  ";
13985c65ebfc7SToomas Soome                 static const char msg4[] = "Answering ARP Request from      ";
13986c65ebfc7SToomas Soome                 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13987c65ebfc7SToomas Soome                                         (rr->AnnounceCount == InitialAnnounceCount)     ? msg2 :
13988c65ebfc7SToomas Soome                                         mDNSSameEthAddress(&arp->sha, &intf->MAC)       ? msg3 : msg4;
13989c65ebfc7SToomas Soome                 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13990c65ebfc7SToomas Soome                        intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b,
13991c65ebfc7SToomas Soome                        &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13992c65ebfc7SToomas Soome                 if (msg == msg1)
13993c65ebfc7SToomas Soome                 {
13994c65ebfc7SToomas Soome                     if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13995c65ebfc7SToomas Soome                         RestartARPProbing(m, rr);
13996c65ebfc7SToomas Soome                     else
13997c65ebfc7SToomas Soome                         LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13998c65ebfc7SToomas Soome                 }
13999c65ebfc7SToomas Soome                 else if (msg == msg3)
14000c65ebfc7SToomas Soome                 {
14001c65ebfc7SToomas Soome                     mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14002c65ebfc7SToomas Soome                 }
14003c65ebfc7SToomas Soome                 else if (msg == msg4)
14004c65ebfc7SToomas Soome                 {
140053b436d06SToomas Soome 		    mDNSv4Addr tpa = arp->tpa;
140063b436d06SToomas Soome 		    mDNSv4Addr spa = arp->spa;
140073b436d06SToomas Soome                     SendARP(m, 2, rr, &tpa, &arp->sha, &spa, &arp->sha);
14008c65ebfc7SToomas Soome                 }
14009c65ebfc7SToomas Soome             }
14010c65ebfc7SToomas Soome     }
14011c65ebfc7SToomas Soome 
14012c65ebfc7SToomas Soome     // Pass 2:
14013c65ebfc7SToomas Soome     // 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.
14014c65ebfc7SToomas Soome     // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
14015c65ebfc7SToomas Soome     // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
14016c65ebfc7SToomas Soome     // 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.
14017c65ebfc7SToomas Soome     // If we see an apparently conflicting ARP, we check the sender hardware address:
14018c65ebfc7SToomas Soome     //   If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
14019c65ebfc7SToomas Soome     //   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.
14020c65ebfc7SToomas Soome     if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
14021c65ebfc7SToomas Soome         debugf("ARP from self for %.4a", arp->tpa.b);
14022c65ebfc7SToomas Soome     else
14023c65ebfc7SToomas Soome     {
14024c65ebfc7SToomas Soome         if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
14025c65ebfc7SToomas Soome             for (rr = m->ResourceRecords; rr; rr=rr->next)
14026c65ebfc7SToomas Soome                 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14027c65ebfc7SToomas Soome                     rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14028c65ebfc7SToomas Soome                 {
14029c65ebfc7SToomas Soome                     if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14030c65ebfc7SToomas Soome                     {
14031c65ebfc7SToomas Soome                         LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14032c65ebfc7SToomas Soome                                 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14033c65ebfc7SToomas Soome                     }
14034c65ebfc7SToomas Soome                     else
14035c65ebfc7SToomas Soome                     {
14036c65ebfc7SToomas Soome                         RestartARPProbing(m, rr);
14037c65ebfc7SToomas Soome                         if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
14038c65ebfc7SToomas Soome                         {
14039c65ebfc7SToomas Soome                             LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
14040c65ebfc7SToomas Soome                                     mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request      " : "Response     ",
14041c65ebfc7SToomas Soome                                     arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr));
14042c65ebfc7SToomas Soome                         }
14043c65ebfc7SToomas Soome                         else
14044c65ebfc7SToomas Soome                         {
14045c65ebfc7SToomas Soome                             LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14046c65ebfc7SToomas Soome                                     arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14047c65ebfc7SToomas Soome                             ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14048c65ebfc7SToomas Soome                         }
14049c65ebfc7SToomas Soome                     }
14050c65ebfc7SToomas Soome                 }
14051c65ebfc7SToomas Soome     }
14052c65ebfc7SToomas Soome 
14053c65ebfc7SToomas Soome     mDNS_Unlock(m);
14054c65ebfc7SToomas Soome }
14055c65ebfc7SToomas Soome 
14056c65ebfc7SToomas Soome /*
14057c65ebfc7SToomas Soome    // Option 1 is Source Link Layer Address Option
14058c65ebfc7SToomas Soome    // Option 2 is Target Link Layer Address Option
14059c65ebfc7SToomas Soome    mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14060c65ebfc7SToomas Soome     {
14061c65ebfc7SToomas Soome     const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14062c65ebfc7SToomas Soome     while (options < end)
14063c65ebfc7SToomas Soome         {
14064c65ebfc7SToomas Soome         debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14065c65ebfc7SToomas Soome         if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14066c65ebfc7SToomas Soome         options += options[1] * 8;
14067c65ebfc7SToomas Soome         }
14068c65ebfc7SToomas Soome     return mDNSNULL;
14069c65ebfc7SToomas Soome     }
14070c65ebfc7SToomas Soome  */
14071c65ebfc7SToomas Soome 
mDNSCoreReceiveRawND(mDNS * const m,const mDNSEthAddr * const sha,const mDNSv6Addr * spa,const IPv6NDP * const ndp,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID)14072c65ebfc7SToomas Soome mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
14073c65ebfc7SToomas Soome                                     const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14074c65ebfc7SToomas Soome {
14075c65ebfc7SToomas Soome     AuthRecord *rr;
14076c65ebfc7SToomas Soome     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
14077c65ebfc7SToomas Soome     if (!intf) return;
14078c65ebfc7SToomas Soome 
14079c65ebfc7SToomas Soome     mDNS_Lock(m);
14080c65ebfc7SToomas Soome 
14081c65ebfc7SToomas Soome     // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14082c65ebfc7SToomas Soome     if (ndp->type == NDP_Sol)
14083c65ebfc7SToomas Soome     {
14084c65ebfc7SToomas Soome         //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14085c65ebfc7SToomas Soome         (void)end;
14086c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
14087c65ebfc7SToomas Soome             if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14088c65ebfc7SToomas Soome                 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
14089c65ebfc7SToomas Soome             {
14090c65ebfc7SToomas Soome                 static const char msg1[] = "NDP Req from owner -- re-probing";
14091c65ebfc7SToomas Soome                 static const char msg2[] = "Ignoring  NDP Request from      ";
14092c65ebfc7SToomas Soome                 static const char msg3[] = "Creating Local NDP Cache entry  ";
14093c65ebfc7SToomas Soome                 static const char msg4[] = "Answering NDP Request from      ";
14094c65ebfc7SToomas Soome                 static const char msg5[] = "Answering NDP Probe   from      ";
14095*472cd20dSToomas Soome                 const char *const msg = mDNSSameEthAddress(sha, &rr->WakeUp.IMAC)   ? msg1 :
14096c65ebfc7SToomas Soome                                         (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
14097*472cd20dSToomas Soome                                         mDNSSameEthAddress(sha, &intf->MAC)         ? msg3 :
14098*472cd20dSToomas Soome                                         mDNSIPv6AddressIsZero(*spa)                 ? msg4 : msg5;
14099c65ebfc7SToomas Soome                 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14100c65ebfc7SToomas Soome                        intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14101c65ebfc7SToomas Soome                 if (msg == msg1)
14102c65ebfc7SToomas Soome                 {
14103c65ebfc7SToomas Soome                     if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
14104c65ebfc7SToomas Soome                         RestartARPProbing(m, rr);
14105c65ebfc7SToomas Soome                     else
14106c65ebfc7SToomas Soome                         LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
14107c65ebfc7SToomas Soome                 }
14108c65ebfc7SToomas Soome                 else if (msg == msg3)
14109c65ebfc7SToomas Soome                     mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14110c65ebfc7SToomas Soome                 else if (msg == msg4)
14111c65ebfc7SToomas Soome                     SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
14112c65ebfc7SToomas Soome                 else if (msg == msg5)
14113c65ebfc7SToomas Soome                     SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
14114c65ebfc7SToomas Soome             }
14115c65ebfc7SToomas Soome     }
14116c65ebfc7SToomas Soome 
14117c65ebfc7SToomas Soome     // 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.
14118c65ebfc7SToomas Soome     if (mDNSSameEthAddress(sha, &intf->MAC))
14119c65ebfc7SToomas Soome         debugf("NDP from self for %.16a", &ndp->target);
14120c65ebfc7SToomas Soome     else
14121c65ebfc7SToomas Soome     {
14122c65ebfc7SToomas Soome         // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14123c65ebfc7SToomas Soome         // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14124c65ebfc7SToomas Soome         // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14125c65ebfc7SToomas Soome         // Hence it is the NDP target address we care about, not the actual packet source address.
14126c65ebfc7SToomas Soome         if (ndp->type == NDP_Adv) spa = &ndp->target;
14127c65ebfc7SToomas Soome         if (!mDNSSameIPv6Address(*spa, zerov6Addr))
14128c65ebfc7SToomas Soome             for (rr = m->ResourceRecords; rr; rr=rr->next)
14129c65ebfc7SToomas Soome                 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14130c65ebfc7SToomas Soome                     rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14131c65ebfc7SToomas Soome                 {
14132c65ebfc7SToomas Soome                     if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14133c65ebfc7SToomas Soome                     {
14134c65ebfc7SToomas Soome                         LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14135c65ebfc7SToomas Soome                                     sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14136c65ebfc7SToomas Soome                     }
14137c65ebfc7SToomas Soome                     else
14138c65ebfc7SToomas Soome                     {
14139c65ebfc7SToomas Soome                         RestartARPProbing(m, rr);
14140c65ebfc7SToomas Soome                         if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
14141c65ebfc7SToomas Soome                         {
14142c65ebfc7SToomas Soome                             LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
14143c65ebfc7SToomas Soome                                     ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
14144c65ebfc7SToomas Soome                         }
14145c65ebfc7SToomas Soome                         else
14146c65ebfc7SToomas Soome                         {
14147c65ebfc7SToomas Soome                             LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14148c65ebfc7SToomas Soome                                     sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14149c65ebfc7SToomas Soome                             ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14150c65ebfc7SToomas Soome                         }
14151c65ebfc7SToomas Soome                     }
14152c65ebfc7SToomas Soome                 }
14153c65ebfc7SToomas Soome     }
14154c65ebfc7SToomas Soome 
14155c65ebfc7SToomas Soome     mDNS_Unlock(m);
14156c65ebfc7SToomas Soome }
14157c65ebfc7SToomas Soome 
mDNSCoreReceiveRawTransportPacket(mDNS * const m,const mDNSEthAddr * const sha,const mDNSAddr * const src,const mDNSAddr * const dst,const mDNSu8 protocol,const mDNSu8 * const p,const TransportLayerPacket * const t,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID,const mDNSu16 len)14158c65ebfc7SToomas Soome mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
14159c65ebfc7SToomas Soome                                                  const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
14160c65ebfc7SToomas Soome {
14161c65ebfc7SToomas Soome     const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
14162c65ebfc7SToomas Soome     mDNSBool wake = mDNSfalse;
14163c65ebfc7SToomas Soome     mDNSBool kaWake = mDNSfalse;
14164c65ebfc7SToomas Soome 
14165c65ebfc7SToomas Soome     switch (protocol)
14166c65ebfc7SToomas Soome     {
14167c65ebfc7SToomas Soome         #define XX wake ? "Received" : "Ignoring", end-p
14168c65ebfc7SToomas Soome     case 0x01:  LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
14169c65ebfc7SToomas Soome         break;
14170c65ebfc7SToomas Soome 
14171c65ebfc7SToomas Soome     case 0x06:  {
14172c65ebfc7SToomas Soome         AuthRecord *kr;
14173c65ebfc7SToomas Soome         mDNSu32 seq, ack;
14174c65ebfc7SToomas Soome                     #define TH_FIN  0x01
14175c65ebfc7SToomas Soome                     #define TH_SYN  0x02
14176c65ebfc7SToomas Soome                     #define TH_RST  0x04
14177c65ebfc7SToomas Soome                     #define TH_ACK  0x10
14178c65ebfc7SToomas Soome 
14179c65ebfc7SToomas Soome         kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
14180c65ebfc7SToomas Soome         if (kr)
14181c65ebfc7SToomas Soome         {
14182c65ebfc7SToomas Soome             LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d  to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
14183c65ebfc7SToomas Soome             // Plan to wake if
14184c65ebfc7SToomas Soome             // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14185c65ebfc7SToomas Soome             // (b) packet that contains new data and acks a sequence number higher than the one
14186c65ebfc7SToomas Soome             //     we have been sending in the keepalive
14187c65ebfc7SToomas Soome 
14188c65ebfc7SToomas Soome             wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
14189c65ebfc7SToomas Soome             if (!wake)
14190c65ebfc7SToomas Soome             {
14191c65ebfc7SToomas Soome                 mDNSu8 *ptr;
14192c65ebfc7SToomas Soome                 mDNSu32 pseq, pack;
14193c65ebfc7SToomas Soome                 mDNSBool data = mDNSfalse;
14194c65ebfc7SToomas Soome                 mDNSu8 tcphlen;
14195c65ebfc7SToomas Soome 
14196c65ebfc7SToomas Soome                 // Convert to host order
14197c65ebfc7SToomas Soome                 ptr = (mDNSu8 *)&seq;
14198c65ebfc7SToomas Soome                 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14199c65ebfc7SToomas Soome 
14200c65ebfc7SToomas Soome                 ptr = (mDNSu8 *)&ack;
14201c65ebfc7SToomas Soome                 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14202c65ebfc7SToomas Soome 
14203c65ebfc7SToomas Soome                 pseq = t->tcp.seq;
14204c65ebfc7SToomas Soome                 ptr = (mDNSu8 *)&pseq;
14205c65ebfc7SToomas Soome                 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14206c65ebfc7SToomas Soome 
14207c65ebfc7SToomas Soome                 pack = t->tcp.ack;
14208c65ebfc7SToomas Soome                 ptr = (mDNSu8 *)&pack;
14209c65ebfc7SToomas Soome                 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14210c65ebfc7SToomas Soome 
14211c65ebfc7SToomas Soome                 // If the other side is acking one more than our sequence number (keepalive is one
14212c65ebfc7SToomas Soome                 // less than the last valid sequence sent) and it's sequence is more than what we
14213c65ebfc7SToomas Soome                 // acked before
14214c65ebfc7SToomas Soome                 //if (end - p - 34  - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14215c65ebfc7SToomas Soome                 tcphlen = ((t->tcp.offset >> 4) * 4);
14216c65ebfc7SToomas Soome                 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
14217c65ebfc7SToomas Soome                 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
14218c65ebfc7SToomas Soome 
14219c65ebfc7SToomas Soome                 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14220c65ebfc7SToomas Soome                 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
14221c65ebfc7SToomas Soome                     ((int)(ack - pseq) == 1))
14222c65ebfc7SToomas Soome                 {
14223c65ebfc7SToomas Soome                     // Send an ACK;
14224c65ebfc7SToomas Soome                     mDNS_SendKeepaliveACK(m, kr);
14225c65ebfc7SToomas Soome                 }
14226c65ebfc7SToomas Soome                 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14227c65ebfc7SToomas Soome                        end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
14228c65ebfc7SToomas Soome             }
14229c65ebfc7SToomas Soome             else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
14230c65ebfc7SToomas Soome             kaWake = wake;
14231c65ebfc7SToomas Soome         }
14232c65ebfc7SToomas Soome         else
14233c65ebfc7SToomas Soome         {
14234c65ebfc7SToomas Soome             // Plan to wake if
14235c65ebfc7SToomas Soome             // (a) RST is not set, AND
14236c65ebfc7SToomas Soome             // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14237c65ebfc7SToomas Soome             wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
14238c65ebfc7SToomas Soome 
14239c65ebfc7SToomas Soome             // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14240c65ebfc7SToomas Soome             // except for ssh connections, where we'll wake for plain data packets too
14241c65ebfc7SToomas Soome             if  (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
14242c65ebfc7SToomas Soome 
14243c65ebfc7SToomas Soome             LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
14244c65ebfc7SToomas Soome                    src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
14245c65ebfc7SToomas Soome                    (t->tcp.flags & 2) ? " SYN" : "",
14246c65ebfc7SToomas Soome                    (t->tcp.flags & 1) ? " FIN" : "",
14247c65ebfc7SToomas Soome                    (t->tcp.flags & 4) ? " RST" : "");
14248c65ebfc7SToomas Soome         }
14249c65ebfc7SToomas Soome         break;
14250c65ebfc7SToomas Soome     }
14251c65ebfc7SToomas Soome 
14252c65ebfc7SToomas Soome     case 0x11:  {
14253c65ebfc7SToomas Soome                     #define ARD_AsNumber 3283
14254c65ebfc7SToomas Soome         static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
14255c65ebfc7SToomas Soome         const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]);                  // Length *including* 8-byte UDP header
14256c65ebfc7SToomas Soome         if (udplen >= sizeof(UDPHeader))
14257c65ebfc7SToomas Soome         {
14258c65ebfc7SToomas Soome             const mDNSu16 datalen = udplen - sizeof(UDPHeader);
14259c65ebfc7SToomas Soome             wake = mDNStrue;
14260c65ebfc7SToomas Soome 
14261c65ebfc7SToomas Soome             // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14262c65ebfc7SToomas Soome             if (mDNSSameIPPort(port, IPSECPort))
14263c65ebfc7SToomas Soome             {
14264c65ebfc7SToomas Soome                 // Specifically ignore NAT keepalive packets
14265c65ebfc7SToomas Soome                 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14266c65ebfc7SToomas Soome                 else
14267c65ebfc7SToomas Soome                 {
14268c65ebfc7SToomas Soome                     // Skip over the Non-ESP Marker if present
14269c65ebfc7SToomas Soome                     const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14270c65ebfc7SToomas Soome                     const IKEHeader *const ike    = (IKEHeader *)(t + (NonESP ? 12 : 8));
14271c65ebfc7SToomas Soome                     const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14272c65ebfc7SToomas Soome                     if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14273c65ebfc7SToomas Soome                         if ((ike->Version & 0x10) == 0x10)
14274c65ebfc7SToomas Soome                         {
14275c65ebfc7SToomas Soome                             // ExchangeType ==  5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14276c65ebfc7SToomas Soome                             // ExchangeType == 34 means 'IKE_SA_INIT'   <http://www.iana.org/assignments/ikev2-parameters>
14277c65ebfc7SToomas Soome                             if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14278c65ebfc7SToomas Soome                             LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14279c65ebfc7SToomas Soome                         }
14280c65ebfc7SToomas Soome                 }
14281c65ebfc7SToomas Soome             }
14282c65ebfc7SToomas Soome 
14283c65ebfc7SToomas Soome             // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14284c65ebfc7SToomas Soome             // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14285c65ebfc7SToomas Soome             // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14286c65ebfc7SToomas Soome             // UDP header (8 bytes)
14287c65ebfc7SToomas Soome             // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14288c65ebfc7SToomas Soome             if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14289c65ebfc7SToomas Soome 
14290c65ebfc7SToomas Soome             LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14291c65ebfc7SToomas Soome         }
14292c65ebfc7SToomas Soome     }
14293c65ebfc7SToomas Soome     break;
14294c65ebfc7SToomas Soome 
14295c65ebfc7SToomas Soome     case 0x3A:  if (&t->bytes[len] <= end)
14296c65ebfc7SToomas Soome         {
14297c65ebfc7SToomas Soome             mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14298c65ebfc7SToomas Soome             if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14299c65ebfc7SToomas Soome             else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14300c65ebfc7SToomas Soome         }
14301c65ebfc7SToomas Soome         break;
14302c65ebfc7SToomas Soome 
14303c65ebfc7SToomas Soome     default:    LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14304c65ebfc7SToomas Soome         break;
14305c65ebfc7SToomas Soome     }
14306c65ebfc7SToomas Soome 
14307c65ebfc7SToomas Soome     if (wake)
14308c65ebfc7SToomas Soome     {
14309c65ebfc7SToomas Soome         AuthRecord *rr, *r2;
14310c65ebfc7SToomas Soome 
14311c65ebfc7SToomas Soome         mDNS_Lock(m);
14312c65ebfc7SToomas Soome         for (rr = m->ResourceRecords; rr; rr=rr->next)
14313c65ebfc7SToomas Soome             if (rr->resrec.InterfaceID == InterfaceID &&
14314c65ebfc7SToomas Soome                 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14315c65ebfc7SToomas Soome                 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14316c65ebfc7SToomas Soome             {
14317c65ebfc7SToomas Soome                 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14318c65ebfc7SToomas Soome                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14319c65ebfc7SToomas Soome                     if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14320c65ebfc7SToomas Soome                         r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14321c65ebfc7SToomas Soome                         r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14322c65ebfc7SToomas Soome                         SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14323c65ebfc7SToomas Soome                         break;
14324c65ebfc7SToomas Soome                 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr;    // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14325c65ebfc7SToomas Soome                 if (!r2 && kaWake) r2 = rr;                             // So that we wake for keepalive packets, even without a matching SRV record
14326c65ebfc7SToomas Soome                 if (r2)
14327c65ebfc7SToomas Soome                 {
14328c65ebfc7SToomas Soome                     LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14329c65ebfc7SToomas Soome                            InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14330c65ebfc7SToomas Soome                     ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14331c65ebfc7SToomas Soome                 }
14332c65ebfc7SToomas Soome                 else
14333c65ebfc7SToomas Soome                     LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14334c65ebfc7SToomas Soome                            InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14335c65ebfc7SToomas Soome             }
14336c65ebfc7SToomas Soome         mDNS_Unlock(m);
14337c65ebfc7SToomas Soome     }
14338c65ebfc7SToomas Soome }
14339c65ebfc7SToomas Soome 
mDNSCoreReceiveRawPacket(mDNS * const m,const mDNSu8 * const p,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID)14340c65ebfc7SToomas Soome mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14341c65ebfc7SToomas Soome {
14342c65ebfc7SToomas Soome     static const mDNSOpaque16 Ethertype_ARP  = { { 0x08, 0x06 } };  // Ethertype 0x0806 = ARP
14343c65ebfc7SToomas Soome     static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } };  // Ethertype 0x0800 = IPv4
14344c65ebfc7SToomas Soome     static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } };  // Ethertype 0x86DD = IPv6
14345c65ebfc7SToomas Soome     static const mDNSOpaque16 ARP_hrd_eth    = { { 0x00, 0x01 } };  // Hardware address space (Ethernet = 1)
14346c65ebfc7SToomas Soome     static const mDNSOpaque16 ARP_pro_ip     = { { 0x08, 0x00 } };  // Protocol address space (IP = 0x0800)
14347c65ebfc7SToomas Soome 
14348c65ebfc7SToomas Soome     // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14349c65ebfc7SToomas Soome     // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14350c65ebfc7SToomas Soome     // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14351c65ebfc7SToomas Soome     // since it points to a an address 14 bytes before pkt.
14352c65ebfc7SToomas Soome     const EthernetHeader     *const eth = (const EthernetHeader *)p;
14353c65ebfc7SToomas Soome     const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14354c65ebfc7SToomas Soome     mDNSAddr src, dst;
14355c65ebfc7SToomas Soome     #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14356c65ebfc7SToomas Soome 
14357c65ebfc7SToomas Soome     // Is ARP? Length must be at least 14 + 28 = 42 bytes
14358c65ebfc7SToomas Soome     if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14359c65ebfc7SToomas Soome         mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14360c65ebfc7SToomas Soome     // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14361c65ebfc7SToomas Soome     else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14362c65ebfc7SToomas Soome     {
14363c65ebfc7SToomas Soome         const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14364c65ebfc7SToomas Soome         const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14365c65ebfc7SToomas Soome         if (transEnd > end) transEnd = end;
14366*472cd20dSToomas Soome         debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src.b, &pkt->v4.dst.b);
14367c65ebfc7SToomas Soome         src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14368c65ebfc7SToomas Soome         dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14369c65ebfc7SToomas Soome         if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14370c65ebfc7SToomas Soome             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14371c65ebfc7SToomas Soome     }
14372c65ebfc7SToomas Soome     // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14373c65ebfc7SToomas Soome     else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14374c65ebfc7SToomas Soome     {
14375c65ebfc7SToomas Soome         const mDNSu8 *const trans = p + 54;
14376*472cd20dSToomas Soome         debugf("Got IPv6  %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src.b, &pkt->v6.dst.b);
14377c65ebfc7SToomas Soome         src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14378c65ebfc7SToomas Soome         dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14379c65ebfc7SToomas Soome         if (end >= trans + RequiredCapLen(pkt->v6.pro))
14380c65ebfc7SToomas Soome             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14381c65ebfc7SToomas Soome                                               (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14382c65ebfc7SToomas Soome     }
14383c65ebfc7SToomas Soome }
14384c65ebfc7SToomas Soome 
ConstructSleepProxyServerName(mDNS * const m,domainlabel * name)14385c65ebfc7SToomas Soome mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14386c65ebfc7SToomas Soome {
14387c65ebfc7SToomas Soome     name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14388c65ebfc7SToomas Soome                                        m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14389c65ebfc7SToomas Soome }
14390c65ebfc7SToomas Soome 
14391c65ebfc7SToomas Soome #ifndef SPC_DISABLED
SleepProxyServerCallback(mDNS * const m,ServiceRecordSet * const srs,mStatus result)14392c65ebfc7SToomas Soome mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14393c65ebfc7SToomas Soome {
14394c65ebfc7SToomas Soome     if (result == mStatus_NameConflict)
14395c65ebfc7SToomas Soome         mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14396c65ebfc7SToomas Soome     else if (result == mStatus_MemFree)
14397c65ebfc7SToomas Soome     {
14398c65ebfc7SToomas Soome         if (m->SleepState)
14399c65ebfc7SToomas Soome             m->SPSState = 3;
14400c65ebfc7SToomas Soome         else
14401c65ebfc7SToomas Soome         {
14402c65ebfc7SToomas Soome             m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14403c65ebfc7SToomas Soome             if (m->SPSState)
14404c65ebfc7SToomas Soome             {
14405c65ebfc7SToomas Soome                 domainlabel name;
14406c65ebfc7SToomas Soome                 ConstructSleepProxyServerName(m, &name);
14407c65ebfc7SToomas Soome                 mDNS_RegisterService(m, srs,
14408c65ebfc7SToomas Soome                                      &name, &SleepProxyServiceType, &localdomain,
14409c65ebfc7SToomas Soome                                      mDNSNULL, m->SPSSocket->port, // Host, port
144103b436d06SToomas Soome                                      mDNSNULL,
14411c65ebfc7SToomas Soome                                      (mDNSu8 *)"", 1,           // TXT data, length
14412c65ebfc7SToomas Soome                                      mDNSNULL, 0,               // Subtypes (none)
14413c65ebfc7SToomas Soome                                      mDNSInterface_Any,         // Interface ID
14414c65ebfc7SToomas Soome                                      SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14415c65ebfc7SToomas Soome             }
14416c65ebfc7SToomas Soome             LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14417c65ebfc7SToomas Soome         }
14418c65ebfc7SToomas Soome     }
14419c65ebfc7SToomas Soome }
14420c65ebfc7SToomas Soome #endif
14421c65ebfc7SToomas Soome 
14422c65ebfc7SToomas Soome // Called with lock held
mDNSCoreBeSleepProxyServer_internal(mDNS * const m,mDNSu8 sps,mDNSu8 port,mDNSu8 marginalpower,mDNSu8 totpower,mDNSu8 features)14423c65ebfc7SToomas Soome mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14424c65ebfc7SToomas Soome {
14425c65ebfc7SToomas Soome     // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14426c65ebfc7SToomas Soome     mDNS_DropLockBeforeCallback();
14427c65ebfc7SToomas Soome 
14428c65ebfc7SToomas Soome     // If turning off SPS, close our socket
14429c65ebfc7SToomas Soome     // (Do this first, BEFORE calling mDNS_DeregisterService below)
14430c65ebfc7SToomas Soome     if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14431c65ebfc7SToomas Soome 
14432c65ebfc7SToomas Soome     // If turning off, or changing type, deregister old name
14433c65ebfc7SToomas Soome #ifndef SPC_DISABLED
14434c65ebfc7SToomas Soome     if (m->SPSState == 1 && sps != m->SPSType)
14435c65ebfc7SToomas Soome     { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14436c65ebfc7SToomas Soome #endif // SPC_DISABLED
14437c65ebfc7SToomas Soome 
14438c65ebfc7SToomas Soome     // Record our new SPS parameters
14439c65ebfc7SToomas Soome     m->SPSType          = sps;
14440c65ebfc7SToomas Soome     m->SPSPortability   = port;
14441c65ebfc7SToomas Soome     m->SPSMarginalPower = marginalpower;
14442c65ebfc7SToomas Soome     m->SPSTotalPower    = totpower;
14443c65ebfc7SToomas Soome     m->SPSFeatureFlags  = features;
14444c65ebfc7SToomas Soome     // If turning on, open socket and advertise service
14445c65ebfc7SToomas Soome     if (sps)
14446c65ebfc7SToomas Soome     {
14447c65ebfc7SToomas Soome         if (!m->SPSSocket)
14448c65ebfc7SToomas Soome         {
14449c65ebfc7SToomas Soome             m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort);
14450c65ebfc7SToomas Soome             if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14451c65ebfc7SToomas Soome         }
14452c65ebfc7SToomas Soome #ifndef SPC_DISABLED
14453c65ebfc7SToomas Soome         if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14454c65ebfc7SToomas Soome #endif // SPC_DISABLED
14455c65ebfc7SToomas Soome     }
14456c65ebfc7SToomas Soome     else if (m->SPSState)
14457c65ebfc7SToomas Soome     {
14458c65ebfc7SToomas Soome         LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14459c65ebfc7SToomas Soome         m->NextScheduledSPS = m->timenow;
14460c65ebfc7SToomas Soome     }
14461c65ebfc7SToomas Soome fail:
14462c65ebfc7SToomas Soome     mDNS_ReclaimLockAfterCallback();
14463c65ebfc7SToomas Soome }
14464c65ebfc7SToomas Soome 
14465c65ebfc7SToomas Soome // ***************************************************************************
14466c65ebfc7SToomas Soome #if COMPILER_LIKES_PRAGMA_MARK
14467c65ebfc7SToomas Soome #pragma mark -
14468c65ebfc7SToomas Soome #pragma mark - Startup and Shutdown
14469c65ebfc7SToomas Soome #endif
14470c65ebfc7SToomas Soome 
mDNS_GrowCache_internal(mDNS * const m,CacheEntity * storage,mDNSu32 numrecords)14471c65ebfc7SToomas Soome mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14472c65ebfc7SToomas Soome {
14473c65ebfc7SToomas Soome     if (storage && numrecords)
14474c65ebfc7SToomas Soome     {
14475c65ebfc7SToomas Soome         mDNSu32 i;
14476c65ebfc7SToomas Soome         debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14477c65ebfc7SToomas Soome         for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14478c65ebfc7SToomas Soome         storage[numrecords-1].next = m->rrcache_free;
14479c65ebfc7SToomas Soome         m->rrcache_free = storage;
14480c65ebfc7SToomas Soome         m->rrcache_size += numrecords;
14481c65ebfc7SToomas Soome     }
14482c65ebfc7SToomas Soome }
14483c65ebfc7SToomas Soome 
mDNS_GrowCache(mDNS * const m,CacheEntity * storage,mDNSu32 numrecords)14484c65ebfc7SToomas Soome mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14485c65ebfc7SToomas Soome {
14486c65ebfc7SToomas Soome     mDNS_Lock(m);
14487c65ebfc7SToomas Soome     mDNS_GrowCache_internal(m, storage, numrecords);
14488c65ebfc7SToomas Soome     mDNS_Unlock(m);
14489c65ebfc7SToomas Soome }
14490c65ebfc7SToomas Soome 
mDNS_InitStorage(mDNS * const m,mDNS_PlatformSupport * const p,CacheEntity * rrcachestorage,mDNSu32 rrcachesize,mDNSBool AdvertiseLocalAddresses,mDNSCallback * Callback,void * Context)14491c65ebfc7SToomas Soome mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p,
14492c65ebfc7SToomas Soome                                    CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14493c65ebfc7SToomas Soome                                    mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14494c65ebfc7SToomas Soome {
14495c65ebfc7SToomas Soome     mDNSu32 slot;
14496c65ebfc7SToomas Soome     mDNSs32 timenow;
14497c65ebfc7SToomas Soome     mStatus result;
14498c65ebfc7SToomas Soome 
14499c65ebfc7SToomas Soome     if (!rrcachestorage) rrcachesize = 0;
14500c65ebfc7SToomas Soome 
14501c65ebfc7SToomas Soome     m->p                             = p;
14502c65ebfc7SToomas Soome     m->NetworkChanged                = 0;
14503c65ebfc7SToomas Soome     m->CanReceiveUnicastOn5353       = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14504c65ebfc7SToomas Soome     m->AdvertiseLocalAddresses       = AdvertiseLocalAddresses;
14505c65ebfc7SToomas Soome     m->DivertMulticastAdvertisements = mDNSfalse;
14506c65ebfc7SToomas Soome     m->mDNSPlatformStatus            = mStatus_Waiting;
14507c65ebfc7SToomas Soome     m->UnicastPort4                  = zeroIPPort;
14508c65ebfc7SToomas Soome     m->UnicastPort6                  = zeroIPPort;
14509c65ebfc7SToomas Soome     m->PrimaryMAC                    = zeroEthAddr;
14510c65ebfc7SToomas Soome     m->MainCallback                  = Callback;
14511c65ebfc7SToomas Soome     m->MainContext                   = Context;
14512c65ebfc7SToomas Soome     m->rec.r.resrec.RecordType       = 0;
14513c65ebfc7SToomas Soome 
14514c65ebfc7SToomas Soome     // For debugging: To catch and report locking failures
14515c65ebfc7SToomas Soome     m->mDNS_busy               = 0;
14516c65ebfc7SToomas Soome     m->mDNS_reentrancy         = 0;
14517c65ebfc7SToomas Soome     m->ShutdownTime            = 0;
14518c65ebfc7SToomas Soome     m->lock_rrcache            = 0;
14519c65ebfc7SToomas Soome     m->lock_Questions          = 0;
14520c65ebfc7SToomas Soome     m->lock_Records            = 0;
14521c65ebfc7SToomas Soome 
14522c65ebfc7SToomas Soome     // Task Scheduling variables
14523c65ebfc7SToomas Soome     result = mDNSPlatformTimeInit();
14524c65ebfc7SToomas Soome     if (result != mStatus_NoError) return(result);
14525c65ebfc7SToomas Soome     m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14526c65ebfc7SToomas Soome     timenow = mDNS_TimeNow_NoLock(m);
14527c65ebfc7SToomas Soome 
14528c65ebfc7SToomas Soome     m->timenow                 = 0;     // MUST only be set within mDNS_Lock/mDNS_Unlock section
14529c65ebfc7SToomas Soome     m->timenow_last            = timenow;
14530c65ebfc7SToomas Soome     m->NextScheduledEvent      = timenow;
14531c65ebfc7SToomas Soome     m->SuppressSending         = timenow;
14532c65ebfc7SToomas Soome     m->NextCacheCheck          = timenow + FutureTime;
14533c65ebfc7SToomas Soome     m->NextScheduledQuery      = timenow + FutureTime;
14534c65ebfc7SToomas Soome     m->NextScheduledProbe      = timenow + FutureTime;
14535c65ebfc7SToomas Soome     m->NextScheduledResponse   = timenow + FutureTime;
14536c65ebfc7SToomas Soome     m->NextScheduledNATOp      = timenow + FutureTime;
14537c65ebfc7SToomas Soome     m->NextScheduledSPS        = timenow + FutureTime;
14538c65ebfc7SToomas Soome     m->NextScheduledKA         = timenow + FutureTime;
14539c65ebfc7SToomas Soome     m->NextScheduledStopTime   = timenow + FutureTime;
14540c65ebfc7SToomas Soome     m->NextBLEServiceTime      = 0;    // zero indicates inactive
14541c65ebfc7SToomas Soome 
14542*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14543c65ebfc7SToomas Soome     m->NextBonjourDisableTime  = 0; // Timer active when non zero.
14544c65ebfc7SToomas Soome     m->BonjourEnabled          = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14545*472cd20dSToomas Soome #endif
14546c65ebfc7SToomas Soome 
14547c65ebfc7SToomas Soome     m->RandomQueryDelay        = 0;
14548c65ebfc7SToomas Soome     m->RandomReconfirmDelay    = 0;
14549c65ebfc7SToomas Soome     m->PktNum                  = 0;
14550c65ebfc7SToomas Soome     m->MPktNum                 = 0;
14551c65ebfc7SToomas Soome     m->LocalRemoveEvents       = mDNSfalse;
14552c65ebfc7SToomas Soome     m->SleepState              = SleepState_Awake;
14553c65ebfc7SToomas Soome     m->SleepSeqNum             = 0;
14554c65ebfc7SToomas Soome     m->SystemWakeOnLANEnabled  = mDNSfalse;
14555c65ebfc7SToomas Soome     m->AnnounceOwner           = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14556c65ebfc7SToomas Soome     m->DelaySleep              = 0;
14557c65ebfc7SToomas Soome     m->SleepLimit              = 0;
14558c65ebfc7SToomas Soome 
14559c65ebfc7SToomas Soome #if APPLE_OSX_mDNSResponder
14560c65ebfc7SToomas Soome     m->UnicastPacketsSent      = 0;
14561c65ebfc7SToomas Soome     m->MulticastPacketsSent    = 0;
14562c65ebfc7SToomas Soome     m->RemoteSubnet            = 0;
14563c65ebfc7SToomas Soome #endif // APPLE_OSX_mDNSResponder
14564c65ebfc7SToomas Soome 
14565c65ebfc7SToomas Soome     // These fields only required for mDNS Searcher...
14566c65ebfc7SToomas Soome     m->Questions               = mDNSNULL;
14567c65ebfc7SToomas Soome     m->NewQuestions            = mDNSNULL;
14568c65ebfc7SToomas Soome     m->CurrentQuestion         = mDNSNULL;
14569c65ebfc7SToomas Soome     m->LocalOnlyQuestions      = mDNSNULL;
14570c65ebfc7SToomas Soome     m->NewLocalOnlyQuestions   = mDNSNULL;
14571c65ebfc7SToomas Soome     m->RestartQuestion         = mDNSNULL;
14572c65ebfc7SToomas Soome     m->rrcache_size            = 0;
14573c65ebfc7SToomas Soome     m->rrcache_totalused       = 0;
14574c65ebfc7SToomas Soome     m->rrcache_active          = 0;
14575c65ebfc7SToomas Soome     m->rrcache_report          = 10;
14576c65ebfc7SToomas Soome     m->rrcache_free            = mDNSNULL;
14577c65ebfc7SToomas Soome 
14578c65ebfc7SToomas Soome     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14579c65ebfc7SToomas Soome     {
14580c65ebfc7SToomas Soome         m->rrcache_hash[slot]      = mDNSNULL;
14581c65ebfc7SToomas Soome         m->rrcache_nextcheck[slot] = timenow + FutureTime;;
14582c65ebfc7SToomas Soome     }
14583c65ebfc7SToomas Soome 
14584c65ebfc7SToomas Soome     mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14585c65ebfc7SToomas Soome     m->rrauth.rrauth_free            = mDNSNULL;
14586c65ebfc7SToomas Soome 
14587c65ebfc7SToomas Soome     for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14588c65ebfc7SToomas Soome         m->rrauth.rrauth_hash[slot] = mDNSNULL;
14589c65ebfc7SToomas Soome 
14590c65ebfc7SToomas Soome     // Fields below only required for mDNS Responder...
14591c65ebfc7SToomas Soome     m->hostlabel.c[0]          = 0;
14592c65ebfc7SToomas Soome     m->nicelabel.c[0]          = 0;
14593c65ebfc7SToomas Soome     m->MulticastHostname.c[0]  = 0;
14594*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14595*472cd20dSToomas Soome     m->RandomizedHostname.c[0] = 0;
14596*472cd20dSToomas Soome #endif
14597c65ebfc7SToomas Soome     m->HIHardware.c[0]         = 0;
14598c65ebfc7SToomas Soome     m->HISoftware.c[0]         = 0;
14599c65ebfc7SToomas Soome     m->ResourceRecords         = mDNSNULL;
14600c65ebfc7SToomas Soome     m->DuplicateRecords        = mDNSNULL;
14601c65ebfc7SToomas Soome     m->NewLocalRecords         = mDNSNULL;
14602c65ebfc7SToomas Soome     m->NewLocalOnlyRecords     = mDNSfalse;
14603c65ebfc7SToomas Soome     m->CurrentRecord           = mDNSNULL;
14604c65ebfc7SToomas Soome     m->HostInterfaces          = mDNSNULL;
14605c65ebfc7SToomas Soome     m->ProbeFailTime           = 0;
14606c65ebfc7SToomas Soome     m->NumFailedProbes         = 0;
14607c65ebfc7SToomas Soome     m->SuppressProbes          = 0;
14608c65ebfc7SToomas Soome 
14609c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
14610c65ebfc7SToomas Soome     m->NextuDNSEvent            = timenow + FutureTime;
14611c65ebfc7SToomas Soome     m->NextSRVUpdate            = timenow + FutureTime;
14612c65ebfc7SToomas Soome 
14613*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14614c65ebfc7SToomas Soome     m->DNSServers               = mDNSNULL;
14615*472cd20dSToomas Soome #endif
14616c65ebfc7SToomas Soome 
14617c65ebfc7SToomas Soome     m->Router                   = zeroAddr;
14618c65ebfc7SToomas Soome     m->AdvertisedV4             = zeroAddr;
14619c65ebfc7SToomas Soome     m->AdvertisedV6             = zeroAddr;
14620c65ebfc7SToomas Soome 
14621c65ebfc7SToomas Soome     m->AuthInfoList             = mDNSNULL;
14622c65ebfc7SToomas Soome 
14623c65ebfc7SToomas Soome     m->ReverseMap.ThisQInterval = -1;
14624c65ebfc7SToomas Soome     m->StaticHostname.c[0]      = 0;
14625c65ebfc7SToomas Soome     m->FQDN.c[0]                = 0;
14626c65ebfc7SToomas Soome     m->Hostnames                = mDNSNULL;
14627c65ebfc7SToomas Soome 
14628c65ebfc7SToomas Soome     m->WABBrowseQueriesCount    = 0;
14629c65ebfc7SToomas Soome     m->WABLBrowseQueriesCount   = 0;
14630c65ebfc7SToomas Soome     m->WABRegQueriesCount       = 0;
14631c65ebfc7SToomas Soome     m->AutoTargetServices       = 1;
14632c65ebfc7SToomas Soome 
14633*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14634c65ebfc7SToomas Soome     m->NumAllInterfaceRecords   = 0;
14635c65ebfc7SToomas Soome     m->NumAllInterfaceQuestions = 0;
14636c65ebfc7SToomas Soome #endif
14637c65ebfc7SToomas Soome     // NAT traversal fields
14638c65ebfc7SToomas Soome     m->LLQNAT.clientCallback    = mDNSNULL;
14639c65ebfc7SToomas Soome     m->LLQNAT.clientContext     = mDNSNULL;
14640c65ebfc7SToomas Soome     m->NATTraversals            = mDNSNULL;
14641c65ebfc7SToomas Soome     m->CurrentNATTraversal      = mDNSNULL;
14642c65ebfc7SToomas Soome     m->retryIntervalGetAddr     = 0;    // delta between time sent and retry
14643c65ebfc7SToomas Soome     m->retryGetAddr             = timenow + FutureTime; // absolute time when we retry
14644c65ebfc7SToomas Soome     m->ExtAddress               = zerov4Addr;
14645c65ebfc7SToomas Soome     m->PCPNonce[0]              = mDNSRandom(-1);
14646c65ebfc7SToomas Soome     m->PCPNonce[1]              = mDNSRandom(-1);
14647c65ebfc7SToomas Soome     m->PCPNonce[2]              = mDNSRandom(-1);
14648c65ebfc7SToomas Soome 
14649c65ebfc7SToomas Soome     m->NATMcastRecvskt          = mDNSNULL;
14650c65ebfc7SToomas Soome     m->LastNATupseconds         = 0;
14651c65ebfc7SToomas Soome     m->LastNATReplyLocalTime    = timenow;
14652c65ebfc7SToomas Soome     m->LastNATMapResultCode     = NATErr_None;
14653c65ebfc7SToomas Soome 
14654c65ebfc7SToomas Soome     m->UPnPInterfaceID          = 0;
14655c65ebfc7SToomas Soome     m->SSDPSocket               = mDNSNULL;
14656c65ebfc7SToomas Soome     m->SSDPWANPPPConnection     = mDNSfalse;
14657c65ebfc7SToomas Soome     m->UPnPRouterPort           = zeroIPPort;
14658c65ebfc7SToomas Soome     m->UPnPSOAPPort             = zeroIPPort;
14659c65ebfc7SToomas Soome     m->UPnPRouterURL            = mDNSNULL;
14660c65ebfc7SToomas Soome     m->UPnPWANPPPConnection     = mDNSfalse;
14661c65ebfc7SToomas Soome     m->UPnPSOAPURL              = mDNSNULL;
14662c65ebfc7SToomas Soome     m->UPnPRouterAddressString  = mDNSNULL;
14663c65ebfc7SToomas Soome     m->UPnPSOAPAddressString    = mDNSNULL;
14664c65ebfc7SToomas Soome     m->SPSType                  = 0;
14665c65ebfc7SToomas Soome     m->SPSPortability           = 0;
14666c65ebfc7SToomas Soome     m->SPSMarginalPower         = 0;
14667c65ebfc7SToomas Soome     m->SPSTotalPower            = 0;
14668c65ebfc7SToomas Soome     m->SPSFeatureFlags          = 0;
14669c65ebfc7SToomas Soome     m->SPSState                 = 0;
14670c65ebfc7SToomas Soome     m->SPSProxyListChanged      = mDNSNULL;
14671c65ebfc7SToomas Soome     m->SPSSocket                = mDNSNULL;
14672c65ebfc7SToomas Soome     m->SPSBrowseCallback        = mDNSNULL;
14673c65ebfc7SToomas Soome     m->ProxyRecords             = 0;
14674c65ebfc7SToomas Soome 
14675c65ebfc7SToomas Soome     m->DNSPushServers           = mDNSNULL;
14676c65ebfc7SToomas Soome     m->DNSPushZones             = mDNSNULL;
14677c65ebfc7SToomas Soome #endif
14678c65ebfc7SToomas Soome 
14679*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14680*472cd20dSToomas Soome     if (WCFConnectionNew)
14681c65ebfc7SToomas Soome     {
14682c65ebfc7SToomas Soome         m->WCF = WCFConnectionNew();
14683c65ebfc7SToomas Soome         if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14684c65ebfc7SToomas Soome     }
14685c65ebfc7SToomas Soome #endif
14686c65ebfc7SToomas Soome 
14687*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
14688*472cd20dSToomas Soome     result = init_and_load_trust_anchors();
14689*472cd20dSToomas Soome     if (result != mStatus_NoError) return(result);
14690c65ebfc7SToomas Soome #endif
14691c65ebfc7SToomas Soome 
14692c65ebfc7SToomas Soome     return(result);
14693c65ebfc7SToomas Soome }
14694c65ebfc7SToomas Soome 
mDNS_Init(mDNS * const m,mDNS_PlatformSupport * const p,CacheEntity * rrcachestorage,mDNSu32 rrcachesize,mDNSBool AdvertiseLocalAddresses,mDNSCallback * Callback,void * Context)14695c65ebfc7SToomas Soome mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14696c65ebfc7SToomas Soome                              CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14697c65ebfc7SToomas Soome                              mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14698c65ebfc7SToomas Soome {
14699c65ebfc7SToomas Soome     mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context);
14700c65ebfc7SToomas Soome     if (result != mStatus_NoError)
14701c65ebfc7SToomas Soome         return(result);
14702c65ebfc7SToomas Soome 
14703*472cd20dSToomas Soome #if MDNS_MALLOC_DEBUGGING
14704*472cd20dSToomas Soome     static mDNSListValidator lv;
14705*472cd20dSToomas Soome     mDNSPlatformAddListValidator(&lv, mDNS_ValidateLists, "mDNS_ValidateLists", m);
14706*472cd20dSToomas Soome #endif
14707c65ebfc7SToomas Soome     result = mDNSPlatformInit(m);
14708c65ebfc7SToomas Soome 
14709c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
14710c65ebfc7SToomas Soome     // It's better to do this *after* the platform layer has set up the
14711c65ebfc7SToomas Soome     // interface list and security credentials
14712c65ebfc7SToomas Soome     uDNS_SetupDNSConfig(m);                     // Get initial DNS configuration
14713c65ebfc7SToomas Soome #endif
14714c65ebfc7SToomas Soome 
14715c65ebfc7SToomas Soome     return(result);
14716c65ebfc7SToomas Soome }
14717c65ebfc7SToomas Soome 
mDNS_ConfigChanged(mDNS * const m)14718c65ebfc7SToomas Soome mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14719c65ebfc7SToomas Soome {
14720c65ebfc7SToomas Soome     if (m->SPSState == 1)
14721c65ebfc7SToomas Soome     {
14722c65ebfc7SToomas Soome         domainlabel name, newname;
14723c65ebfc7SToomas Soome #ifndef SPC_DISABLED
14724c65ebfc7SToomas Soome         domainname type, domain;
14725c65ebfc7SToomas Soome         DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14726c65ebfc7SToomas Soome #endif // SPC_DISABLED
14727c65ebfc7SToomas Soome         ConstructSleepProxyServerName(m, &newname);
14728c65ebfc7SToomas Soome         if (!SameDomainLabelCS(name.c, newname.c))
14729c65ebfc7SToomas Soome         {
14730c65ebfc7SToomas Soome             LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14731c65ebfc7SToomas Soome             // When SleepProxyServerCallback gets the mStatus_MemFree message,
14732c65ebfc7SToomas Soome             // it will reregister the service under the new name
14733c65ebfc7SToomas Soome             m->SPSState = 2;
14734c65ebfc7SToomas Soome #ifndef SPC_DISABLED
14735c65ebfc7SToomas Soome             mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14736c65ebfc7SToomas Soome #endif // SPC_DISABLED
14737c65ebfc7SToomas Soome         }
14738c65ebfc7SToomas Soome     }
14739c65ebfc7SToomas Soome 
14740c65ebfc7SToomas Soome     if (m->MainCallback)
14741c65ebfc7SToomas Soome         m->MainCallback(m, mStatus_ConfigChanged);
14742c65ebfc7SToomas Soome }
14743c65ebfc7SToomas Soome 
DynDNSHostNameCallback(mDNS * const m,AuthRecord * const rr,mStatus result)14744c65ebfc7SToomas Soome mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14745c65ebfc7SToomas Soome {
14746c65ebfc7SToomas Soome     (void)m;    // unused
14747c65ebfc7SToomas Soome     debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14748c65ebfc7SToomas Soome     mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14749c65ebfc7SToomas Soome }
14750c65ebfc7SToomas Soome 
14751*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
PurgeOrReconfirmCacheRecord(mDNS * const m,CacheRecord * cr)14752*472cd20dSToomas Soome mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr)
14753c65ebfc7SToomas Soome {
14754c65ebfc7SToomas Soome     mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14755c65ebfc7SToomas Soome                      cr->resrec.rrtype     == kDNSType_A ||
14756c65ebfc7SToomas Soome                      cr->resrec.rrtype     == kDNSType_AAAA ||
14757c65ebfc7SToomas Soome                      cr->resrec.rrtype     == kDNSType_SRV ||
14758c65ebfc7SToomas Soome                      cr->resrec.rrtype     == kDNSType_CNAME;
14759c65ebfc7SToomas Soome 
14760*472cd20dSToomas Soome     debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14761c65ebfc7SToomas Soome            purge    ? "purging"   : "reconfirming",
14762*472cd20dSToomas Soome            cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
14763*472cd20dSToomas Soome            cr->resrec.rDNSServer ? mDNSVal16(cr->resrec.rDNSServer->port) : -1,
14764*472cd20dSToomas Soome            cr->resrec.rDNSServer ? cr->resrec.rDNSServer->domain.c : mDNSNULL, CRDisplayString(m, cr));
14765c65ebfc7SToomas Soome 
14766c65ebfc7SToomas Soome     if (purge)
14767c65ebfc7SToomas Soome     {
14768c65ebfc7SToomas Soome         LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14769c65ebfc7SToomas Soome         mDNS_PurgeCacheResourceRecord(m, cr);
14770c65ebfc7SToomas Soome     }
14771c65ebfc7SToomas Soome     else
14772c65ebfc7SToomas Soome     {
14773c65ebfc7SToomas Soome         LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14774c65ebfc7SToomas Soome         mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14775c65ebfc7SToomas Soome     }
14776c65ebfc7SToomas Soome }
14777*472cd20dSToomas Soome #endif
14778c65ebfc7SToomas Soome 
mDNS_PurgeBeforeResolve(mDNS * const m,DNSQuestion * q)147793b436d06SToomas Soome mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
14780c65ebfc7SToomas Soome {
14781c65ebfc7SToomas Soome     CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14782c65ebfc7SToomas Soome     CacheRecord *rp;
14783c65ebfc7SToomas Soome     for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14784c65ebfc7SToomas Soome     {
14785*472cd20dSToomas Soome         if (SameNameCacheRecordAnswersQuestion(rp, q))
14786c65ebfc7SToomas Soome         {
147873b436d06SToomas Soome             LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
14788c65ebfc7SToomas Soome             mDNS_PurgeCacheResourceRecord(m, rp);
14789c65ebfc7SToomas Soome         }
14790c65ebfc7SToomas Soome     }
14791c65ebfc7SToomas Soome }
14792c65ebfc7SToomas Soome 
14793*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
DNSServerChangeForQuestion(mDNS * const m,DNSQuestion * q,DNSServer * new)14794c65ebfc7SToomas Soome mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14795c65ebfc7SToomas Soome {
14796c65ebfc7SToomas Soome     DNSQuestion *qptr;
14797c65ebfc7SToomas Soome 
14798c65ebfc7SToomas Soome     (void) m;
14799c65ebfc7SToomas Soome 
14800c65ebfc7SToomas Soome     if (q->DuplicateOf)
14801c65ebfc7SToomas Soome         LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14802c65ebfc7SToomas Soome 
14803c65ebfc7SToomas Soome     // Make sure all the duplicate questions point to the same DNSServer so that delivery
14804c65ebfc7SToomas Soome     // of events for all of them are consistent. Duplicates for a question are always inserted
14805c65ebfc7SToomas Soome     // after in the list.
14806c65ebfc7SToomas Soome     q->qDNSServer = new;
14807c65ebfc7SToomas Soome     for (qptr = q->next ; qptr; qptr = qptr->next)
14808c65ebfc7SToomas Soome     {
14809c65ebfc7SToomas Soome         if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14810c65ebfc7SToomas Soome     }
14811c65ebfc7SToomas Soome }
14812*472cd20dSToomas Soome #endif
14813c65ebfc7SToomas Soome 
SetConfigState(mDNS * const m,mDNSBool delete)14814c65ebfc7SToomas Soome mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14815c65ebfc7SToomas Soome {
14816c65ebfc7SToomas Soome     McastResolver *mr;
14817*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14818c65ebfc7SToomas Soome     DNSServer *ptr;
14819*472cd20dSToomas Soome #endif
14820c65ebfc7SToomas Soome 
14821c65ebfc7SToomas Soome     if (delete)
14822c65ebfc7SToomas Soome     {
14823*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14824c65ebfc7SToomas Soome         for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14825c65ebfc7SToomas Soome         {
14826c65ebfc7SToomas Soome             ptr->penaltyTime = 0;
14827*472cd20dSToomas Soome             ptr->flags |= DNSServerFlag_Delete;
14828*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14829*472cd20dSToomas Soome             if (ptr->flags & DNSServerFlag_Unreachable)
14830c65ebfc7SToomas Soome                 NumUnreachableDNSServers--;
14831c65ebfc7SToomas Soome #endif
14832c65ebfc7SToomas Soome         }
14833*472cd20dSToomas Soome #endif
14834c65ebfc7SToomas Soome         // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14835c65ebfc7SToomas Soome         // mcast resolvers. Today we get both mcast and ucast configuration using the same
14836c65ebfc7SToomas Soome         // API
14837c65ebfc7SToomas Soome         for (mr = m->McastResolvers; mr; mr = mr->next)
14838c65ebfc7SToomas Soome             mr->flags |= McastResolver_FlagDelete;
14839c65ebfc7SToomas Soome     }
14840c65ebfc7SToomas Soome     else
14841c65ebfc7SToomas Soome     {
14842*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14843c65ebfc7SToomas Soome         for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14844c65ebfc7SToomas Soome         {
14845c65ebfc7SToomas Soome             ptr->penaltyTime = 0;
14846*472cd20dSToomas Soome             ptr->flags &= ~DNSServerFlag_Delete;
14847*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14848*472cd20dSToomas Soome             if (ptr->flags & DNSServerFlag_Unreachable)
14849c65ebfc7SToomas Soome                 NumUnreachableDNSServers++;
14850c65ebfc7SToomas Soome #endif
14851c65ebfc7SToomas Soome         }
14852*472cd20dSToomas Soome #endif
14853c65ebfc7SToomas Soome         for (mr = m->McastResolvers; mr; mr = mr->next)
14854c65ebfc7SToomas Soome             mr->flags &= ~McastResolver_FlagDelete;
14855c65ebfc7SToomas Soome     }
14856c65ebfc7SToomas Soome }
14857c65ebfc7SToomas Soome 
SetDynDNSHostNameIfChanged(mDNS * const m,domainname * const fqdn)14858c65ebfc7SToomas Soome mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn)
14859c65ebfc7SToomas Soome {
14860c65ebfc7SToomas Soome     // Did our FQDN change?
14861c65ebfc7SToomas Soome     if (!SameDomainName(fqdn, &m->FQDN))
14862c65ebfc7SToomas Soome     {
14863c65ebfc7SToomas Soome         if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14864c65ebfc7SToomas Soome 
14865c65ebfc7SToomas Soome         AssignDomainName(&m->FQDN, fqdn);
14866c65ebfc7SToomas Soome 
14867c65ebfc7SToomas Soome         if (m->FQDN.c[0])
14868c65ebfc7SToomas Soome         {
14869c65ebfc7SToomas Soome             mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14870c65ebfc7SToomas Soome             mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14871c65ebfc7SToomas Soome         }
14872c65ebfc7SToomas Soome     }
14873c65ebfc7SToomas Soome }
14874c65ebfc7SToomas Soome 
14875*472cd20dSToomas Soome // Even though this is called “Setup” it is not called just once at startup.
14876*472cd20dSToomas Soome // It’s actually called multiple times, every time there’s a configuration change.
uDNS_SetupDNSConfig(mDNS * const m)14877c65ebfc7SToomas Soome mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14878c65ebfc7SToomas Soome {
14879*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14880c65ebfc7SToomas Soome     mDNSu32 slot;
14881c65ebfc7SToomas Soome     CacheGroup *cg;
14882c65ebfc7SToomas Soome     CacheRecord *cr;
14883*472cd20dSToomas Soome #endif
14884c65ebfc7SToomas Soome     mDNSAddr v4, v6, r;
14885c65ebfc7SToomas Soome     domainname fqdn;
14886*472cd20dSToomas Soome #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14887c65ebfc7SToomas Soome     DNSServer   *ptr, **p = &m->DNSServers;
14888c65ebfc7SToomas Soome     const DNSServer *oldServers = m->DNSServers;
14889c65ebfc7SToomas Soome     DNSQuestion *q;
14890*472cd20dSToomas Soome #endif
14891c65ebfc7SToomas Soome     McastResolver *mr, **mres = &m->McastResolvers;
14892*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14893*472cd20dSToomas Soome     DNSPushNotificationServer **psp;
14894*472cd20dSToomas Soome #endif
14895c65ebfc7SToomas Soome 
14896c65ebfc7SToomas Soome     debugf("uDNS_SetupDNSConfig: entry");
14897c65ebfc7SToomas Soome 
14898c65ebfc7SToomas Soome     // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14899c65ebfc7SToomas Soome     uDNS_SetupWABQueries(m);
14900c65ebfc7SToomas Soome 
14901c65ebfc7SToomas Soome     mDNS_Lock(m);
14902c65ebfc7SToomas Soome 
14903c65ebfc7SToomas Soome     // We need to first mark all the entries to be deleted. If the configuration changed, then
14904c65ebfc7SToomas Soome     // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14905c65ebfc7SToomas Soome     //
14906c65ebfc7SToomas Soome     // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14907c65ebfc7SToomas Soome     // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14908c65ebfc7SToomas Soome     // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14909c65ebfc7SToomas Soome     // for the dns configuration change notification.
14910c65ebfc7SToomas Soome     SetConfigState(m, mDNStrue);
14911c65ebfc7SToomas Soome     if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14912c65ebfc7SToomas Soome     {
14913c65ebfc7SToomas Soome         SetDynDNSHostNameIfChanged(m, &fqdn);
14914c65ebfc7SToomas Soome         SetConfigState(m, mDNSfalse);
14915c65ebfc7SToomas Soome         mDNS_Unlock(m);
14916c65ebfc7SToomas Soome         LogInfo("uDNS_SetupDNSConfig: No configuration change");
14917c65ebfc7SToomas Soome         return mStatus_NoError;
14918c65ebfc7SToomas Soome     }
14919c65ebfc7SToomas Soome 
14920c65ebfc7SToomas Soome     // For now, we just delete the mcast resolvers. We don't deal with cache or
14921c65ebfc7SToomas Soome     // questions here. Neither question nor cache point to mcast resolvers. Questions
14922c65ebfc7SToomas Soome     // do inherit the timeout values from mcast resolvers. But we don't bother
14923c65ebfc7SToomas Soome     // affecting them as they never change.
14924c65ebfc7SToomas Soome     while (*mres)
14925c65ebfc7SToomas Soome     {
14926c65ebfc7SToomas Soome         if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14927c65ebfc7SToomas Soome         {
14928c65ebfc7SToomas Soome             mr = *mres;
14929c65ebfc7SToomas Soome             *mres = (*mres)->next;
14930c65ebfc7SToomas Soome             debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14931c65ebfc7SToomas Soome             mDNSPlatformMemFree(mr);
14932c65ebfc7SToomas Soome         }
14933c65ebfc7SToomas Soome         else
14934c65ebfc7SToomas Soome         {
14935c65ebfc7SToomas Soome             (*mres)->flags &= ~McastResolver_FlagNew;
14936c65ebfc7SToomas Soome             mres = &(*mres)->next;
14937c65ebfc7SToomas Soome         }
14938c65ebfc7SToomas Soome     }
14939c65ebfc7SToomas Soome 
14940*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14941*472cd20dSToomas Soome     Querier_ProcessDNSServiceChanges();
14942*472cd20dSToomas Soome #else
14943c65ebfc7SToomas Soome     // Update our qDNSServer pointers before we go and free the DNSServer object memory
14944c65ebfc7SToomas Soome     //
14945c65ebfc7SToomas Soome     // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14946c65ebfc7SToomas Soome     // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14947c65ebfc7SToomas Soome     // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14948c65ebfc7SToomas Soome     // DNSServers and flush the cache.
14949c65ebfc7SToomas Soome     //
14950c65ebfc7SToomas Soome     // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14951c65ebfc7SToomas Soome     //   is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14952c65ebfc7SToomas Soome     //   flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14953c65ebfc7SToomas Soome     //   pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14954c65ebfc7SToomas Soome     //   flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14955c65ebfc7SToomas Soome     //   later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14956c65ebfc7SToomas Soome     //   we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14957c65ebfc7SToomas Soome     //   the same resGroupID.
14958c65ebfc7SToomas Soome     //
14959c65ebfc7SToomas Soome     //   Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14960c65ebfc7SToomas Soome     //   of the old followed by ADD of the new records.
14961c65ebfc7SToomas Soome     //
14962c65ebfc7SToomas Soome     // - A non-scoped question picks DNSServer X,  creates a cache entry with X. If the resolver gets removed later, we will
14963c65ebfc7SToomas Soome     //   pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14964c65ebfc7SToomas Soome     //   as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14965c65ebfc7SToomas Soome     //
14966c65ebfc7SToomas Soome     // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14967c65ebfc7SToomas Soome     //   cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14968c65ebfc7SToomas Soome     //   non-scoped question and vice versa.
14969c65ebfc7SToomas Soome     //
14970*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14971c65ebfc7SToomas Soome     DNS64RestartQuestions(m);
14972c65ebfc7SToomas Soome #endif
14973*472cd20dSToomas Soome 
14974*472cd20dSToomas Soome     // First, restart questions whose suppression status will change. The suppression status of each question in a given
14975*472cd20dSToomas Soome     // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14976*472cd20dSToomas Soome     // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14977*472cd20dSToomas Soome     // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14978*472cd20dSToomas Soome     // suppressed (or non-suppressed).
14979c65ebfc7SToomas Soome     for (q = m->Questions; q; q = q->next)
14980c65ebfc7SToomas Soome     {
14981*472cd20dSToomas Soome         DNSServer *s;
14982*472cd20dSToomas Soome         const DNSServer *t;
14983*472cd20dSToomas Soome         mDNSBool oldSuppressed;
14984*472cd20dSToomas Soome 
14985*472cd20dSToomas Soome         if (mDNSOpaque16IsZero(q->TargetQID)) continue;
14986*472cd20dSToomas Soome 
14987c65ebfc7SToomas Soome         SetValidDNSServers(m, q);
14988*472cd20dSToomas Soome         q->triedAllServersOnce = mDNSfalse;
14989c65ebfc7SToomas Soome         s = GetServerForQuestion(m, q);
14990c65ebfc7SToomas Soome         t = q->qDNSServer;
14991*472cd20dSToomas Soome         if (s != t)
14992c65ebfc7SToomas Soome         {
14993*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
14994*472cd20dSToomas Soome                 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR ":%d (" PRI_DM_NAME ") to "
14995*472cd20dSToomas Soome                 PRI_IP_ADDR ":%d (" PRI_DM_NAME ") for question " PRI_DM_NAME " (" PUB_S ") (scope:%p)",
14996*472cd20dSToomas Soome                 q->request_id, mDNSVal16(q->TargetQID),
14997*472cd20dSToomas Soome                 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), DM_NAME_PARAM(t ? &t->domain : mDNSNULL),
14998*472cd20dSToomas Soome                 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), DM_NAME_PARAM(s ? &s->domain : mDNSNULL),
14999*472cd20dSToomas Soome                 DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->InterfaceID);
15000*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15001*472cd20dSToomas Soome             // If this question had a DNS Push server associated with it, substitute the new server for the
15002*472cd20dSToomas Soome             // old one.   If there is no new server, then we'll clean up the push server later.
15003*472cd20dSToomas Soome             if (!q->DuplicateOf && (q->dnsPushServer != mDNSNULL))
15004c65ebfc7SToomas Soome             {
15005*472cd20dSToomas Soome                 if (q->dnsPushServer->qDNSServer == t)
15006c65ebfc7SToomas Soome                 {
15007*472cd20dSToomas Soome                     q->dnsPushServer->qDNSServer = s; // which might be null
15008c65ebfc7SToomas Soome                 }
15009*472cd20dSToomas Soome                 // If it is null, do the accounting and drop the push server.
15010*472cd20dSToomas Soome                 if (q->dnsPushServer->qDNSServer == mDNSNULL)
15011c65ebfc7SToomas Soome                 {
15012*472cd20dSToomas Soome                     DNSPushReconcileConnection(m, q);
15013c65ebfc7SToomas Soome                 }
15014c65ebfc7SToomas Soome             }
15015*472cd20dSToomas Soome #endif
15016c65ebfc7SToomas Soome         }
15017*472cd20dSToomas Soome         oldSuppressed = q->Suppressed;
15018*472cd20dSToomas Soome         q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15019*472cd20dSToomas Soome         if (!q->Suppressed != !oldSuppressed) q->Restart = mDNStrue;
15020c65ebfc7SToomas Soome     }
15021c65ebfc7SToomas Soome     RestartUnicastQuestions(m);
15022c65ebfc7SToomas Soome 
15023*472cd20dSToomas Soome     // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
15024*472cd20dSToomas Soome     // have already had their server changed by being restarted.
15025*472cd20dSToomas Soome     for (q = m->Questions; q; q = q->next)
15026*472cd20dSToomas Soome     {
15027*472cd20dSToomas Soome         DNSServer *s;
15028*472cd20dSToomas Soome         const DNSServer *t;
15029*472cd20dSToomas Soome 
15030*472cd20dSToomas Soome         if (mDNSOpaque16IsZero(q->TargetQID) || q->DuplicateOf) continue;
15031*472cd20dSToomas Soome 
15032*472cd20dSToomas Soome         SetValidDNSServers(m, q);
15033*472cd20dSToomas Soome         q->triedAllServersOnce = mDNSfalse;
15034*472cd20dSToomas Soome         s = GetServerForQuestion(m, q);
15035*472cd20dSToomas Soome         t = q->qDNSServer;
15036*472cd20dSToomas Soome         DNSServerChangeForQuestion(m, q, s);
15037*472cd20dSToomas Soome         if (s == t) continue;
15038*472cd20dSToomas Soome 
15039*472cd20dSToomas Soome         q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15040*472cd20dSToomas Soome         q->unansweredQueries = 0;
15041*472cd20dSToomas Soome         q->TargetQID = mDNS_NewMessageID(m);
15042*472cd20dSToomas Soome         if (!q->Suppressed) ActivateUnicastQuery(m, q, mDNStrue);
15043*472cd20dSToomas Soome     }
15044*472cd20dSToomas Soome 
15045*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15046*472cd20dSToomas Soome     // The above code may have found some DNS Push servers that are no longer valid.   Now that we
15047*472cd20dSToomas Soome     // are done running through the code, we need to drop our connections to those servers.
15048*472cd20dSToomas Soome     // When we get here, any such servers should have zero questions associated with them.
15049*472cd20dSToomas Soome     for (psp = &m->DNSPushServers; *psp != mDNSNULL; )
15050*472cd20dSToomas Soome     {
15051*472cd20dSToomas Soome         DNSPushNotificationServer *server = *psp;
15052*472cd20dSToomas Soome 
15053*472cd20dSToomas Soome         // It's possible that a push server whose DNS server has been deleted could be still connected but
15054*472cd20dSToomas Soome         // not referenced by any questions.  In this case, we just delete the push server rather than trying
15055*472cd20dSToomas Soome         // to figure out with which DNS server (if any) to associate it.
15056*472cd20dSToomas Soome         if (server->qDNSServer != mDNSNULL && server->qDNSServer->flags & DNSServerFlag_Delete)
15057*472cd20dSToomas Soome         {
15058*472cd20dSToomas Soome             server->qDNSServer = mDNSNULL;
15059*472cd20dSToomas Soome         }
15060*472cd20dSToomas Soome 
15061*472cd20dSToomas Soome         if (server->qDNSServer == mDNSNULL)
15062*472cd20dSToomas Soome         {
15063*472cd20dSToomas Soome             // This would be a programming error, so should never happen.
15064*472cd20dSToomas Soome             if (server->numberOfQuestions != 0)
15065*472cd20dSToomas Soome             {
15066*472cd20dSToomas Soome                 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server->serverName);
15067*472cd20dSToomas Soome             }
15068*472cd20dSToomas Soome             DNSPushServerDrop(server);
15069*472cd20dSToomas Soome             *psp = server->next;
15070*472cd20dSToomas Soome             mDNSPlatformMemFree(server);
15071*472cd20dSToomas Soome         }
15072*472cd20dSToomas Soome         else
15073*472cd20dSToomas Soome         {
15074*472cd20dSToomas Soome             psp = &(*psp)->next;
15075*472cd20dSToomas Soome         }
15076*472cd20dSToomas Soome     }
15077*472cd20dSToomas Soome #endif
15078*472cd20dSToomas Soome 
15079c65ebfc7SToomas Soome     FORALL_CACHERECORDS(slot, cg, cr)
15080c65ebfc7SToomas Soome     {
15081*472cd20dSToomas Soome         if (cr->resrec.InterfaceID) continue;
15082c65ebfc7SToomas Soome 
15083c65ebfc7SToomas Soome         // We already walked the questions and restarted/reactivated them if the dns server
15084c65ebfc7SToomas Soome         // change affected the question. That should take care of updating the cache. But
15085c65ebfc7SToomas Soome         // what if there is no active question at this point when the DNS server change
15086c65ebfc7SToomas Soome         // happened ? There could be old cache entries lying around and if we don't flush
15087c65ebfc7SToomas Soome         // them, a new question after the DNS server change could pick up these stale
15088c65ebfc7SToomas Soome         // entries and get a wrong answer.
15089c65ebfc7SToomas Soome         //
15090c65ebfc7SToomas Soome         // For cache entries that have active questions we might have skipped rescheduling
15091c65ebfc7SToomas Soome         // the questions if they were suppressed (see above). To keep it simple, we walk
15092c65ebfc7SToomas Soome         // all the cache entries to make sure that there are no stale entries. We use the
15093c65ebfc7SToomas Soome         // active question's InterfaceID/ServiceID for looking up the right DNS server.
15094c65ebfc7SToomas Soome         //
15095c65ebfc7SToomas Soome         // Note: If GetServerForName returns NULL, it could either mean that there are no
15096c65ebfc7SToomas Soome         // DNS servers or no matching DNS servers for this question. In either case,
15097c65ebfc7SToomas Soome         // the cache should get purged below when we process deleted DNS servers.
15098c65ebfc7SToomas Soome 
15099*472cd20dSToomas Soome         if (cr->CRActiveQuestion)
15100*472cd20dSToomas Soome         {
15101c65ebfc7SToomas Soome             // Purge or Reconfirm if this cache entry would use the new DNS server
15102*472cd20dSToomas Soome             ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion->InterfaceID, cr->CRActiveQuestion->ServiceID);
15103c65ebfc7SToomas Soome             if (ptr && (ptr != cr->resrec.rDNSServer))
15104c65ebfc7SToomas Soome             {
15105*472cd20dSToomas Soome                 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15106*472cd20dSToomas Soome                         CRDisplayString(m, cr), &ptr->addr,
15107*472cd20dSToomas Soome                         cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL);
15108*472cd20dSToomas Soome                 PurgeOrReconfirmCacheRecord(m, cr);
15109c65ebfc7SToomas Soome 
15110c65ebfc7SToomas Soome                 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15111c65ebfc7SToomas Soome                 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15112*472cd20dSToomas Soome                 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion->qDNSServer)
15113c65ebfc7SToomas Soome                 {
15114*472cd20dSToomas Soome                     LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->CRActiveQuestion->qDNSServer->addr, CRDisplayString(m, cr));
15115c65ebfc7SToomas Soome                     cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer;
15116c65ebfc7SToomas Soome                 }
15117c65ebfc7SToomas Soome             }
15118c65ebfc7SToomas Soome 
15119*472cd20dSToomas Soome             if (cr->resrec.rDNSServer && cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15120c65ebfc7SToomas Soome             {
15121c65ebfc7SToomas Soome                 DNSQuestion *qptr = cr->CRActiveQuestion;
15122*472cd20dSToomas Soome                 if (qptr->qDNSServer == cr->resrec.rDNSServer)
15123c65ebfc7SToomas Soome                 {
15124c65ebfc7SToomas Soome                     LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s  Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15125*472cd20dSToomas Soome                            " to be freed", CRDisplayString(m, cr),
15126*472cd20dSToomas Soome                            qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15127*472cd20dSToomas Soome                            &cr->resrec.rDNSServer->addr);
15128c65ebfc7SToomas Soome                     qptr->validDNSServers = zeroOpaque128;
15129c65ebfc7SToomas Soome                     qptr->qDNSServer = mDNSNULL;
15130c65ebfc7SToomas Soome                     cr->resrec.rDNSServer = mDNSNULL;
15131c65ebfc7SToomas Soome                 }
15132c65ebfc7SToomas Soome                 else
15133c65ebfc7SToomas Soome                 {
15134c65ebfc7SToomas Soome                     LogInfo("uDNS_SetupDNSConfig: Cache Record %s,  Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15135*472cd20dSToomas Soome                             " resetting to  question's DNSServer Address %#a", CRDisplayString(m, cr),
15136*472cd20dSToomas Soome                             qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15137*472cd20dSToomas Soome                             &cr->resrec.rDNSServer->addr,
15138*472cd20dSToomas Soome                             qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL);
15139c65ebfc7SToomas Soome                     cr->resrec.rDNSServer = qptr->qDNSServer;
15140c65ebfc7SToomas Soome                 }
15141*472cd20dSToomas Soome                 PurgeOrReconfirmCacheRecord(m, cr);
15142c65ebfc7SToomas Soome             }
15143*472cd20dSToomas Soome         }
15144*472cd20dSToomas Soome         else if (!cr->resrec.rDNSServer || cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15145c65ebfc7SToomas Soome         {
15146*472cd20dSToomas Soome             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
15147*472cd20dSToomas Soome                 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S ", DNS server " PUB_S " " PRI_IP_ADDR " " PUB_S,
15148*472cd20dSToomas Soome                 CRDisplayString(m, cr), !cr->resrec.rDNSServer ? "(to be deleted)" : "",
15149*472cd20dSToomas Soome                 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
15150*472cd20dSToomas Soome                 cr->resrec.rDNSServer ? DNSScopeToString(cr->resrec.rDNSServer->scopeType) : "" );
15151c65ebfc7SToomas Soome             cr->resrec.rDNSServer = mDNSNULL;
15152*472cd20dSToomas Soome             mDNS_PurgeCacheResourceRecord(m, cr);
15153*472cd20dSToomas Soome         }
15154c65ebfc7SToomas Soome     }
15155c65ebfc7SToomas Soome 
15156*472cd20dSToomas Soome     //  Delete all the DNS servers that are flagged for deletion
15157*472cd20dSToomas Soome     while (*p)
15158*472cd20dSToomas Soome     {
15159*472cd20dSToomas Soome         if (((*p)->flags & DNSServerFlag_Delete) != 0)
15160*472cd20dSToomas Soome         {
15161*472cd20dSToomas Soome             ptr = *p;
15162c65ebfc7SToomas Soome             *p = (*p)->next;
15163*472cd20dSToomas Soome             LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
15164c65ebfc7SToomas Soome             mDNSPlatformMemFree(ptr);
15165c65ebfc7SToomas Soome         }
15166c65ebfc7SToomas Soome         else
15167c65ebfc7SToomas Soome         {
15168c65ebfc7SToomas Soome             p = &(*p)->next;
15169c65ebfc7SToomas Soome         }
15170c65ebfc7SToomas Soome     }
15171*472cd20dSToomas Soome     LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m));
15172c65ebfc7SToomas Soome 
15173c65ebfc7SToomas Soome     // 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).
15174c65ebfc7SToomas Soome     // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15175c65ebfc7SToomas Soome     // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15176c65ebfc7SToomas Soome     // 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.
15177c65ebfc7SToomas Soome     if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
15178c65ebfc7SToomas Soome     {
15179c65ebfc7SToomas Soome         int count = 0;
15180c65ebfc7SToomas Soome         FORALL_CACHERECORDS(slot, cg, cr)
15181c65ebfc7SToomas Soome         {
15182c65ebfc7SToomas Soome             if (!cr->resrec.InterfaceID)
15183c65ebfc7SToomas Soome             {
15184c65ebfc7SToomas Soome                 mDNS_PurgeCacheResourceRecord(m, cr);
15185c65ebfc7SToomas Soome                 count++;
15186c65ebfc7SToomas Soome             }
15187c65ebfc7SToomas Soome         }
15188c65ebfc7SToomas Soome         LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15189c65ebfc7SToomas Soome                 m->DNSServers ? "DNS server became" : "No DNS servers", count);
15190c65ebfc7SToomas Soome 
15191c65ebfc7SToomas Soome         // Force anything that needs to get zone data to get that information again
15192c65ebfc7SToomas Soome         RestartRecordGetZoneData(m);
15193c65ebfc7SToomas Soome     }
15194*472cd20dSToomas Soome #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
15195c65ebfc7SToomas Soome 
15196c65ebfc7SToomas Soome     SetDynDNSHostNameIfChanged(m, &fqdn);
15197c65ebfc7SToomas Soome 
15198c65ebfc7SToomas Soome     mDNS_Unlock(m);
15199c65ebfc7SToomas Soome 
15200c65ebfc7SToomas Soome     // handle router and primary interface changes
15201c65ebfc7SToomas Soome     v4 = v6 = r = zeroAddr;
15202c65ebfc7SToomas Soome     v4.type = r.type = mDNSAddrType_IPv4;
15203c65ebfc7SToomas Soome 
15204c65ebfc7SToomas Soome     if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
15205c65ebfc7SToomas Soome     {
15206c65ebfc7SToomas Soome         mDNS_SetPrimaryInterfaceInfo(m,
15207c65ebfc7SToomas Soome                                      !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
15208c65ebfc7SToomas Soome                                      !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
15209c65ebfc7SToomas Soome                                      !mDNSIPv4AddressIsZero(r.ip.v4) ? &r  : mDNSNULL);
15210c65ebfc7SToomas Soome     }
15211c65ebfc7SToomas Soome     else
15212c65ebfc7SToomas Soome     {
15213c65ebfc7SToomas Soome         mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
15214c65ebfc7SToomas Soome         if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
15215c65ebfc7SToomas Soome     }
15216c65ebfc7SToomas Soome 
15217*472cd20dSToomas Soome     debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m));
15218c65ebfc7SToomas Soome     return mStatus_NoError;
15219c65ebfc7SToomas Soome }
15220c65ebfc7SToomas Soome 
mDNSCoreInitComplete(mDNS * const m,mStatus result)15221c65ebfc7SToomas Soome mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
15222c65ebfc7SToomas Soome {
15223c65ebfc7SToomas Soome     m->mDNSPlatformStatus = result;
15224c65ebfc7SToomas Soome     if (m->MainCallback)
15225c65ebfc7SToomas Soome     {
15226c65ebfc7SToomas Soome         mDNS_Lock(m);
15227c65ebfc7SToomas Soome         mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
15228c65ebfc7SToomas Soome         m->MainCallback(m, mStatus_NoError);
15229c65ebfc7SToomas Soome         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
15230c65ebfc7SToomas Soome         mDNS_Unlock(m);
15231c65ebfc7SToomas Soome     }
15232c65ebfc7SToomas Soome }
15233c65ebfc7SToomas Soome 
DeregLoop(mDNS * const m,AuthRecord * const start)15234c65ebfc7SToomas Soome mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
15235c65ebfc7SToomas Soome {
15236c65ebfc7SToomas Soome     m->CurrentRecord = start;
15237c65ebfc7SToomas Soome     while (m->CurrentRecord)
15238c65ebfc7SToomas Soome     {
15239c65ebfc7SToomas Soome         AuthRecord *rr = m->CurrentRecord;
15240c65ebfc7SToomas Soome         LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15241c65ebfc7SToomas Soome                 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating  " : "Accelerating",
15242c65ebfc7SToomas Soome                 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15243c65ebfc7SToomas Soome         if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15244c65ebfc7SToomas Soome             mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15245c65ebfc7SToomas Soome         else if (rr->AnnounceCount > 1)
15246c65ebfc7SToomas Soome         {
15247c65ebfc7SToomas Soome             rr->AnnounceCount = 1;
15248c65ebfc7SToomas Soome             rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15249c65ebfc7SToomas Soome         }
15250c65ebfc7SToomas Soome         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15251c65ebfc7SToomas Soome         // new records could have been added to the end of the list as a result of that call.
15252c65ebfc7SToomas Soome         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15253c65ebfc7SToomas Soome             m->CurrentRecord = rr->next;
15254c65ebfc7SToomas Soome     }
15255c65ebfc7SToomas Soome }
15256c65ebfc7SToomas Soome 
mDNS_StartExit(mDNS * const m)15257c65ebfc7SToomas Soome mDNSexport void mDNS_StartExit(mDNS *const m)
15258c65ebfc7SToomas Soome {
15259c65ebfc7SToomas Soome     AuthRecord *rr;
15260c65ebfc7SToomas Soome 
15261c65ebfc7SToomas Soome     mDNS_Lock(m);
15262c65ebfc7SToomas Soome 
15263*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit");
15264c65ebfc7SToomas Soome     m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15265c65ebfc7SToomas Soome 
15266c65ebfc7SToomas Soome     mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15267c65ebfc7SToomas Soome 
15268*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15269*472cd20dSToomas Soome     if (WCFConnectionDealloc)
15270c65ebfc7SToomas Soome     {
15271*472cd20dSToomas Soome         if (m->WCF)
15272*472cd20dSToomas Soome         {
15273*472cd20dSToomas Soome             WCFConnectionDealloc(m->WCF);
15274*472cd20dSToomas Soome             m->WCF = mDNSNULL;
15275c65ebfc7SToomas Soome         }
15276*472cd20dSToomas Soome     }
15277c65ebfc7SToomas Soome #endif
15278c65ebfc7SToomas Soome 
15279c65ebfc7SToomas Soome #ifndef UNICAST_DISABLED
15280c65ebfc7SToomas Soome     {
15281c65ebfc7SToomas Soome         SearchListElem *s;
15282c65ebfc7SToomas Soome         SuspendLLQs(m);
15283c65ebfc7SToomas Soome         // Don't need to do SleepRecordRegistrations() here
15284c65ebfc7SToomas Soome         // because we deregister all records and services later in this routine
15285c65ebfc7SToomas Soome         while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15286c65ebfc7SToomas Soome 
15287c65ebfc7SToomas Soome         // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15288c65ebfc7SToomas Soome         // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15289c65ebfc7SToomas Soome         // and we may crash because the list still contains dangling pointers.
15290c65ebfc7SToomas Soome         for (s = SearchList; s; s = s->next)
15291c65ebfc7SToomas Soome             while (s->AuthRecs)
15292c65ebfc7SToomas Soome             {
15293c65ebfc7SToomas Soome                 ARListElem *dereg = s->AuthRecs;
15294c65ebfc7SToomas Soome                 s->AuthRecs = s->AuthRecs->next;
15295c65ebfc7SToomas Soome                 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15296c65ebfc7SToomas Soome             }
15297c65ebfc7SToomas Soome     }
15298c65ebfc7SToomas Soome #endif
15299c65ebfc7SToomas Soome 
15300*472cd20dSToomas Soome     DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_All);
15301c65ebfc7SToomas Soome 
15302c65ebfc7SToomas Soome     // Shut down all our active NAT Traversals
15303c65ebfc7SToomas Soome     while (m->NATTraversals)
15304c65ebfc7SToomas Soome     {
15305c65ebfc7SToomas Soome         NATTraversalInfo *t = m->NATTraversals;
15306c65ebfc7SToomas Soome         mDNS_StopNATOperation_internal(m, t);       // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15307c65ebfc7SToomas Soome 
15308c65ebfc7SToomas Soome         // After stopping the NAT Traversal, we zero out the fields.
15309c65ebfc7SToomas Soome         // This has particularly important implications for our AutoTunnel records --
15310c65ebfc7SToomas Soome         // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15311c65ebfc7SToomas Soome         // handlers to just turn around and attempt to re-register those same records.
15312c65ebfc7SToomas Soome         // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15313c65ebfc7SToomas Soome         // to not do this.
15314c65ebfc7SToomas Soome         t->ExternalAddress = zerov4Addr;
15315c65ebfc7SToomas Soome         t->NewAddress      = zerov4Addr;
15316c65ebfc7SToomas Soome         t->ExternalPort    = zeroIPPort;
15317c65ebfc7SToomas Soome         t->RequestedPort   = zeroIPPort;
15318c65ebfc7SToomas Soome         t->Lifetime        = 0;
15319c65ebfc7SToomas Soome         t->Result          = mStatus_NoError;
15320c65ebfc7SToomas Soome     }
15321c65ebfc7SToomas Soome 
15322c65ebfc7SToomas Soome     // Make sure there are nothing but deregistering records remaining in the list
15323c65ebfc7SToomas Soome     if (m->CurrentRecord)
15324*472cd20dSToomas Soome     {
15325*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
15326*472cd20dSToomas Soome             "mDNS_StartExit: ERROR m->CurrentRecord already set " PRI_S, ARDisplayString(m, m->CurrentRecord));
15327*472cd20dSToomas Soome     }
15328c65ebfc7SToomas Soome 
15329c65ebfc7SToomas Soome     // We're in the process of shutting down, so queries, etc. are no longer available.
15330c65ebfc7SToomas Soome     // Consequently, determining certain information, e.g. the uDNS update server's IP
15331c65ebfc7SToomas Soome     // address, will not be possible.  The records on the main list are more likely to
15332c65ebfc7SToomas Soome     // already contain such information, so we deregister the duplicate records first.
15333*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering duplicate resource records");
15334c65ebfc7SToomas Soome     DeregLoop(m, m->DuplicateRecords);
15335*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering resource records");
15336c65ebfc7SToomas Soome     DeregLoop(m, m->ResourceRecords);
15337c65ebfc7SToomas Soome 
15338c65ebfc7SToomas Soome     // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15339c65ebfc7SToomas Soome     // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15340c65ebfc7SToomas Soome     if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15341c65ebfc7SToomas Soome     {
15342c65ebfc7SToomas Soome         m->NextScheduledResponse = m->timenow;
15343c65ebfc7SToomas Soome         m->SuppressSending = 0;
15344c65ebfc7SToomas Soome     }
15345c65ebfc7SToomas Soome 
15346*472cd20dSToomas Soome     if (m->ResourceRecords)
15347*472cd20dSToomas Soome     {
15348*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Sending final record deregistrations");
15349*472cd20dSToomas Soome     }
15350*472cd20dSToomas Soome     else
15351*472cd20dSToomas Soome     {
15352*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: No deregistering records remain");
15353*472cd20dSToomas Soome     }
15354c65ebfc7SToomas Soome 
15355c65ebfc7SToomas Soome     for (rr = m->DuplicateRecords; rr; rr = rr->next)
15356*472cd20dSToomas Soome     {
15357*472cd20dSToomas Soome         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
15358*472cd20dSToomas Soome             "mDNS_StartExit: Should not still have Duplicate Records remaining: %02X " PRI_S,
15359*472cd20dSToomas Soome             rr->resrec.RecordType, ARDisplayString(m, rr));
15360*472cd20dSToomas Soome     }
15361c65ebfc7SToomas Soome 
15362c65ebfc7SToomas Soome     // If any deregistering records remain, send their deregistration announcements before we exit
15363c65ebfc7SToomas Soome     if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
15364c65ebfc7SToomas Soome 
15365c65ebfc7SToomas Soome     mDNS_Unlock(m);
15366c65ebfc7SToomas Soome 
15367*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: done");
15368c65ebfc7SToomas Soome }
15369c65ebfc7SToomas Soome 
mDNS_FinalExit(mDNS * const m)15370c65ebfc7SToomas Soome mDNSexport void mDNS_FinalExit(mDNS *const m)
15371c65ebfc7SToomas Soome {
15372c65ebfc7SToomas Soome     mDNSu32 rrcache_active = 0;
15373c65ebfc7SToomas Soome     mDNSu32 rrcache_totalused = m->rrcache_totalused;
15374c65ebfc7SToomas Soome     mDNSu32 slot;
15375c65ebfc7SToomas Soome     AuthRecord *rr;
15376c65ebfc7SToomas Soome 
15377*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: mDNSPlatformClose");
15378c65ebfc7SToomas Soome     mDNSPlatformClose(m);
15379c65ebfc7SToomas Soome 
15380c65ebfc7SToomas Soome     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
15381c65ebfc7SToomas Soome     {
15382c65ebfc7SToomas Soome         while (m->rrcache_hash[slot])
15383c65ebfc7SToomas Soome         {
15384c65ebfc7SToomas Soome             CacheGroup *cg = m->rrcache_hash[slot];
15385c65ebfc7SToomas Soome             while (cg->members)
15386c65ebfc7SToomas Soome             {
15387c65ebfc7SToomas Soome                 CacheRecord *cr = cg->members;
15388c65ebfc7SToomas Soome                 cg->members = cg->members->next;
15389c65ebfc7SToomas Soome                 if (cr->CRActiveQuestion) rrcache_active++;
15390c65ebfc7SToomas Soome                 ReleaseCacheRecord(m, cr);
15391c65ebfc7SToomas Soome             }
15392c65ebfc7SToomas Soome             cg->rrcache_tail = &cg->members;
15393c65ebfc7SToomas Soome             ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15394c65ebfc7SToomas Soome         }
15395c65ebfc7SToomas Soome     }
15396c65ebfc7SToomas Soome     debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15397c65ebfc7SToomas Soome     if (rrcache_active != m->rrcache_active)
15398c65ebfc7SToomas Soome         LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
15399c65ebfc7SToomas Soome 
15400c65ebfc7SToomas Soome     for (rr = m->ResourceRecords; rr; rr = rr->next)
15401c65ebfc7SToomas Soome         LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15402c65ebfc7SToomas Soome 
15403*472cd20dSToomas Soome #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15404*472cd20dSToomas Soome     uninit_trust_anchors();
15405*472cd20dSToomas Soome #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15406*472cd20dSToomas Soome 
15407*472cd20dSToomas Soome     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: done");
15408c65ebfc7SToomas Soome }
15409c65ebfc7SToomas Soome 
15410c65ebfc7SToomas Soome #ifdef UNIT_TEST
15411c65ebfc7SToomas Soome #include "../unittests/mdns_ut.c"
15412c65ebfc7SToomas Soome #endif
15413