]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-258.21.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2006 Apple Computer, Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * This code is completely 100% portable C. It does not depend on any external header files
18 * from outside the mDNS project -- all the types it expects to find are defined right here.
19 *
20 * The previous point is very important: This file does not depend on any external
21 * header files. It should compile on *any* platform that has a C compiler, without
22 * making *any* assumptions about availability of so-called "standard" C functions,
23 * routines, or types (which may or may not be present on any given platform).
24
25 * Formatting notes:
26 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
27 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
28 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
29 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
30 * therefore common sense dictates that if they are part of a compound statement then they
31 * should be indented to the same level as everything else in that compound statement.
32 * Indenting curly braces at the same level as the "if" implies that curly braces are
33 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
34 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
35 * understand why variable y is not of type "char*" just proves the point that poor code
36 * layout leads people to unfortunate misunderstandings about how the C language really works.)
37 */
38
39 #include "DNSCommon.h" // Defines general DNS untility routines
40 #include "uDNS.h" // Defines entry points into unicast-specific routines
41
42 // Disable certain benign warnings with Microsoft compilers
43 #if(defined(_MSC_VER))
44 // Disable "conditional expression is constant" warning for debug macros.
45 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
46 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
47 #pragma warning(disable:4127)
48
49 // Disable "assignment within conditional expression".
50 // Other compilers understand the convention that if you place the assignment expression within an extra pair
51 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
52 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
53 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
54 #pragma warning(disable:4706)
55 #endif
56
57 #if APPLE_OSX_mDNSResponder
58
59 #include <WebFilterDNS/WebFilterDNS.h>
60
61 #if ! NO_WCF
62 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
63 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
64
65 // Do we really need to define a macro for "if"?
66 #define CHECK_WCF_FUNCTION(X) if (X)
67 #endif // ! NO_WCF
68
69 #else
70
71 #define NO_WCF 1
72 #endif // APPLE_OSX_mDNSResponder
73
74 // Forward declarations
75 mDNSlocal void BeginSleepProcessing(mDNS *const m);
76 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
77 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password);
78 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
79
80 // ***************************************************************************
81 #if COMPILER_LIKES_PRAGMA_MARK
82 #pragma mark - Program Constants
83 #endif
84
85 #define NO_HINFO 1
86
87
88 // Any records bigger than this are considered 'large' records
89 #define SmallRecordLimit 1024
90
91 #define kMaxUpdateCredits 10
92 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
93
94 mDNSexport const char *const mDNS_DomainTypeNames[] =
95 {
96 "b._dns-sd._udp.", // Browse
97 "db._dns-sd._udp.", // Default Browse
98 "lb._dns-sd._udp.", // Automatic Browse
99 "r._dns-sd._udp.", // Registration
100 "dr._dns-sd._udp." // Default Registration
101 };
102
103 #ifdef UNICAST_DISABLED
104 #define uDNS_IsActiveQuery(q, u) mDNSfalse
105 #endif
106
107 // ***************************************************************************
108 #if COMPILER_LIKES_PRAGMA_MARK
109 #pragma mark -
110 #pragma mark - General Utility Functions
111 #endif
112
113 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
114 {
115 if (m->mDNS_busy != m->mDNS_reentrancy+1)
116 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
117
118 #if ForceAlerts
119 if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
120 #endif
121
122 if (ActiveQuestion(q))
123 {
124 // Depending on whether this is a multicast or unicast question we want to set either:
125 // m->NextScheduledQuery = NextQSendTime(q) or
126 // m->NextuDNSEvent = NextQSendTime(q)
127 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
128 if (*timer - NextQSendTime(q) > 0)
129 *timer = NextQSendTime(q);
130 }
131 }
132
133 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
134 {
135 CacheGroup *cg;
136 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
137 if (cg->namehash == namehash && SameDomainName(cg->name, name))
138 break;
139 return(cg);
140 }
141
142 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
143 {
144 return(CacheGroupForName(m, slot, rr->namehash, rr->name));
145 }
146
147 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
148 {
149 NetworkInterfaceInfo *intf;
150
151 if (addr->type == mDNSAddrType_IPv4)
152 {
153 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
154 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
155 for (intf = m->HostInterfaces; intf; intf = intf->next)
156 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
157 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
158 return(mDNStrue);
159 }
160
161 if (addr->type == mDNSAddrType_IPv6)
162 {
163 if (mDNSv6AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
164 for (intf = m->HostInterfaces; intf; intf = intf->next)
165 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
166 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
167 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
168 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
169 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
170 return(mDNStrue);
171 }
172
173 return(mDNSfalse);
174 }
175
176 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
177 {
178 NetworkInterfaceInfo *intf = m->HostInterfaces;
179 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
180 return(intf);
181 }
182
183 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
184 {
185 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
186 return(intf ? intf->ifname : mDNSNULL);
187 }
188
189 // For a single given DNSQuestion, deliver an add/remove result for the single given AuthRecord
190 // Used by AnswerAllLocalQuestionsWithLocalAuthRecord() and AnswerNewLocalOnlyQuestion()
191 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, DNSQuestion *q, AuthRecord *rr, QC_result AddRecord)
192 {
193 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
194 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
195 {
196 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
197 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
198 return;
199 }
200
201 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
202 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
203 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
204 if (q->QuestionCallback && !q->NoAnswer)
205 {
206 q->CurrentAnswers += AddRecord ? 1 : -1;
207 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
208 }
209 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
210 }
211
212 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
213 // delivers the appropriate add/remove events to listening questions:
214 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
215 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
216 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
217 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
218 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
219 //
220 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
221 // and by mDNS_Deregister_internal()
222
223 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
224 {
225 if (m->CurrentQuestion)
226 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
227 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
228
229 m->CurrentQuestion = m->LocalOnlyQuestions;
230 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
231 {
232 DNSQuestion *q = m->CurrentQuestion;
233 m->CurrentQuestion = q->next;
234 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
235 AnswerLocalQuestionWithLocalAuthRecord(m, q, rr, AddRecord); // MUST NOT dereference q again
236 }
237
238 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
239 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly || rr->resrec.InterfaceID == mDNSInterface_P2P)
240 {
241 m->CurrentQuestion = m->Questions;
242 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
243 {
244 DNSQuestion *q = m->CurrentQuestion;
245 m->CurrentQuestion = q->next;
246 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
247 AnswerLocalQuestionWithLocalAuthRecord(m, q, rr, AddRecord); // MUST NOT dereference q again
248 }
249 }
250
251 m->CurrentQuestion = mDNSNULL;
252 }
253
254 // ***************************************************************************
255 #if COMPILER_LIKES_PRAGMA_MARK
256 #pragma mark -
257 #pragma mark - Resource Record Utility Functions
258 #endif
259
260 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
261
262 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
263 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
264 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
265 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
266
267 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
268 (ResourceRecordIsValidAnswer(RR) && \
269 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
270
271 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
272 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
273
274 #define InitialAnnounceCount ((mDNSu8)8)
275
276 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
277 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
278 // and then if the machine fails to wake, 3 goodbye packets).
279 #define GoodbyeCount ((mDNSu8)3)
280 #define WakeupCount ((mDNSu8)18)
281
282 // Number of wakeups we send if WakeOnResolve is set in the question
283 #define InitialWakeOnResolveCount ((mDNSu8)3)
284
285 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
286 // This means that because the announce interval is doubled after sending the first packet, the first
287 // observed on-the-wire inter-packet interval between announcements is actually one second.
288 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
289 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
290 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
291 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
292
293 #define DefaultAPIntervalForRecordType(X) ((X) & kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
294 (X) & kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
295 (X) & kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
296
297 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
298 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
299 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
300 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
301
302 #define MaxUnansweredQueries 4
303
304 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
305 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
306 // TTL and rdata may differ.
307 // This is used for cache flush management:
308 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
309 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
310
311 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
312
313 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
314
315 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
316 {
317 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
318 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
319 if (r1->resrec.InterfaceID &&
320 r2->resrec.InterfaceID &&
321 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
322 return(mDNSBool)(
323 r1->resrec.rrclass == r2->resrec.rrclass &&
324 r1->resrec.namehash == r2->resrec.namehash &&
325 SameDomainName(r1->resrec.name, r2->resrec.name));
326 }
327
328 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
329 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
330 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
331 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
332 // so a response of any type should match, even if it is not actually the type the client plans to use.
333
334 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
335 // and require the rrtypes to match for the rdata to be considered potentially conflicting
336 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
337 {
338 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
339 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
340 if (pktrr->resrec.InterfaceID &&
341 authrr->resrec.InterfaceID &&
342 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
343 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
344 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
345 return(mDNSBool)(
346 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
347 pktrr->resrec.namehash == authrr->resrec.namehash &&
348 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
349 }
350
351 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
352 // This is the information that the requester believes to be correct.
353 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
354 // This is the information that we believe to be correct.
355 // We've already determined that we plan to give this answer on this interface
356 // (either the record is non-specific, or it is specific to this interface)
357 // so now we just need to check the name, type, class, rdata and TTL.
358 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
359 {
360 // If RR signature is different, or data is different, then don't suppress our answer
361 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
362
363 // If the requester's indicated TTL is less than half the real TTL,
364 // we need to give our answer before the requester's copy expires.
365 // If the requester's indicated TTL is at least half the real TTL,
366 // then we can suppress our answer this time.
367 // If the requester's indicated TTL is greater than the TTL we believe,
368 // then that's okay, and we don't need to do anything about it.
369 // (If two responders on the network are offering the same information,
370 // that's okay, and if they are offering the information with different TTLs,
371 // the one offering the lower TTL should defer to the one offering the higher TTL.)
372 return(mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
373 }
374
375 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
376 {
377 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
378 {
379 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
380 {
381 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
382 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
383 }
384 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
385 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
386 // Some defensive code:
387 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
388 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
389 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
390 if (m->NextScheduledProbe - m->timenow < 0)
391 m->NextScheduledProbe = m->timenow;
392 }
393 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
394 {
395 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
396 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
397 }
398 }
399
400 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
401 {
402 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
403 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
404
405 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
406 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
407 // records that are going to probe, then we delay its first announcement so that it will
408 // go out synchronized with the first announcement for the other records that *are* probing.
409 // This is a minor performance tweak that helps keep groups of related records synchronized together.
410 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
411 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
412 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
413 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
414 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
415
416 if (rr->ProbeCount)
417 {
418 // If we have no probe suppression time set, or it is in the past, set it now
419 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
420 {
421 // To allow us to aggregate probes when a group of services are registered together,
422 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
423 // 1/4 second wait; probe
424 // 1/4 second wait; probe
425 // 1/4 second wait; probe
426 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
427 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
428
429 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
430 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
431 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
432 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
433 m->SuppressProbes = m->timenow;
434
435 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
436 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
437 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
438 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
439 m->SuppressProbes = m->timenow;
440
441 // except... don't expect to be able to send before the m->SuppressSending timer fires
442 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
443 m->SuppressProbes = NonZeroTime(m->SuppressSending);
444
445 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
446 {
447 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
448 m->SuppressProbes - m->timenow,
449 m->NextScheduledProbe - m->timenow,
450 m->NextScheduledQuery - m->timenow,
451 m->SuppressSending,
452 m->SuppressSending - m->timenow);
453 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
454 }
455 }
456 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
457 }
458 else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
459 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
460 else
461 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
462
463 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
464 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
465 // After three probes one second apart with no answer, we conclude the client is now sleeping
466 // and we can begin broadcasting our announcements to take over ownership of that IP address.
467 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
468 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
469 if (rr->AddressProxy.type) rr->LastAPTime = m->timenow;
470
471 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
472 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
473 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
474 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
475 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
476 if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
477 if (rr->WakeUp.HMAC.l[0] && rr->resrec.rrtype == kDNSType_AAAA)
478 rr->LastAPTime = m->timenow - rr->ThisAPInterval + mDNSPlatformOneSecond * 10;
479
480 // Set LastMCTime to now, to inhibit multicast responses
481 // (no need to send additional multicast responses when we're announcing anyway)
482 rr->LastMCTime = m->timenow;
483 rr->LastMCInterface = mDNSInterfaceMark;
484
485 SetNextAnnounceProbeTime(m, rr);
486 }
487
488 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
489 {
490 const domainname *target;
491 if (rr->AutoTarget)
492 {
493 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
494 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
495 // with the port number in our advertised SRV record automatically tracking the external mapped port.
496 DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
497 if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
498 }
499
500 target = GetServiceTarget(m, rr);
501 if (!target || target->c[0] == 0)
502 {
503 // defer registration until we've got a target
504 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
505 rr->state = regState_NoTarget;
506 return mDNSNULL;
507 }
508 else
509 {
510 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
511 return target;
512 }
513 }
514
515 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
516 // Eventually we should unify this with GetServiceTarget() in uDNS.c
517 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
518 {
519 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
520 const domainname *newname = &m->MulticastHostname;
521
522 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
523
524 if (!(rr->ForceMCast || rr->resrec.InterfaceID == mDNSInterface_LocalOnly || rr->resrec.InterfaceID == mDNSInterface_P2P || IsLocalDomain(&rr->namestorage)))
525 {
526 const domainname *const n = SetUnicastTargetToHostName(m, rr);
527 if (n) newname = n;
528 else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
529 }
530
531 if (target && SameDomainName(target, newname))
532 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
533
534 if (target && !SameDomainName(target, newname))
535 {
536 AssignDomainName(target, newname);
537 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
538
539 // If we're in the middle of probing this record, we need to start again,
540 // because changing its rdata may change the outcome of the tie-breaker.
541 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
542 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
543
544 // If we've announced this record, we really should send a goodbye packet for the old rdata before
545 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
546 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
547 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
548 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
549 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
550
551 rr->AnnounceCount = InitialAnnounceCount;
552 rr->RequireGoodbye = mDNSfalse;
553 InitializeLastAPTime(m, rr);
554 }
555 }
556
557 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
558 {
559 if (rr->RecordCallback)
560 {
561 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
562 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
563 rr->Acknowledged = mDNStrue;
564 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
565 rr->RecordCallback(m, rr, mStatus_NoError);
566 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
567 }
568 }
569
570 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
571 {
572 // Make sure that we don't activate the SRV record and associated service records, if it is in
573 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
574 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
575 // the target becomes available, the records will be reregistered.
576 if (rr->resrec.rrtype != kDNSType_SRV)
577 {
578 AuthRecord *srvRR = mDNSNULL;
579 if (rr->resrec.rrtype == kDNSType_PTR)
580 srvRR = rr->Additional1;
581 else if (rr->resrec.rrtype == kDNSType_TXT)
582 srvRR = rr->DependentOn;
583 if (srvRR)
584 {
585 if (srvRR->resrec.rrtype != kDNSType_SRV)
586 {
587 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
588 }
589 else
590 {
591 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
592 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
593 rr->state = srvRR->state;
594 }
595 }
596 }
597
598 if (rr->state == regState_NoTarget)
599 {
600 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
601 return;
602 }
603 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
604 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
605 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
606 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
607 // 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.
608 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
609 {
610 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
611 rr->state = regState_DeregPending;
612 }
613 else
614 {
615 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
616 rr->state = regState_Pending;
617 }
618 rr->ProbeCount = 0;
619 rr->AnnounceCount = 0;
620 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
621 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
622 rr->expire = 0; // Forget about all the leases, start fresh
623 rr->uselease = mDNStrue;
624 rr->updateid = zeroID;
625 rr->SRVChanged = mDNSfalse;
626 rr->updateError = mStatus_NoError;
627 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
628 // The records might already be registered with the server and hence could have NAT state.
629 if (rr->NATinfo.clientContext)
630 {
631 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
632 rr->NATinfo.clientContext = mDNSNULL;
633 }
634 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
635 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
636 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
637 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
638 }
639
640 // Two records qualify to be local duplicates if:
641 // (a) the RecordTypes are the same, or
642 // (b) one is Unique and the other Verified
643 // (c) either is in the process of deregistering
644 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
645 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
646 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
647
648 #define RecordIsLocalDuplicate(A,B) \
649 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
650
651 // Exported so uDNS.c can call this
652 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
653 {
654 domainname *target = GetRRDomainNameTarget(&rr->resrec);
655 AuthRecord *r;
656 AuthRecord **p = &m->ResourceRecords;
657 AuthRecord **d = &m->DuplicateRecords;
658
659 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
660 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
661
662 if (!rr->resrec.RecordType)
663 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
664
665 if (m->ShutdownTime)
666 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
667
668 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
669 {
670 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
671 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P) rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
672 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
673 {
674 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
675 if (intf && !intf->Advertise) rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
676 }
677 if (rr->resrec.InterfaceID != previousID)
678 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
679 }
680
681 while (*p && *p != rr) p=&(*p)->next;
682 while (*d && *d != rr) d=&(*d)->next;
683 if (*d || *p)
684 {
685 LogMsg("Error! Tried to register AuthRecord %p %##s (%s) that's already in the list",
686 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
687 return(mStatus_AlreadyRegistered);
688 }
689
690 if (rr->DependentOn)
691 {
692 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
693 rr->resrec.RecordType = kDNSRecordTypeVerified;
694 else
695 {
696 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
697 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
698 return(mStatus_Invalid);
699 }
700 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified)))
701 {
702 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
703 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
704 return(mStatus_Invalid);
705 }
706 }
707
708 // If this resource record is referencing a specific interface, make sure it exists
709 if (rr->resrec.InterfaceID && rr->resrec.InterfaceID != mDNSInterface_LocalOnly && rr->resrec.InterfaceID != mDNSInterface_P2P)
710 {
711 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
712 if (!intf)
713 {
714 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr->resrec.InterfaceID);
715 return(mStatus_BadReferenceErr);
716 }
717 }
718
719 rr->next = mDNSNULL;
720
721 // Field Group 1: The actual information pertaining to this resource record
722 // Set up by client prior to call
723
724 // Field Group 2: Persistent metadata for Authoritative Records
725 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
726 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
727 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
728 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
729 // rr->Callback = already set in mDNS_SetupResourceRecord
730 // rr->Context = already set in mDNS_SetupResourceRecord
731 // rr->RecordType = already set in mDNS_SetupResourceRecord
732 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
733 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
734 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
735 if (rr->AutoTarget && target) target->c[0] = 0;
736
737 // Field Group 3: Transient state for Authoritative Records
738 rr->Acknowledged = mDNSfalse;
739 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
740 rr->AnnounceCount = InitialAnnounceCount;
741 rr->RequireGoodbye = mDNSfalse;
742 rr->AnsweredLocalQ = mDNSfalse;
743 rr->IncludeInProbe = mDNSfalse;
744 rr->ImmedUnicast = mDNSfalse;
745 rr->SendNSECNow = mDNSNULL;
746 rr->ImmedAnswer = mDNSNULL;
747 rr->ImmedAdditional = mDNSNULL;
748 rr->SendRNow = mDNSNULL;
749 rr->v4Requester = zerov4Addr;
750 rr->v6Requester = zerov6Addr;
751 rr->NextResponse = mDNSNULL;
752 rr->NR_AnswerTo = mDNSNULL;
753 rr->NR_AdditionalTo = mDNSNULL;
754 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
755 // rr->LastAPTime = Set for us in InitializeLastAPTime()
756 // rr->LastMCTime = Set for us in InitializeLastAPTime()
757 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
758 rr->NewRData = mDNSNULL;
759 rr->newrdlength = 0;
760 rr->UpdateCallback = mDNSNULL;
761 rr->UpdateCredits = kMaxUpdateCredits;
762 rr->NextUpdateCredit = 0;
763 rr->UpdateBlocked = 0;
764
765 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
766 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
767
768 // Field Group 4: Transient uDNS state for Authoritative Records
769 rr->state = regState_Zero;
770 rr->uselease = 0;
771 rr->expire = 0;
772 rr->Private = 0;
773 rr->updateid = zeroID;
774 rr->zone = rr->resrec.name;
775 rr->nta = mDNSNULL;
776 rr->tcp = mDNSNULL;
777 rr->OrigRData = 0;
778 rr->OrigRDLen = 0;
779 rr->InFlightRData = 0;
780 rr->InFlightRDLen = 0;
781 rr->QueuedRData = 0;
782 rr->QueuedRDLen = 0;
783 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
784 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
785 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
786 // times with different values if the external NAT port changes during the lifetime of the service registration.
787 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
788
789 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
790 // rr->resrec.name->c = MUST be set by client
791 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
792 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
793 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
794 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
795
796 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
797 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
798 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
799 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
800
801 if (rr->AutoTarget)
802 {
803 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
804 #ifndef UNICAST_DISABLED
805 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
806 // 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.
807 if (rr->state == regState_NoTarget)
808 {
809 // Initialize the target so that we don't crash while logging etc.
810 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
811 if (tar) tar->c[0] = 0;
812 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
813 }
814 #endif
815 }
816 else
817 {
818 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
819 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
820 }
821
822 if (!ValidateDomainName(rr->resrec.name))
823 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
824
825 // Don't do this until *after* we've set rr->resrec.rdlength
826 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
827 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
828
829 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
830 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
831
832 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly || rr->resrec.InterfaceID == mDNSInterface_P2P)
833 {
834 // If this is supposed to be unique, make sure we don't have any name conflicts
835 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
836 {
837 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
838 for (r = m->ResourceRecords; r; r=r->next)
839 {
840 const AuthRecord *s2 = r->RRSet ? r->RRSet : r;
841 if (s1 != s2 && SameResourceRecordSignature(r, rr) && !IdenticalSameNameRecord(&r->resrec, &rr->resrec))
842 break;
843 }
844 if (r) // If we found a conflict, set RecordType = kDNSRecordTypeDeregistering so we'll deliver the callback
845 {
846 debugf("Name conflict %p %##s (%s)", rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
847 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
848 rr->resrec.rroriginalttl = 0;
849 rr->ImmedAnswer = mDNSInterfaceMark;
850 m->LocalRemoveEvents = mDNStrue;
851 m->NextScheduledResponse = m->timenow;
852 }
853 }
854 }
855
856 // For uDNS records, we don't support duplicate checks at this time
857 #ifndef UNICAST_DISABLED
858 if (AuthRecord_uDNS(rr))
859 {
860 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
861 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
862 // 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.
863 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
864 while (*p) p=&(*p)->next;
865 *p = rr;
866 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
867 rr->ProbeCount = 0;
868 rr->AnnounceCount = 0;
869 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
870 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
871 }
872 #endif
873
874 // Now that we've finished building our new record, make sure it's not identical to one we already have
875 for (r = m->ResourceRecords; r; r=r->next)
876 if (RecordIsLocalDuplicate(r, rr))
877 {
878 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
879 else break;
880 }
881
882 if (r)
883 {
884 debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
885 *d = rr;
886 // If the previous copy of this record is already verified unique,
887 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
888 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
889 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
890 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
891 rr->ProbeCount = 0;
892 }
893 else
894 {
895 debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
896 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
897 *p = rr;
898 }
899
900 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
901 {
902 // For records that are not going to probe, acknowledge them right away
903 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
904 AcknowledgeRecord(m, rr);
905
906 // Adding a record may affect whether or not we should sleep
907 mDNS_UpdateAllowSleep(m);
908 }
909
910 return(mStatus_NoError);
911 }
912
913 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
914 {
915 m->ProbeFailTime = m->timenow;
916 m->NumFailedProbes++;
917 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
918 // If a bunch of hosts have all been configured with the same name, then they'll all
919 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
920 // up to name-10. After that they'll start adding random increments in the range 1-100,
921 // so they're more likely to branch out in the available namespace and settle on a set of
922 // unique names quickly. If after five more tries the host is still conflicting, then we
923 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
924 if (m->NumFailedProbes >= 15)
925 {
926 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
927 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
928 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
929 }
930 }
931
932 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
933 {
934 RData *OldRData = rr->resrec.rdata;
935 mDNSu16 OldRDLen = rr->resrec.rdlength;
936 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
937 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
938 if (rr->UpdateCallback)
939 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
940 }
941
942 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
943 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
944 // Exported so uDNS.c can call this
945 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
946 {
947 AuthRecord *r2;
948 mDNSu8 RecordType = rr->resrec.RecordType;
949 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
950
951 while (*p && *p != rr) p=&(*p)->next;
952
953 if (*p)
954 {
955 // We found our record on the main list. See if there are any duplicates that need special handling.
956 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
957 {
958 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
959 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
960 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
961 }
962 else
963 {
964 // Before we delete the record (and potentially send a goodbye packet)
965 // first see if we have a record on the duplicate list ready to take over from it.
966 AuthRecord **d = &m->DuplicateRecords;
967 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
968 if (*d)
969 {
970 AuthRecord *dup = *d;
971 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
972 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
973 *d = dup->next; // Cut replacement record from DuplicateRecords list
974 dup->next = rr->next; // And then...
975 rr->next = dup; // ... splice it in right after the record we're about to delete
976 dup->resrec.RecordType = rr->resrec.RecordType;
977 dup->ProbeCount = rr->ProbeCount;
978 dup->AnnounceCount = rr->AnnounceCount;
979 dup->RequireGoodbye = rr->RequireGoodbye;
980 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
981 dup->ImmedAnswer = rr->ImmedAnswer;
982 dup->ImmedUnicast = rr->ImmedUnicast;
983 dup->ImmedAdditional = rr->ImmedAdditional;
984 dup->v4Requester = rr->v4Requester;
985 dup->v6Requester = rr->v6Requester;
986 dup->ThisAPInterval = rr->ThisAPInterval;
987 dup->LastAPTime = rr->LastAPTime;
988 dup->LastMCTime = rr->LastMCTime;
989 dup->LastMCInterface = rr->LastMCInterface;
990 dup->Private = rr->Private;
991 dup->state = rr->state;
992 rr->RequireGoodbye = mDNSfalse;
993 rr->AnsweredLocalQ = mDNSfalse;
994 }
995 }
996 }
997 else
998 {
999 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1000 p = &m->DuplicateRecords;
1001 while (*p && *p != rr) p=&(*p)->next;
1002 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1003 if (*p) rr->RequireGoodbye = mDNSfalse;
1004 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1005 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1006 }
1007
1008 if (!*p)
1009 {
1010 // No need to log an error message if we already know this is a potentially repeated deregistration
1011 if (drt != mDNS_Dereg_repeat)
1012 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1013 return(mStatus_BadReferenceErr);
1014 }
1015
1016 // If this is a shared record and we've announced it at least once,
1017 // we need to retract that announcement before we delete the record
1018
1019 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1020 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1021 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1022 // mechanism to cope with the client callback modifying the question list while that's happening.
1023 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1024 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1025 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1026 // records, thereby invoking yet more callbacks, without limit.
1027 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1028 // actual goodbye packets.
1029
1030 #ifndef UNICAST_DISABLED
1031 if (AuthRecord_uDNS(rr))
1032 {
1033 if (rr->RequireGoodbye)
1034 {
1035 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1036 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1037 m->LocalRemoveEvents = mDNStrue;
1038 uDNS_DeregisterRecord(m, rr);
1039 // At this point unconditionally we bail out
1040 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1041 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1042 // process and will complete asynchronously. Either way we don't need to do anything more here.
1043 return(mStatus_NoError);
1044 }
1045 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1046 // from the server. In that case, if the records have been part of a group update, clear the
1047 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1048 rr->updateid = zeroID;
1049
1050 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1051 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1052 // This happens today when we turn on/off interface where we get multiple network transitions
1053 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1054 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1055 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1056 // NAT state here takes care of the case where we did not send goodbyes at all.
1057 if (rr->NATinfo.clientContext)
1058 {
1059 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1060 rr->NATinfo.clientContext = mDNSNULL;
1061 }
1062 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1063 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1064 }
1065 #endif // UNICAST_DISABLED
1066
1067 if (RecordType == kDNSRecordTypeUnregistered)
1068 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1069 else if (RecordType == kDNSRecordTypeDeregistering)
1070 {
1071 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1072 return(mStatus_BadReferenceErr);
1073 }
1074
1075 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1076 // We may want to consider changing this code so that we generate local-only question "rmv"
1077 // events (and maybe goodbye packets too) for unique records as well as for shared records
1078 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1079 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1080 // clause will execute here and the record will be cut from the list.
1081 if (rr->WakeUp.HMAC.l[0] ||
1082 (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1083 {
1084 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1085 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1086 rr->resrec.rroriginalttl = 0;
1087 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1088 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
1089 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1090 m->LocalRemoveEvents = mDNStrue;
1091 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1092 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1093 }
1094 else
1095 {
1096 *p = rr->next; // Cut this record from the list
1097 // If someone is about to look at this, bump the pointer forward
1098 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
1099 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1100 rr->next = mDNSNULL;
1101
1102 // Should we generate local remove events here?
1103 // i.e. something like:
1104 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1105
1106 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1107 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1108
1109 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1110 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1111 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1112
1113 // If we have an update queued up which never executed, give the client a chance to free that memory
1114 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1115
1116
1117 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1118 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1119 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1120 // so any attempt to touch rr after this is likely to lead to a crash.
1121 if (drt != mDNS_Dereg_conflict)
1122 {
1123 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1124 LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1125 if (rr->RecordCallback)
1126 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
1127 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1128 }
1129 else
1130 {
1131 RecordProbeFailure(m, rr);
1132 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1133 if (rr->RecordCallback)
1134 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
1135 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1136 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1137 // Note that with all the client callbacks going on, by the time we get here all the
1138 // records we marked may have been explicitly deregistered by the client anyway.
1139 r2 = m->DuplicateRecords;
1140 while (r2)
1141 {
1142 if (r2->ProbeCount != 0xFF) r2 = r2->next;
1143 else { mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict); r2 = m->DuplicateRecords; }
1144 }
1145 }
1146 }
1147 mDNS_UpdateAllowSleep(m);
1148 return(mStatus_NoError);
1149 }
1150
1151 // ***************************************************************************
1152 #if COMPILER_LIKES_PRAGMA_MARK
1153 #pragma mark -
1154 #pragma mark - Packet Sending Functions
1155 #endif
1156
1157 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1158 {
1159 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1160 {
1161 **nrpp = rr;
1162 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1163 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1164 // The referenced record will definitely be acceptable (by recursive application of this rule)
1165 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1166 rr->NR_AdditionalTo = add;
1167 *nrpp = &rr->NextResponse;
1168 }
1169 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1170 }
1171
1172 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1173 {
1174 AuthRecord *rr, *rr2;
1175 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
1176 {
1177 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1178 // later in the "for" loop, and we will follow further "additional" links then.)
1179 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1180 AddRecordToResponseList(nrpp, rr->Additional1, rr);
1181
1182 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1183 AddRecordToResponseList(nrpp, rr->Additional2, rr);
1184
1185 // For SRV records, automatically add the Address record(s) for the target host
1186 if (rr->resrec.rrtype == kDNSType_SRV)
1187 {
1188 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1189 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1190 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1191 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
1192 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1193 AddRecordToResponseList(nrpp, rr2, rr);
1194 }
1195 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
1196 {
1197 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
1198 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
1199 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
1200 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
1201 SameDomainName(rr->resrec.name, rr2->resrec.name))
1202 AddRecordToResponseList(nrpp, rr2, rr);
1203 }
1204 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
1205 {
1206 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1207 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1208 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1209 }
1210 }
1211 }
1212
1213 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1214 {
1215 AuthRecord *rr;
1216 AuthRecord *ResponseRecords = mDNSNULL;
1217 AuthRecord **nrp = &ResponseRecords;
1218
1219 // Make a list of all our records that need to be unicast to this destination
1220 for (rr = m->ResourceRecords; rr; rr=rr->next)
1221 {
1222 // If we find we can no longer unicast this answer, clear ImmedUnicast
1223 if (rr->ImmedAnswer == mDNSInterfaceMark ||
1224 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1225 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
1226 rr->ImmedUnicast = mDNSfalse;
1227
1228 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1229 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1230 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1231 {
1232 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
1233 rr->ImmedUnicast = mDNSfalse;
1234 rr->v4Requester = zerov4Addr;
1235 rr->v6Requester = zerov6Addr;
1236 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
1237 { rr->NR_AnswerTo = (mDNSu8*)~0; *nrp = rr; nrp = &rr->NextResponse; }
1238 }
1239 }
1240
1241 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1242
1243 while (ResponseRecords)
1244 {
1245 mDNSu8 *responseptr = m->omsg.data;
1246 mDNSu8 *newptr;
1247 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1248
1249 // Put answers in the packet
1250 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1251 {
1252 rr = ResponseRecords;
1253 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1254 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1255 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
1256 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1257 if (!newptr && m->omsg.h.numAnswers) break; // If packet full, send it now
1258 if (newptr) responseptr = newptr;
1259 ResponseRecords = rr->NextResponse;
1260 rr->NextResponse = mDNSNULL;
1261 rr->NR_AnswerTo = mDNSNULL;
1262 rr->NR_AdditionalTo = mDNSNULL;
1263 rr->RequireGoodbye = mDNStrue;
1264 }
1265
1266 // Add additionals, if there's space
1267 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
1268 {
1269 rr = ResponseRecords;
1270 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1271 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1272 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
1273 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1274
1275 if (newptr) responseptr = newptr;
1276 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
1277 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
1278 ResponseRecords = rr->NextResponse;
1279 rr->NextResponse = mDNSNULL;
1280 rr->NR_AnswerTo = mDNSNULL;
1281 rr->NR_AdditionalTo = mDNSNULL;
1282 }
1283
1284 if (m->omsg.h.numAnswers)
1285 mDNSSendDNSMessage(m, &m->omsg, responseptr, mDNSInterface_Any, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL);
1286 }
1287 }
1288
1289 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1290 // and the client's mStatus_MemFree callback will have been invoked
1291 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
1292 {
1293 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
1294 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1295 // it should go ahead and immediately dispose of this registration
1296 rr->resrec.RecordType = kDNSRecordTypeShared;
1297 rr->RequireGoodbye = mDNSfalse;
1298 rr->WakeUp.HMAC = zeroEthAddr;
1299 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1300 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
1301 }
1302
1303 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1304 // any deregistering records that remain in the m->ResourceRecords list.
1305 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1306 // which may change the record list and/or question list.
1307 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1308 mDNSlocal void DiscardDeregistrations(mDNS *const m)
1309 {
1310 if (m->CurrentRecord)
1311 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
1312 m->CurrentRecord = m->ResourceRecords;
1313
1314 while (m->CurrentRecord)
1315 {
1316 AuthRecord *rr = m->CurrentRecord;
1317 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1318 CompleteDeregistration(m, rr); // Don't touch rr after this
1319 else
1320 m->CurrentRecord = rr->next;
1321 }
1322 }
1323
1324 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
1325 {
1326 int i, val = 0;
1327 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
1328 for (i=1; i<=src[0]; i++)
1329 {
1330 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
1331 val = val * 10 + src[i] - '0';
1332 }
1333 if (val > 255) return(mStatus_Invalid);
1334 *dst = (mDNSu8)val;
1335 return(mStatus_NoError);
1336 }
1337
1338 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
1339 {
1340 int skip = CountLabels(name) - 6;
1341 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
1342 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
1343 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
1344 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
1345 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
1346 a->type = mDNSAddrType_IPv4;
1347 return(mStatus_NoError);
1348 }
1349
1350 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
1351 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
1352 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1353
1354 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
1355 {
1356 int i, h, l;
1357 const domainname *n;
1358
1359 int skip = CountLabels(name) - 34;
1360 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
1361
1362 n = SkipLeadingLabels(name, skip);
1363 for (i=0; i<16; i++)
1364 {
1365 if (n->c[0] != 1) return mStatus_Invalid;
1366 l = HexVal(n->c[1]);
1367 n = (const domainname *)(n->c + 2);
1368
1369 if (n->c[0] != 1) return mStatus_Invalid;
1370 h = HexVal(n->c[1]);
1371 n = (const domainname *)(n->c + 2);
1372
1373 if (l<0 || h<0) return mStatus_Invalid;
1374 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
1375 }
1376
1377 a->type = mDNSAddrType_IPv6;
1378 return(mStatus_NoError);
1379 }
1380
1381 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
1382 {
1383 int skip = CountLabels(name) - 2;
1384 if (skip >= 0)
1385 {
1386 const domainname *suffix = SkipLeadingLabels(name, skip);
1387 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
1388 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
1389 }
1390 return(mDNSAddrType_None);
1391 }
1392
1393 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
1394 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
1395 {
1396 int i;
1397 mDNSu8 *ptr = m->omsg.data;
1398 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1399 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1400
1401 // 0x00 Destination address
1402 for (i=0; i<6; i++) *ptr++ = dst->b[i];
1403
1404 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1405 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
1406
1407 // 0x0C ARP Ethertype (0x0806)
1408 *ptr++ = 0x08; *ptr++ = 0x06;
1409
1410 // 0x0E ARP header
1411 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
1412 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
1413 *ptr++ = 6; // Hardware address length
1414 *ptr++ = 4; // Protocol address length
1415 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
1416
1417 // 0x16 Sender hardware address (our MAC address)
1418 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
1419
1420 // 0x1C Sender protocol address
1421 for (i=0; i<4; i++) *ptr++ = spa->b[i];
1422
1423 // 0x20 Target hardware address
1424 for (i=0; i<6; i++) *ptr++ = tha->b[i];
1425
1426 // 0x26 Target protocol address
1427 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
1428
1429 // 0x2A Total ARP Packet length 42 bytes
1430 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1431 }
1432
1433 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
1434 {
1435 const mDNSu16 *ptr = data;
1436 while (length > 0) { length -= 2; sum += *ptr++; }
1437 sum = (sum & 0xFFFF) + (sum >> 16);
1438 sum = (sum & 0xFFFF) + (sum >> 16);
1439 return(sum != 0xFFFF ? sum : 0);
1440 }
1441
1442 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
1443 {
1444 IPv6PseudoHeader ph;
1445 ph.src = *src;
1446 ph.dst = *dst;
1447 ph.len.b[0] = length >> 24;
1448 ph.len.b[1] = length >> 16;
1449 ph.len.b[2] = length >> 8;
1450 ph.len.b[3] = length;
1451 ph.pro.b[0] = 0;
1452 ph.pro.b[1] = 0;
1453 ph.pro.b[2] = 0;
1454 ph.pro.b[3] = protocol;
1455 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
1456 }
1457
1458 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
1459 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
1460 {
1461 int i;
1462 mDNSOpaque16 checksum;
1463 mDNSu8 *ptr = m->omsg.data;
1464 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1465 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1466 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1467 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] } };
1468 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
1469 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1470 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
1471
1472 // 0x00 Destination address
1473 for (i=0; i<6; i++) *ptr++ = dst->b[i];
1474 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1475 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1476 // link with a pointless link-layer multicast.
1477 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1478 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1479 // *ptr++ = 0x33;
1480 // *ptr++ = 0x33;
1481 // *ptr++ = 0xFF;
1482 // *ptr++ = tpa->b[0xD];
1483 // *ptr++ = tpa->b[0xE];
1484 // *ptr++ = tpa->b[0xF];
1485
1486 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1487 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1488
1489 // 0x0C IPv6 Ethertype (0x86DD)
1490 *ptr++ = 0x86; *ptr++ = 0xDD;
1491
1492 // 0x0E IPv6 header
1493 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
1494 *ptr++ = 0x00; *ptr++ = 0x20; // Length
1495 *ptr++ = 0x3A; // Protocol == ICMPv6
1496 *ptr++ = 0xFF; // Hop Limit
1497
1498 // 0x16 Sender IPv6 address
1499 for (i=0; i<16; i++) *ptr++ = spa->b[i];
1500
1501 // 0x26 Destination IPv6 address
1502 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
1503
1504 // 0x36 NDP header
1505 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
1506 *ptr++ = 0x00; // Code
1507 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
1508 *ptr++ = flags;
1509 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
1510
1511 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
1512 {
1513 // 0x3E NDP target.
1514 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
1515 // 0x4E Source Link-layer Address
1516 // <http://www.ietf.org/rfc/rfc2461.txt>
1517 // MUST NOT be included when the source IP address is the unspecified address.
1518 // Otherwise, on link layers that have addresses this option MUST be included
1519 // in multicast solicitations and SHOULD be included in unicast solicitations.
1520 if (!mDNSIPv6AddressIsZero(*spa))
1521 {
1522 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
1523 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
1524 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1525 }
1526 }
1527 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
1528 {
1529 // 0x3E NDP target.
1530 for (i=0; i<16; i++) *ptr++ = spa->b[i];
1531 // 0x4E Target Link-layer Address
1532 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
1533 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
1534 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
1535 }
1536
1537 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
1538 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
1539 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
1540 m->omsg.data[0x38] = checksum.b[0];
1541 m->omsg.data[0x39] = checksum.b[1];
1542
1543 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
1544 }
1545
1546 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
1547 {
1548 owner->u.owner.vers = 0;
1549 owner->u.owner.seq = m->SleepSeqNum;
1550 owner->u.owner.HMAC = m->PrimaryMAC;
1551 owner->u.owner.IMAC = intf->MAC;
1552 owner->u.owner.password = zeroEthAddr;
1553
1554 // Don't try to compute the optlen until *after* we've set up the data fields
1555 // 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
1556 owner->opt = kDNSOpt_Owner;
1557 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
1558 }
1559
1560 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
1561 {
1562 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
1563 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
1564 }
1565
1566 // Note about acceleration of announcements to facilitate automatic coalescing of
1567 // multiple independent threads of announcements into a single synchronized thread:
1568 // The announcements in the packet may be at different stages of maturity;
1569 // One-second interval, two-second interval, four-second interval, and so on.
1570 // After we've put in all the announcements that are due, we then consider
1571 // whether there are other nearly-due announcements that are worth accelerating.
1572 // To be eligible for acceleration, a record MUST NOT be older (further along
1573 // its timeline) than the most mature record we've already put in the packet.
1574 // In other words, younger records can have their timelines accelerated to catch up
1575 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
1576 // Older records cannot have their timelines accelerated; this would just widen
1577 // the gap between them and their younger bretheren and get them even more out of sync.
1578
1579 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
1580 // the record list and/or question list.
1581 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1582 mDNSlocal void SendResponses(mDNS *const m)
1583 {
1584 int pktcount = 0;
1585 AuthRecord *rr, *r2;
1586 mDNSs32 maxExistingAnnounceInterval = 0;
1587 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
1588
1589 m->NextScheduledResponse = m->timenow + 0x78000000;
1590
1591 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
1592
1593 for (rr = m->ResourceRecords; rr; rr=rr->next)
1594 if (rr->ImmedUnicast)
1595 {
1596 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
1597 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
1598 v4.ip.v4 = rr->v4Requester;
1599 v6.ip.v6 = rr->v6Requester;
1600 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
1601 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
1602 if (rr->ImmedUnicast)
1603 {
1604 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
1605 rr->ImmedUnicast = mDNSfalse;
1606 }
1607 }
1608
1609 // ***
1610 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
1611 // ***
1612
1613 // Run through our list of records, and decide which ones we're going to announce on all interfaces
1614 for (rr = m->ResourceRecords; rr; rr=rr->next)
1615 {
1616 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
1617 if (TimeToAnnounceThisRecord(rr, m->timenow))
1618 {
1619 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1620 {
1621 if (!rr->WakeUp.HMAC.l[0])
1622 {
1623 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
1624 }
1625 else
1626 {
1627 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
1628 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
1629 for (r2 = rr; r2; r2=r2->next)
1630 if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC))
1631 {
1632 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
1633 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
1634 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
1635 {
1636 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
1637 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
1638 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
1639 }
1640 r2->LastAPTime = m->timenow;
1641 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
1642 }
1643 }
1644 }
1645 else if (ResourceRecordIsValidAnswer(rr))
1646 {
1647 if (rr->AddressProxy.type)
1648 {
1649 rr->AnnounceCount--;
1650 rr->ThisAPInterval *= 2;
1651 rr->LastAPTime = m->timenow;
1652 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
1653 {
1654 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
1655 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
1656 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
1657 }
1658 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
1659 {
1660 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
1661 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
1662 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
1663 }
1664 }
1665 else
1666 {
1667 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
1668 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
1669 maxExistingAnnounceInterval = rr->ThisAPInterval;
1670 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
1671 }
1672 }
1673 }
1674 }
1675
1676 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
1677 // Eligible records that are more than half-way to their announcement time are accelerated
1678 for (rr = m->ResourceRecords; rr; rr=rr->next)
1679 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
1680 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
1681 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
1682 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
1683 ResourceRecordIsValidAnswer(rr)))
1684 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
1685
1686 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
1687 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
1688 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
1689 // then all that means is that it won't get sent -- which would not be the end of the world.
1690 for (rr = m->ResourceRecords; rr; rr=rr->next)
1691 {
1692 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
1693 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
1694 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
1695 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
1696 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
1697 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
1698 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
1699 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
1700 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
1701 // We also make sure we send the DeviceInfo TXT record too, if necessary
1702 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
1703 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
1704 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
1705 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1706 {
1707 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
1708 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
1709 }
1710 }
1711
1712 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
1713 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
1714 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
1715 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
1716 // -- 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
1717 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
1718 for (rr = m->ResourceRecords; rr; rr=rr->next)
1719 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1720 {
1721 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
1722 {
1723 for (r2 = m->ResourceRecords; r2; r2=r2->next)
1724 if (ResourceRecordIsValidAnswer(r2))
1725 if (r2->ImmedAnswer != mDNSInterfaceMark &&
1726 r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
1727 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
1728 }
1729 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
1730 {
1731 for (r2 = m->ResourceRecords; r2; r2=r2->next)
1732 if (ResourceRecordIsValidAnswer(r2))
1733 if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
1734 r2->ImmedAdditional = rr->ImmedAdditional;
1735 }
1736 }
1737
1738 // Now set SendRNow state appropriately
1739 for (rr = m->ResourceRecords; rr; rr=rr->next)
1740 {
1741 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
1742 {
1743 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
1744 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
1745 rr->LastMCTime = m->timenow;
1746 rr->LastMCInterface = rr->ImmedAnswer;
1747 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
1748 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
1749 {
1750 rr->AnnounceCount--;
1751 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1752 rr->ThisAPInterval *= 2;
1753 rr->LastAPTime = m->timenow;
1754 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
1755 }
1756 }
1757 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
1758 {
1759 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
1760 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
1761 rr->LastMCTime = m->timenow;
1762 rr->LastMCInterface = rr->ImmedAnswer;
1763 }
1764 SetNextAnnounceProbeTime(m, rr);
1765 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
1766 }
1767
1768 // ***
1769 // *** 2. Loop through interface list, sending records as appropriate
1770 // ***
1771
1772 while (intf)
1773 {
1774 const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
1775 int numDereg = 0;
1776 int numAnnounce = 0;
1777 int numAnswer = 0;
1778 mDNSu8 *responseptr = m->omsg.data;
1779 mDNSu8 *newptr;
1780 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1781
1782 // First Pass. Look for:
1783 // 1. Deregistering records that need to send their goodbye packet
1784 // 2. Updated records that need to retract their old data
1785 // 3. Answers and announcements we need to send
1786 for (rr = m->ResourceRecords; rr; rr=rr->next)
1787 {
1788 if (rr->SendRNow == intf->InterfaceID)
1789 {
1790 RData *OldRData = rr->resrec.rdata;
1791 mDNSu16 oldrdlength = rr->resrec.rdlength;
1792 mDNSu8 active = (mDNSu8)
1793 (rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
1794 (m->SleepState != SleepState_Sleeping || intf->SPSAddr[0].type || intf->SPSAddr[1].type || intf->SPSAddr[2].type));
1795 newptr = mDNSNULL;
1796 if (rr->NewRData && active)
1797 {
1798 // See if we should send a courtesy "goodbye" for the old data before we replace it.
1799 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
1800 {
1801 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
1802 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
1803 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
1804 }
1805 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
1806 }
1807
1808 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1809 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1810 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
1811 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1812 if (newptr)
1813 {
1814 responseptr = newptr;
1815 rr->RequireGoodbye = active;
1816 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
1817 else if (rr->LastAPTime == m->timenow) numAnnounce++; else numAnswer++;
1818 }
1819
1820 if (rr->NewRData && active)
1821 SetNewRData(&rr->resrec, OldRData, oldrdlength);
1822
1823 // The first time through (pktcount==0), if this record is verified unique
1824 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
1825 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
1826 rr->SendNSECNow = mDNSInterfaceMark;
1827
1828 if (newptr) // If succeeded in sending, advance to next interface
1829 {
1830 // If sending on all interfaces, go to next interface; else we're finished now
1831 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
1832 rr->SendRNow = GetNextActiveInterfaceID(intf);
1833 else
1834 rr->SendRNow = mDNSNULL;
1835 }
1836 }
1837 }
1838
1839 // Second Pass. Add additional records, if there's space.
1840 newptr = responseptr;
1841 for (rr = m->ResourceRecords; rr; rr=rr->next)
1842 if (rr->ImmedAdditional == intf->InterfaceID)
1843 if (ResourceRecordIsValidAnswer(rr))
1844 {
1845 // If we have at least one answer already in the packet, then plan to add additionals too
1846 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
1847
1848 // If we're not planning to send any additionals, but this record is a unique one, then
1849 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
1850 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
1851 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
1852 {
1853 const AuthRecord *a;
1854 for (a = m->ResourceRecords; a; a=a->next)
1855 if (a->LastMCTime == m->timenow &&
1856 a->LastMCInterface == intf->InterfaceID &&
1857 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
1858 }
1859 if (!SendAdditional) // If we don't want to send this after all,
1860 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
1861 else if (newptr) // Else, try to add it if we can
1862 {
1863 // The first time through (pktcount==0), if this record is verified unique
1864 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
1865 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
1866 rr->SendNSECNow = mDNSInterfaceMark;
1867
1868 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1869 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
1870 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
1871 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
1872 if (newptr)
1873 {
1874 responseptr = newptr;
1875 rr->ImmedAdditional = mDNSNULL;
1876 rr->RequireGoodbye = mDNStrue;
1877 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
1878 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
1879 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
1880 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
1881 rr->LastMCTime = m->timenow;
1882 rr->LastMCInterface = intf->InterfaceID;
1883 }
1884 }
1885 }
1886
1887 // Third Pass. Add NSEC records, if there's space.
1888 // When we're generating an NSEC record in response to a specify query for that type
1889 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
1890 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
1891 for (rr = m->ResourceRecords; rr; rr=rr->next)
1892 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
1893 {
1894 AuthRecord nsec;
1895 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, mDNSNULL, mDNSNULL);
1896 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
1897 AssignDomainName(&nsec.namestorage, rr->resrec.name);
1898 mDNSPlatformMemZero(nsec.rdatastorage.u.nsec.bitmap, sizeof(nsec.rdatastorage.u.nsec.bitmap));
1899 for (r2 = m->ResourceRecords; r2; r2=r2->next)
1900 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
1901 {
1902 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
1903 else nsec.rdatastorage.u.nsec.bitmap[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
1904 }
1905 newptr = responseptr;
1906 if (!r2) // If we successfully built our NSEC record, add it to the packet now
1907 {
1908 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
1909 if (newptr) responseptr = newptr;
1910 }
1911
1912 // If we successfully put the NSEC record, clear the SendNSECNow flag
1913 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
1914 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
1915 {
1916 rr->SendNSECNow = mDNSNULL;
1917 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
1918 for (r2 = rr->next; r2; r2=r2->next)
1919 if (SameResourceRecordNameClassInterface(r2, rr))
1920 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
1921 r2->SendNSECNow = mDNSNULL;
1922 }
1923 }
1924
1925 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
1926 {
1927 // If we have data to send, add OWNER option if necessary, then send packet
1928
1929 if (OwnerRecordSpace)
1930 {
1931 AuthRecord opt;
1932 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
1933 opt.resrec.rrclass = NormalMaxDNSMessageData;
1934 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
1935 opt.resrec.rdestimate = sizeof(rdataOPT);
1936 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
1937 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
1938 if (newptr) { responseptr = newptr; LogSPS("SendResponses put %s", ARDisplayString(m, &opt)); }
1939 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
1940 LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
1941 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
1942 else
1943 LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
1944 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
1945 }
1946
1947 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
1948 numDereg, numDereg == 1 ? "" : "s",
1949 numAnnounce, numAnnounce == 1 ? "" : "s",
1950 numAnswer, numAnswer == 1 ? "" : "s",
1951 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
1952 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
1953 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
1954 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
1955 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
1956 // There might be more things to send on this interface, so go around one more time and try again.
1957 }
1958 else // Nothing more to send on this interface; go to next
1959 {
1960 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
1961 #if MDNS_DEBUGMSGS && 0
1962 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
1963 debugf(msg, intf, next);
1964 #endif
1965 intf = next;
1966 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
1967 }
1968 }
1969
1970 // ***
1971 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
1972 // ***
1973
1974 if (m->CurrentRecord)
1975 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
1976 m->CurrentRecord = m->ResourceRecords;
1977 while (m->CurrentRecord)
1978 {
1979 rr = m->CurrentRecord;
1980 m->CurrentRecord = rr->next;
1981
1982 if (rr->SendRNow)
1983 {
1984 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly && rr->resrec.InterfaceID != mDNSInterface_P2P)
1985 LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr->SendRNow, rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
1986 rr->SendRNow = mDNSNULL;
1987 }
1988
1989 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1990 {
1991 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
1992
1993 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
1994 {
1995 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
1996 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
1997 }
1998 else
1999 {
2000 rr->ImmedAnswer = mDNSNULL;
2001 rr->ImmedUnicast = mDNSfalse;
2002 rr->v4Requester = zerov4Addr;
2003 rr->v6Requester = zerov6Addr;
2004 }
2005 }
2006 }
2007 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2008 }
2009
2010 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2011 // so we want to be lazy about how frequently we do it.
2012 // 1. If a cache record is currently referenced by *no* active questions,
2013 // then we don't mind expiring it up to a minute late (who will know?)
2014 // 2. Else, if a cache record is due for some of its final expiration queries,
2015 // we'll allow them to be late by up to 2% of the TTL
2016 // 3. Else, if a cache record has completed all its final expiration queries without success,
2017 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2018 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2019 // so allow at most 1/10 second lateness
2020 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2021 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2022 #define CacheCheckGracePeriod(RR) ( \
2023 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
2024 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
2025 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
2026 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
2027
2028 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2029
2030 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2031 {
2032 if (m->rrcache_nextcheck[slot] - event > 0)
2033 m->rrcache_nextcheck[slot] = event;
2034 if (m->NextCacheCheck - event > 0)
2035 m->NextCacheCheck = event;
2036 }
2037
2038 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2039 // rr->TimeRcvd
2040 // rr->resrec.rroriginalttl
2041 // rr->UnansweredQueries
2042 // rr->CRActiveQuestion
2043 mDNSlocal void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2044 {
2045 rr->NextRequiredQuery = RRExpireTime(rr);
2046
2047 // If we have an active question, then see if we want to schedule a refresher query for this record.
2048 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2049 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2050 {
2051 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2052 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2053 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2054 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2055 }
2056
2057 ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2058 }
2059
2060 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
2061 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
2062 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
2063 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2064
2065 mDNSlocal mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2066 {
2067 if (interval < kMinimumReconfirmTime)
2068 interval = kMinimumReconfirmTime;
2069 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
2070 interval = 0x10000000;
2071
2072 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2073 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2074 {
2075 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2076 // For all the reconfirmations in a given batch, we want to use the same random value
2077 // so that the reconfirmation questions can be grouped into a single query packet
2078 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2079 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2080 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
2081 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2082 SetNextCacheCheckTimeForRecord(m, rr);
2083 }
2084 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2085 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2086 return(mStatus_NoError);
2087 }
2088
2089 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
2090
2091 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2092 // It also appends to the list of known answer records that need to be included,
2093 // and updates the forcast for the size of the known answer section.
2094 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
2095 CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2096 {
2097 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
2098 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2099 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2100 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2101 if (!newptr)
2102 {
2103 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2104 return(mDNSfalse);
2105 }
2106 else
2107 {
2108 mDNSu32 forecast = *answerforecast;
2109 const mDNSu32 slot = HashSlot(&q->qname);
2110 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2111 CacheRecord *rr;
2112 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
2113
2114 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2115 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2116 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
2117 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not already in the known answer list
2118 rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2119 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2120 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
2121 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
2122 {
2123 // We don't want to include unique records in the Known Answer section. The Known Answer section
2124 // is intended to suppress floods of shared-record replies from many other devices on the network.
2125 // That concept really does not apply to unique records, and indeed if we do send a query for
2126 // which we have a unique record already in our cache, then including that unique record as a
2127 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2128
2129 *ka = rr; // Link this record into our known answer chain
2130 ka = &rr->NextInKAList;
2131 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2132 forecast += 12 + rr->resrec.rdestimate;
2133 // If we're trying to put more than one question in this packet, and it doesn't fit
2134 // then undo that last question and try again next time
2135 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
2136 {
2137 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2138 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data);
2139 query->h.numQuestions--;
2140 ka = *kalistptrptr; // Go back to where we started and retract these answer records
2141 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
2142 return(mDNSfalse); // Return false, so we'll try again in the next packet
2143 }
2144 }
2145
2146 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2147 *queryptr = newptr; // Update the packet pointer
2148 *answerforecast = forecast; // Update the forecast
2149 *kalistptrptr = ka; // Update the known answer list pointer
2150 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
2151
2152 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // For every resource record in our cache,
2153 if (rr->resrec.InterfaceID == q->SendQNow && // received on this interface
2154 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList && // which is not in the known answer list
2155 SameNameRecordAnswersQuestion(&rr->resrec, q)) // which answers our question
2156 {
2157 rr->UnansweredQueries++; // indicate that we're expecting a response
2158 rr->LastUnansweredTime = m->timenow;
2159 SetNextCacheCheckTimeForRecord(m, rr);
2160 }
2161
2162 return(mDNStrue);
2163 }
2164 }
2165
2166 // When we have a query looking for a specified name, but there appear to be no answers with
2167 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2168 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
2169 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2170 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2171 // A typical reconfirmation scenario might go like this:
2172 // Depth 0: Name "myhost.local" has no address records
2173 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2174 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2175 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2176 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2177 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2178 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
2179 {
2180 mDNSu32 slot;
2181 CacheGroup *cg;
2182 CacheRecord *cr;
2183 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
2184 FORALL_CACHERECORDS(slot, cg, cr)
2185 {
2186 domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
2187 if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
2188 {
2189 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
2190 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
2191 if (depth < 5) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
2192 }
2193 }
2194 }
2195
2196 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2197 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
2198 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2199 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2200 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
2201 {
2202 CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
2203 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
2204 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
2205 return(cr);
2206 }
2207
2208 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
2209 {
2210 CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
2211 const CacheRecord *cr, *bestcr = mDNSNULL;
2212 mDNSu32 bestmetric = 1000000;
2213 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
2214 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
2215 if (cr != c0 && cr != c1) // that's not one we've seen before,
2216 if (SameNameRecordAnswersQuestion(&cr->resrec, q)) // and answers our browse query,
2217 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
2218 {
2219 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
2220 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
2221 }
2222 return(bestcr);
2223 }
2224
2225 // Finds the three best Sleep Proxies we currently have in our cache
2226 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
2227 {
2228 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
2229 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
2230 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
2231 }
2232
2233 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2234 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
2235 {
2236 int i;
2237 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2238 }
2239
2240 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
2241 {
2242 int i;
2243 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
2244 }
2245
2246 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
2247 {
2248 int i;
2249 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2250 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2251 for (i=0; i<DupSuppressInfoSize; i++)
2252 if (ds[i].InterfaceID == intf->InterfaceID)
2253 {
2254 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
2255 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
2256 if (v4 && v6) return(mDNStrue);
2257 }
2258 return(mDNSfalse);
2259 }
2260
2261 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
2262 {
2263 int i, j;
2264
2265 // See if we have this one in our list somewhere already
2266 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
2267
2268 // If not, find a slot we can re-use
2269 if (i >= DupSuppressInfoSize)
2270 {
2271 i = 0;
2272 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
2273 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
2274 i = j;
2275 }
2276
2277 // Record the info about this query we saw
2278 ds[i].Time = Time;
2279 ds[i].InterfaceID = InterfaceID;
2280 ds[i].Type = Type;
2281
2282 return(i);
2283 }
2284
2285 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
2286 {
2287 int len, i, cnt;
2288 mDNSInterfaceID InterfaceID = q->InterfaceID;
2289 domainname *d = &q->qname;
2290
2291 // We can't send magic packets without knowing which interface to send it on.
2292 if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
2293 {
2294 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
2295 return;
2296 }
2297
2298 // Split MAC@IPAddress and pass them separately
2299 len = d->c[0];
2300 i = 1;
2301 cnt = 0;
2302 for (i = 1; i < len; i++)
2303 {
2304 if (d->c[i] == '@')
2305 {
2306 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
2307 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
2308 if (cnt != 5)
2309 {
2310 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
2311 return;
2312 }
2313 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
2314 {
2315 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
2316 return;
2317 }
2318 if ((len - i) > (int)(sizeof(IPAddr) - 1))
2319 {
2320 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
2321 return;
2322 }
2323 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
2324 EthAddr[i - 1] = 0;
2325 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
2326 IPAddr[len - i] = 0;
2327 mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
2328 return;
2329 }
2330 else if (d->c[i] == ':')
2331 cnt++;
2332 }
2333 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
2334 }
2335
2336 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
2337 {
2338 // If more than 90% of the way to the query time, we should unconditionally accelerate it
2339 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
2340 return(mDNStrue);
2341
2342 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2343 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
2344 {
2345 // We forecast: qname (n) type (2) class (2)
2346 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
2347 const mDNSu32 slot = HashSlot(&q->qname);
2348 const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2349 const CacheRecord *rr;
2350 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) // If we have a resource record in our cache,
2351 if (rr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
2352 SameNameRecordAnswersQuestion(&rr->resrec, q) && // which answers our question
2353 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
2354 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0)// and we'll ask at least once again before NextRequiredQuery
2355 {
2356 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2357 forecast += 12 + rr->resrec.rdestimate;
2358 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
2359 }
2360 return(mDNStrue);
2361 }
2362
2363 return(mDNSfalse);
2364 }
2365
2366 // How Standard Queries are generated:
2367 // 1. The Question Section contains the question
2368 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
2369
2370 // How Probe Queries are generated:
2371 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2372 // if some other host is already using *any* records with this name, we want to know about it.
2373 // 2. The Authority Section contains the proposed values we intend to use for one or more
2374 // of our records with that name (analogous to the Update section of DNS Update packets)
2375 // because if some other host is probing at the same time, we each want to know what the other is
2376 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2377
2378 mDNSlocal void SendQueries(mDNS *const m)
2379 {
2380 mDNSu32 slot;
2381 CacheGroup *cg;
2382 CacheRecord *cr;
2383 AuthRecord *ar;
2384 int pktcount = 0;
2385 DNSQuestion *q;
2386 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2387 mDNSs32 maxExistingQuestionInterval = 0;
2388 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2389 CacheRecord *KnownAnswerList = mDNSNULL;
2390
2391 // 1. If time for a query, work out what we need to do
2392
2393 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
2394 // to their NextRequiredQuery to be worth batching them together with this one
2395 FORALL_CACHERECORDS(slot, cg, cr)
2396 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
2397 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
2398 {
2399 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
2400 q = cr->CRActiveQuestion;
2401 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
2402 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2403 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2404 if (q->Target.type) q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
2405 else if (!mDNSOpaque16IsZero(q->TargetQID)) { q->LastQTime = m->timenow - q->ThisQInterval; cr->UnansweredQueries++; }
2406 else if (q->SendQNow == mDNSNULL) q->SendQNow = cr->resrec.InterfaceID;
2407 else if (q->SendQNow != cr->resrec.InterfaceID) q->SendQNow = mDNSInterfaceMark;
2408 }
2409
2410 // Scan our list of questions to see which:
2411 // *WideArea* queries need to be sent
2412 // *unicast* queries need to be sent
2413 // *multicast* queries we're definitely going to send
2414 if (m->CurrentQuestion)
2415 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2416 m->CurrentQuestion = m->Questions;
2417 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
2418 {
2419 q = m->CurrentQuestion;
2420 if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
2421 {
2422 mDNSu8 *qptr = m->omsg.data;
2423 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
2424
2425 // If we fail to get a new on-demand socket (should only happen cases of the most extreme resource exhaustion), we'll try again next time
2426 if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
2427 if (q->LocalSocket)
2428 {
2429 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
2430 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
2431 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL);
2432 q->ThisQInterval *= QuestionIntervalStep;
2433 }
2434 if (q->ThisQInterval > MaxQuestionInterval)
2435 q->ThisQInterval = MaxQuestionInterval;
2436 q->LastQTime = m->timenow;
2437 q->LastQTxTime = m->timenow;
2438 q->RecentAnswerPkts = 0;
2439 q->SendQNow = mDNSNULL;
2440 q->ExpectUnicastResp = NonZeroTime(m->timenow);
2441 }
2442 else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
2443 {
2444 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2445 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
2446 if (maxExistingQuestionInterval < q->ThisQInterval)
2447 maxExistingQuestionInterval = q->ThisQInterval;
2448 }
2449 // If m->CurrentQuestion wasn't modified out from under us, advance it now
2450 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
2451 // m->CurrentQuestion point to the right question
2452 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
2453 }
2454 while (m->CurrentQuestion)
2455 {
2456 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2457 m->CurrentQuestion = m->CurrentQuestion->next;
2458 }
2459 m->CurrentQuestion = mDNSNULL;
2460
2461 // Scan our list of questions
2462 // (a) to see if there are any more that are worth accelerating, and
2463 // (b) to update the state variables for *all* the questions we're going to send
2464 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
2465 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
2466 // 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.
2467 m->NextScheduledQuery = m->timenow + 0x78000000;
2468 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
2469 {
2470 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow ||
2471 (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
2472 {
2473 // If at least halfway to next query time, advance to next interval
2474 // If less than halfway to next query time, then
2475 // treat this as logically a repeat of the last transmission, without advancing the interval
2476 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
2477 {
2478 //LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2479 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
2480 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
2481 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
2482 q->ThisQInterval *= QuestionIntervalStep;
2483 if (q->ThisQInterval > MaxQuestionInterval)
2484 q->ThisQInterval = MaxQuestionInterval;
2485 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
2486 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
2487 {
2488 // Generally don't need to log this.
2489 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
2490 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
2491 // and when there simply happen to be no instances of the service the client is looking
2492 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
2493 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
2494 q->qname.c, DNSTypeName(q->qtype));
2495 // Sending third query, and no answers yet; time to begin doubting the source
2496 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
2497 }
2498 }
2499
2500 // Mark for sending. (If no active interfaces, then don't even try.)
2501 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
2502 if (q->SendOnAll)
2503 {
2504 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
2505 q->LastQTime = m->timenow;
2506 }
2507
2508 // If we recorded a duplicate suppression for this question less than half an interval ago,
2509 // then we consider it recent enough that we don't need to do an identical query ourselves.
2510 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
2511
2512 q->LastQTxTime = m->timenow;
2513 q->RecentAnswerPkts = 0;
2514 if (q->RequestUnicast) q->RequestUnicast--;
2515 }
2516 // For all questions (not just the ones we're sending) check what the next scheduled event will be
2517 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
2518 SetNextQueryTime(m,q);
2519 }
2520
2521 // 2. Scan our authoritative RR list to see what probes we might need to send
2522
2523 m->NextScheduledProbe = m->timenow + 0x78000000;
2524
2525 if (m->CurrentRecord)
2526 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2527 m->CurrentRecord = m->ResourceRecords;
2528 while (m->CurrentRecord)
2529 {
2530 ar = m->CurrentRecord;
2531 m->CurrentRecord = ar->next;
2532 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
2533 {
2534 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
2535 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
2536 {
2537 SetNextAnnounceProbeTime(m, ar);
2538 }
2539 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
2540 else if (ar->ProbeCount)
2541 {
2542 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
2543 {
2544 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
2545 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
2546 }
2547 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
2548 {
2549 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
2550 // IPv6 source = zero
2551 // No target hardware address
2552 // IPv6 target address is address we're probing
2553 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
2554 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
2555 }
2556 // Mark for sending. (If no active interfaces, then don't even try.)
2557 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
2558 ar->LastAPTime = m->timenow;
2559 // When we have a late conflict that resets a record to probing state we use a special marker value greater
2560 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
2561 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
2562 ar->ProbeCount = DefaultProbeCountForTypeUnique;
2563 ar->ProbeCount--;
2564 SetNextAnnounceProbeTime(m, ar);
2565 if (ar->ProbeCount == 0)
2566 {
2567 // If this is the last probe for this record, then see if we have any matching records
2568 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
2569 AuthRecord *r2;
2570 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
2571 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
2572 r2->ProbeCount = 0;
2573 // ... then acknowledge this record to the client.
2574 // We do this optimistically, just as we're about to send the third probe.
2575 // This helps clients that both advertise and browse, and want to filter themselves
2576 // from the browse results list, because it helps ensure that the registration
2577 // confirmation will be delivered 1/4 second *before* the browse "add" event.
2578 // A potential downside is that we could deliver a registration confirmation and then find out
2579 // moments later that there's a name conflict, but applications have to be prepared to handle
2580 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
2581 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
2582 }
2583 }
2584 // else, if it has now finished probing, move it to state Verified,
2585 // and update m->NextScheduledResponse so it will be announced
2586 else
2587 {
2588 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
2589 ar->resrec.RecordType = kDNSRecordTypeVerified;
2590 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
2591 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
2592 SetNextAnnounceProbeTime(m, ar);
2593 }
2594 }
2595 }
2596 m->CurrentRecord = m->DuplicateRecords;
2597 while (m->CurrentRecord)
2598 {
2599 ar = m->CurrentRecord;
2600 m->CurrentRecord = ar->next;
2601 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
2602 AcknowledgeRecord(m, ar);
2603 }
2604
2605 // 3. Now we know which queries and probes we're sending,
2606 // go through our interface list sending the appropriate queries on each interface
2607 while (intf)
2608 {
2609 const int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2610 mDNSu8 *queryptr = m->omsg.data;
2611 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
2612 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
2613 if (!KnownAnswerList)
2614 {
2615 // Start a new known-answer list
2616 CacheRecord **kalistptr = &KnownAnswerList;
2617 mDNSu32 answerforecast = OwnerRecordSpace; // We start by assuming we'll need at least enough space to put the Owner Option
2618
2619 // Put query questions in this packet
2620 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
2621 {
2622 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
2623 {
2624 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
2625 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
2626 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
2627
2628 // If we're suppressing this question, or we successfully put it, update its SendQNow state
2629 if (SuppressOnThisInterface(q->DupSuppress, intf) ||
2630 BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
2631 {
2632 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
2633 if (q->WakeOnResolveCount)
2634 {
2635 mDNSSendWakeOnResolve(m, q);
2636 q->WakeOnResolveCount--;
2637 }
2638 }
2639 }
2640 }
2641
2642 // Put probe questions in this packet
2643 for (ar = m->ResourceRecords; ar; ar=ar->next)
2644 if (ar->SendRNow == intf->InterfaceID)
2645 {
2646 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
2647 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2648 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
2649 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2650 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
2651 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
2652 if (newptr)
2653 {
2654 queryptr = newptr;
2655 answerforecast = forecast;
2656 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
2657 ar->IncludeInProbe = mDNStrue;
2658 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d",
2659 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
2660 }
2661 }
2662 }
2663
2664 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
2665 while (KnownAnswerList)
2666 {
2667 CacheRecord *ka = KnownAnswerList;
2668 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
2669 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers,
2670 &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace);
2671 if (newptr)
2672 {
2673 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
2674 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
2675 queryptr = newptr;
2676 KnownAnswerList = ka->NextInKAList;
2677 ka->NextInKAList = mDNSNULL;
2678 }
2679 else
2680 {
2681 // If we ran out of space and we have more than one question in the packet, that's an error --
2682 // we shouldn't have put more than one question if there was a risk of us running out of space.
2683 if (m->omsg.h.numQuestions > 1)
2684 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
2685 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
2686 break;
2687 }
2688 }
2689
2690 for (ar = m->ResourceRecords; ar; ar=ar->next)
2691 if (ar->IncludeInProbe)
2692 {
2693 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
2694 ar->IncludeInProbe = mDNSfalse;
2695 if (newptr) queryptr = newptr;
2696 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
2697 }
2698
2699 if (queryptr > m->omsg.data)
2700 {
2701 if (OwnerRecordSpace)
2702 {
2703 AuthRecord opt;
2704 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
2705 opt.resrec.rrclass = NormalMaxDNSMessageData;
2706 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
2707 opt.resrec.rdestimate = sizeof(rdataOPT);
2708 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2709 LogSPS("SendQueries putting %s", ARDisplayString(m, &opt));
2710 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
2711 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
2712 if (!queryptr)
2713 LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
2714 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2715 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
2716 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
2717 LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
2718 m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr,
2719 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2720 }
2721
2722 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
2723 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
2724 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
2725 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
2726 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
2727 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
2728 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL);
2729 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL);
2730 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2731 if (++pktcount >= 1000)
2732 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
2733 // There might be more records left in the known answer list, or more questions to send
2734 // on this interface, so go around one more time and try again.
2735 }
2736 else // Nothing more to send on this interface; go to next
2737 {
2738 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2739 #if MDNS_DEBUGMSGS && 0
2740 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
2741 debugf(msg, intf, next);
2742 #endif
2743 intf = next;
2744 }
2745 }
2746
2747 // 4. Final housekeeping
2748
2749 // 4a. Debugging check: Make sure we announced all our records
2750 for (ar = m->ResourceRecords; ar; ar=ar->next)
2751 if (ar->SendRNow)
2752 {
2753 if (ar->resrec.InterfaceID != mDNSInterface_LocalOnly && ar->resrec.InterfaceID != mDNSInterface_P2P)
2754 LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar->SendRNow, ar->resrec.InterfaceID, ARDisplayString(m, ar));
2755 ar->SendRNow = mDNSNULL;
2756 }
2757
2758 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
2759 // that their interface which went away might come back again, the logic will want to send queries
2760 // for those records, but we can't because their interface isn't here any more, so to keep the
2761 // state machine ticking over we just pretend we did so.
2762 // If the interface does not come back in time, the cache record will expire naturally
2763 FORALL_CACHERECORDS(slot, cg, cr)
2764 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
2765 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
2766 {
2767 cr->UnansweredQueries++;
2768 cr->CRActiveQuestion->SendQNow = mDNSNULL;
2769 SetNextCacheCheckTimeForRecord(m, cr);
2770 }
2771
2772 // 4c. Debugging check: Make sure we sent all our planned questions
2773 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
2774 // we legitimately couldn't send because the interface is no longer available
2775 for (q = m->Questions; q; q=q->next)
2776 if (q->SendQNow)
2777 {
2778 DNSQuestion *x;
2779 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
2780 LogMsg("SendQueries: No active interface %p to send %s question: %p %##s (%s)", q->SendQNow, x ? "new" : "old", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
2781 q->SendQNow = mDNSNULL;
2782 }
2783 }
2784
2785 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
2786 {
2787 int i, j;
2788 mDNSu8 *ptr = m->omsg.data;
2789 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2790 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
2791
2792 // 0x00 Destination address
2793 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
2794
2795 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2796 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2797
2798 // 0x0C Ethertype (0x0842)
2799 *ptr++ = 0x08;
2800 *ptr++ = 0x42;
2801
2802 // 0x0E Wakeup sync sequence
2803 for (i=0; i<6; i++) *ptr++ = 0xFF;
2804
2805 // 0x14 Wakeup data
2806 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
2807
2808 // 0x74 Password
2809 for (i=0; i<6; i++) *ptr++ = password->b[i];
2810
2811 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
2812
2813 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
2814 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
2815 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
2816 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
2817 // So, we send one of each, unicast first, then broadcast second.
2818 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
2819 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
2820 }
2821
2822 // ***************************************************************************
2823 #if COMPILER_LIKES_PRAGMA_MARK
2824 #pragma mark -
2825 #pragma mark - RR List Management & Task Management
2826 #endif
2827
2828 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
2829 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
2830 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
2831 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
2832 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
2833 {
2834 DNSQuestion *const q = m->CurrentQuestion;
2835 mDNSBool followcname = rr->resrec.RecordType != kDNSRecordTypePacketNegative && AddRecord &&
2836 rr->resrec.rrtype == kDNSType_CNAME && q->qtype != kDNSType_CNAME;
2837 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
2838 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
2839
2840 if (QuerySuppressed(q)) return;
2841
2842 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
2843 // may be called twice, once when the record is received, and again when it's time to notify local clients.
2844 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
2845
2846 rr->LastUsed = m->timenow;
2847 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
2848 {
2849 if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
2850 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
2851 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
2852 rr->CRActiveQuestion = q; // We know q is non-null
2853 SetNextCacheCheckTimeForRecord(m, rr);
2854 }
2855
2856 // If this is:
2857 // (a) a no-cache add, where we've already done at least one 'QM' query, or
2858 // (b) a normal add, where we have at least one unique-type answer,
2859 // then there's no need to keep polling the network.
2860 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
2861 // We do this for mDNS questions and uDNS one-shot questions, but not for
2862 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
2863 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
2864 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
2865 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
2866 {
2867 q->LastQTime = m->timenow;
2868 q->LastQTxTime = m->timenow;
2869 q->RecentAnswerPkts = 0;
2870 q->ThisQInterval = MaxQuestionInterval;
2871 q->RequestUnicast = mDNSfalse;
2872 debugf("AnswerCurrentQuestionWithResourceRecord: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2873 }
2874
2875 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
2876
2877 // Only deliver negative answers if client has explicitly requested them
2878 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
2879 if (!AddRecord || !q->ReturnIntermed) return;
2880
2881 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
2882 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
2883 {
2884 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
2885 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
2886 {
2887 CacheRecord neg;
2888 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
2889 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
2890 }
2891 else
2892 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
2893 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2894 }
2895 // Note: Proceed with caution here because client callback function is allowed to do anything,
2896 // including starting/stopping queries, registering/deregistering records, etc.
2897
2898 if (followcname && m->CurrentQuestion == q)
2899 {
2900 const mDNSBool selfref = SameDomainName(&q->qname, &rr->resrec.rdata->u.name);
2901 if (q->CNAMEReferrals >= 10 || selfref)
2902 LogMsg("AnswerCurrentQuestionWithResourceRecord: %p %##s (%s) NOT following CNAME referral %d%s for %s",
2903 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", CRDisplayString(m, rr));
2904 else
2905 {
2906 const mDNSu32 c = q->CNAMEReferrals + 1; // Stash a copy of the new q->CNAMEReferrals value
2907
2908 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
2909 // themselves. Without that check we can get into a case where we have two duplicate questions,
2910 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
2911 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
2912 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
2913 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
2914 // for either of them. This is not a problem for CNAME loops of two or more records because in
2915 // those cases the newly re-appended question A has a different target name and therefore cannot be
2916 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
2917
2918 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
2919 // and track CNAMEs coming and going, we should really create a subordinate query here,
2920 // which we would subsequently cancel and retract if the CNAME referral record were removed.
2921 // In reality this is such a corner case we'll ignore it until someone actually needs it.
2922 LogInfo("AnswerCurrentQuestionWithResourceRecord: %p %##s (%s) following CNAME referral %d for %s",
2923 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, CRDisplayString(m, rr));
2924
2925 mDNS_StopQuery_internal(m, q); // Stop old query
2926 AssignDomainName(&q->qname, &rr->resrec.rdata->u.name); // Update qname
2927 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
2928 // If a unicast query results in a CNAME that points to a .local, we need to re-try
2929 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
2930 // to try this as unicast query even though it is a .local name
2931 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
2932 {
2933 LogInfo("AnswerCurrentQuestionWithResourceRecord: Resolving a .local CNAME %p %##s (%s) CacheRecord %s",
2934 q, q->qname.c, DNSTypeName(q->qtype), CRDisplayString(m, rr));
2935 q->InterfaceID = mDNSInterface_Unicast;
2936 }
2937 mDNS_StartQuery_internal(m, q); // start new query
2938 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
2939 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
2940 q->CNAMEReferrals = c;
2941 }
2942 }
2943 }
2944
2945 // New Questions are answered through AnswerNewQuestion. But there may not have been any
2946 // matching cache records for the questions when it is called. There are two possibilities.
2947 //
2948 // 1) There are no cache records
2949 // 2) There are cache records but the DNSServers between question and cache record don't match.
2950 //
2951 // In the case of (1), where there are no cache records and later we add them when we get a response,
2952 // CacheRecordAdd/CacheRecordDeferredAdd will take care of adding the cache and delivering the ADD
2953 // events to the application. If we already have a cache entry, then no ADD events are delivered
2954 // unless the RDATA has changed
2955 //
2956 // In the case of (2) where we had the cache records and did not answer because of the DNSServer mismatch,
2957 // we need to answer them whenever we change the DNSServer. But we can't do it at the instant the DNSServer
2958 // changes because when we do the callback, the question can get deleted and the calling function would not
2959 // know how to handle it. So, we run this function from mDNS_Execute to handle DNSServer changes on the
2960 // question
2961
2962 mDNSlocal void AnswerQuestionsForDNSServerChanges(mDNS *const m)
2963 {
2964 DNSQuestion *q;
2965 DNSQuestion *qnext;
2966 CacheRecord *rr;
2967 mDNSu32 slot;
2968 CacheGroup *cg;
2969
2970 if (m->CurrentQuestion)
2971 LogMsg("AnswerQuestionsForDNSServerChanges: ERROR m->CurrentQuestion already set: %##s (%s)",
2972 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
2973
2974 for (q = m->Questions; q && q != m->NewQuestions; q = qnext)
2975 {
2976 qnext = q->next;
2977
2978 // multicast or DNSServers did not change.
2979 if (mDNSOpaque16IsZero(q->TargetQID)) continue;
2980 if (!q->deliverAddEvents) continue;
2981
2982 // We are going to look through the cache for this question since it changed
2983 // its DNSserver last time. Reset it so that we don't call them again. Calling
2984 // them again will deliver duplicate events to the application
2985 q->deliverAddEvents = mDNSfalse;
2986 if (QuerySuppressed(q)) continue;
2987 m->CurrentQuestion = q;
2988 slot = HashSlot(&q->qname);
2989 cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2990 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
2991 {
2992 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
2993 {
2994 LogInfo("AnswerQuestionsForDNSServerChanges: Calling AnswerCurrentQuestionWithResourceRecord for question %p %##s using resource record %s",
2995 q, q->qname.c, CRDisplayString(m, rr));
2996 // When this question penalizes a DNS server and has no more DNS servers to pick, we normally
2997 // deliver a negative cache response and suspend the question for 60 seconds (see uDNS_CheckCurrentQuestion).
2998 // But sometimes we may already find the negative cache entry and deliver that here as the process
2999 // of changing DNS servers. When the cache entry is about to expire, we will resend the question and
3000 // that time, we need to make sure that we have a valid DNS server. Otherwise, we will deliver
3001 // a negative cache response without trying the server.
3002 if (!q->qDNSServer && !q->DuplicateOf && rr->resrec.RecordType == kDNSRecordTypePacketNegative)
3003 {
3004 DNSQuestion *qptr;
3005 SetValidDNSServers(m, q);
3006 q->qDNSServer = GetServerForQuestion(m, q);
3007 for (qptr = q->next ; qptr; qptr = qptr->next)
3008 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
3009 }
3010 q->CurrentAnswers++;
3011 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3012 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3013 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3014 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3015 }
3016 }
3017 }
3018 m->CurrentQuestion = mDNSNULL;
3019 }
3020
3021 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
3022 {
3023 rr->DelayDelivery = 0;
3024 if (m->CurrentQuestion)
3025 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3026 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3027 m->CurrentQuestion = m->Questions;
3028 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3029 {
3030 DNSQuestion *q = m->CurrentQuestion;
3031 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3032 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3033 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3034 m->CurrentQuestion = q->next;
3035 }
3036 m->CurrentQuestion = mDNSNULL;
3037 }
3038
3039 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot)
3040 {
3041 const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
3042 const mDNSs32 start = m->timenow - 0x10000000;
3043 mDNSs32 delay = start;
3044 CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
3045 const CacheRecord *rr;
3046 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3047 if (threshhold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
3048 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
3049 delay = RRExpireTime(rr);
3050 if (delay - start > 0) return(NonZeroTime(delay));
3051 else return(0);
3052 }
3053
3054 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
3055 // If new questions are created as a result of invoking client callbacks, they will be added to
3056 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3057 // rr is a new CacheRecord just received into our cache
3058 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3059 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3060 // which may change the record list and/or question list.
3061 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3062 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
3063 {
3064 DNSQuestion *q;
3065
3066 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3067 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3068 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3069 {
3070 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3071 {
3072 // If this question is one that's actively sending queries, and it's received ten answers within one
3073 // second of sending the last query packet, then that indicates some radical network topology change,
3074 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3075 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3076 // because we will anyway send another query within a few seconds. The first reset query is sent out
3077 // randomized over the next four seconds to reduce possible synchronization between machines.
3078 if (q->LastAnswerPktNum != m->PktNum)
3079 {
3080 q->LastAnswerPktNum = m->PktNum;
3081 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
3082 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
3083 {
3084 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3085 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
3086 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
3087 q->ThisQInterval = InitialQuestionInterval;
3088 SetNextQueryTime(m,q);
3089 }
3090 }
3091 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
3092 DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
3093 &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
3094 rr->resrec.rDNSServer->port : zeroIPPort), q);
3095 q->CurrentAnswers++;
3096 q->unansweredQueries = 0;
3097 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3098 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3099 if (q->CurrentAnswers > 4000)
3100 {
3101 static int msgcount = 0;
3102 if (msgcount++ < 10)
3103 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3104 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
3105 rr->resrec.rroriginalttl = 0;
3106 rr->UnansweredQueries = MaxUnansweredQueries;
3107 }
3108 }
3109 }
3110
3111 if (!rr->DelayDelivery)
3112 {
3113 if (m->CurrentQuestion)
3114 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3115 m->CurrentQuestion = m->Questions;
3116 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3117 {
3118 q = m->CurrentQuestion;
3119 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3120 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3121 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3122 m->CurrentQuestion = q->next;
3123 }
3124 m->CurrentQuestion = mDNSNULL;
3125 }
3126
3127 SetNextCacheCheckTimeForRecord(m, rr);
3128 }
3129
3130 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3131 // If new questions are created as a result of invoking client callbacks, they will be added to
3132 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3133 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3134 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3135 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3136 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3137 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3138 // which may change the record list and/or question list.
3139 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3140 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
3141 {
3142 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
3143 if (m->CurrentQuestion)
3144 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3145 m->CurrentQuestion = m->Questions;
3146 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
3147 // since we're not caching the record and we'll get no opportunity to do this later
3148 while (m->CurrentQuestion)
3149 {
3150 DNSQuestion *q = m->CurrentQuestion;
3151 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3152 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
3153 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3154 m->CurrentQuestion = q->next;
3155 }
3156 m->CurrentQuestion = mDNSNULL;
3157 }
3158
3159 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3160 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3161 // If new questions are created as a result of invoking client callbacks, they will be added to
3162 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3163 // rr is an existing cache CacheRecord that just expired and is being deleted
3164 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3165 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3166 // which may change the record list and/or question list.
3167 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3168 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
3169 {
3170 if (m->CurrentQuestion)
3171 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3172 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3173 m->CurrentQuestion = m->Questions;
3174
3175 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3176 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3177 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3178 {
3179 DNSQuestion *q = m->CurrentQuestion;
3180 // When a question enters suppressed state, we generate RMV events and generate a negative
3181 // response. A cache may be present that answers this question e.g., cache entry generated
3182 // before the question became suppressed. We need to skip the suppressed questions here as
3183 // the RMV event has already been generated.
3184 if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
3185 {
3186 verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
3187 q->FlappingInterface1 = mDNSNULL;
3188 q->FlappingInterface2 = mDNSNULL;
3189
3190 // When a question changes DNS server, it is marked with deliverAddEvents if we find any
3191 // cache entry corresponding to the new DNS server. Before we deliver the ADD event, the
3192 // cache entry may be removed in which case CurrentAnswers can be zero.
3193 if (q->deliverAddEvents && !q->CurrentAnswers)
3194 {
3195 LogInfo("CacheRecordRmv: Question %p %##s (%s) deliverAddEvents set, DNSServer %#a:%d",
3196 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3197 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3198 m->CurrentQuestion = q->next;
3199 continue;
3200 }
3201 if (q->CurrentAnswers == 0)
3202 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3203 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
3204 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
3205 else
3206 {
3207 q->CurrentAnswers--;
3208 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
3209 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
3210 }
3211 if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
3212 {
3213 if (q->CurrentAnswers == 0)
3214 {
3215 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3216 q->qname.c, DNSTypeName(q->qtype));
3217 ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3218 }
3219 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
3220 }
3221 }
3222 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3223 m->CurrentQuestion = q->next;
3224 }
3225 m->CurrentQuestion = mDNSNULL;
3226 }
3227
3228 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
3229 {
3230 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3231 unsigned int i;
3232 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
3233 #endif
3234 e->next = m->rrcache_free;
3235 m->rrcache_free = e;
3236 m->rrcache_totalused--;
3237 }
3238
3239 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
3240 {
3241 CacheEntity *e = (CacheEntity *)(*cp);
3242 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3243 if ((*cp)->rrcache_tail != &(*cp)->members)
3244 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3245 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
3246 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3247 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
3248 (*cp)->name = mDNSNULL;
3249 *cp = (*cp)->next; // Cut record from list
3250 ReleaseCacheEntity(m, e);
3251 }
3252
3253 mDNSlocal void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
3254 {
3255 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3256 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
3257 r->resrec.rdata = mDNSNULL;
3258 ReleaseCacheEntity(m, (CacheEntity *)r);
3259 }
3260
3261 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3262 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3263 // callbacks for old records are delivered before callbacks for newer records.
3264 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
3265 {
3266 CacheRecord **rp = &cg->members;
3267
3268 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3269 m->lock_rrcache = 1;
3270
3271 while (*rp)
3272 {
3273 CacheRecord *const rr = *rp;
3274 mDNSs32 event = RRExpireTime(rr);
3275 if (m->timenow - event >= 0) // If expired, delete it
3276 {
3277 *rp = rr->next; // Cut it from the list
3278 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3279 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
3280 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
3281 {
3282 DNSQuestion *q = rr->CRActiveQuestion;
3283 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3284 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3285 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3286 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3287 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3288 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3289 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
3290 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
3291 {
3292 q->ThisQInterval = InitialQuestionInterval;
3293 q->LastQTime = m->timenow - q->ThisQInterval;
3294 SetNextQueryTime(m, q);
3295 }
3296 CacheRecordRmv(m, rr);
3297 m->rrcache_active--;
3298 }
3299 ReleaseCacheRecord(m, rr);
3300 }
3301 else // else, not expired; see if we need to query
3302 {
3303 // If waiting to delay delivery, do nothing until then
3304 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
3305 event = rr->DelayDelivery;
3306 else
3307 {
3308 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
3309 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3310 {
3311 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
3312 event = NextCacheCheckEvent(rr); // then just record when we want the next query
3313 else // else trigger our question to go out now
3314 {
3315 // Set NextScheduledQuery to timenow so that SendQueries() will run.
3316 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
3317 m->NextScheduledQuery = m->timenow;
3318 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3319 // which will correctly update m->NextCacheCheck for us.
3320 event = m->timenow + 0x3FFFFFFF;
3321 }
3322 }
3323 }
3324 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3325 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
3326 if (m->rrcache_nextcheck[slot] - event > 0)
3327 m->rrcache_nextcheck[slot] = event;
3328 rp = &rr->next;
3329 }
3330 }
3331 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
3332 cg->rrcache_tail = rp;
3333 m->lock_rrcache = 0;
3334 }
3335
3336 // Caller should hold the lock
3337 mDNSlocal void AnswerSuppressUnusableQuestion(mDNS *const m, DNSQuestion *q)
3338 {
3339 LogInfo("AnswerSuppressUnusableQuestion: Generating negative response for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3340 if (!m->CurrentQuestion) LogMsg("AnswerSuppressUnusableQuestion: ERROR!! CurrentQuestion not set");
3341
3342 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, mDNSNULL);
3343 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
3344 if (m->CurrentQuestion == q) q->ThisQInterval = 0; // Deactivate this question
3345 // Don't touch the question after this
3346 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
3347 }
3348
3349 mDNSlocal void AnswerNewQuestion(mDNS *const m)
3350 {
3351 mDNSBool ShouldQueryImmediately = mDNStrue;
3352 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
3353 const mDNSu32 slot = HashSlot(&q->qname);
3354 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3355
3356 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3357
3358 if (cg) CheckCacheExpiration(m, slot, cg);
3359 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
3360 m->NewQuestions = q->next;
3361 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3362 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3363 //
3364 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3365 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
3366 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3367 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3368 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3369 // advanced it), that means the question was deleted, so we no longer need to worry about answering
3370 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3371 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
3372 //
3373 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
3374 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3375 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3376 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3377
3378 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3379 // This should be safe, because calling the client's question callback may cause the
3380 // question list to be modified, but should not ever cause the rrcache list to be modified.
3381 // If the client's question callback deletes the question, then m->CurrentQuestion will
3382 // be advanced, and we'll exit out of the loop
3383 m->lock_rrcache = 1;
3384 if (m->CurrentQuestion)
3385 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3386 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3387 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
3388
3389 if (q->NoAnswer == NoAnswer_Fail)
3390 {
3391 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3392 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
3393 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
3394 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
3395 q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
3396 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
3397 }
3398 if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit; }
3399
3400 // If 'mDNSInterface_Any' question, see if we want to tell it about LocalOnly records
3401 if (q->InterfaceID == mDNSInterface_Any)
3402 {
3403 if (m->CurrentRecord)
3404 LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3405 m->CurrentRecord = m->ResourceRecords;
3406 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
3407 {
3408 AuthRecord *rr = m->CurrentRecord;
3409 m->CurrentRecord = rr->next;
3410 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly || rr->resrec.InterfaceID == mDNSInterface_P2P)
3411 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3412 {
3413 AnswerLocalQuestionWithLocalAuthRecord(m, q, rr, mDNStrue);
3414 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3415 }
3416 }
3417 m->CurrentRecord = mDNSNULL;
3418 }
3419 if (m->CurrentQuestion != q) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit; }
3420
3421 // If we are not supposed to answer this question, generate a negative response.
3422 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
3423 if (QuerySuppressed(q)) { q->SuppressQuery = mDNSfalse; AnswerSuppressUnusableQuestion(m, q); q->SuppressQuery = mDNStrue; }
3424 else
3425 {
3426 CacheRecord *rr;
3427 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
3428 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
3429 {
3430 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
3431 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
3432 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
3433 {
3434 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
3435 rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
3436 continue; // Go to next one in loop
3437 }
3438
3439 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
3440 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
3441 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
3442 ShouldQueryImmediately = mDNSfalse;
3443 q->CurrentAnswers++;
3444 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
3445 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
3446 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
3447 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3448 }
3449 else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
3450 ShouldQueryImmediately = mDNSfalse;
3451 }
3452 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
3453 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
3454 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
3455
3456 if (ShouldQueryImmediately && ActiveQuestion(q))
3457 {
3458 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3459 q->ThisQInterval = InitialQuestionInterval;
3460 q->LastQTime = m->timenow - q->ThisQInterval;
3461 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
3462 {
3463 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
3464 if (!m->RandomQueryDelay)
3465 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
3466 q->LastQTime += m->RandomQueryDelay;
3467 }
3468 }
3469
3470 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
3471 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
3472 // answers for this question until *after* its scheduled transmission time, in which case
3473 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
3474 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
3475 SetNextQueryTime(m,q);
3476
3477 exit:
3478 m->CurrentQuestion = mDNSNULL;
3479 m->lock_rrcache = 0;
3480 }
3481
3482 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
3483 // appropriate answers, stopping if it reaches a NewLocalRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
3484 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
3485 {
3486 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
3487 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
3488
3489 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3490
3491 if (m->CurrentQuestion)
3492 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3493 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3494 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
3495
3496 if (m->CurrentRecord)
3497 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3498 m->CurrentRecord = m->ResourceRecords;
3499
3500 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
3501 {
3502 AuthRecord *rr = m->CurrentRecord;
3503 m->CurrentRecord = rr->next;
3504 if (ResourceRecordAnswersQuestion(&rr->resrec, q))
3505 {
3506 AnswerLocalQuestionWithLocalAuthRecord(m, q, rr, mDNStrue);
3507 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
3508 }
3509 }
3510
3511 m->CurrentQuestion = mDNSNULL;
3512 m->CurrentRecord = mDNSNULL;
3513 }
3514
3515 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
3516 {
3517 CacheEntity *e = mDNSNULL;
3518
3519 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
3520 m->lock_rrcache = 1;
3521
3522 // If we have no free records, ask the client layer to give us some more memory
3523 if (!m->rrcache_free && m->MainCallback)
3524 {
3525 if (m->rrcache_totalused != m->rrcache_size)
3526 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
3527 m->rrcache_totalused, m->rrcache_size);
3528
3529 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
3530 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
3531 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
3532 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
3533 // and recycle them, instead of allocating more memory.
3534 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
3535 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
3536 m->rrcache_size, m->rrcache_active);
3537 else
3538 {
3539 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
3540 m->MainCallback(m, mStatus_GrowCache);
3541 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3542 }
3543 }
3544
3545 // If we still have no free records, recycle all the records we can.
3546 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
3547 if (!m->rrcache_free)
3548 {
3549 mDNSu32 oldtotalused = m->rrcache_totalused;
3550 mDNSu32 slot;
3551 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
3552 {
3553 CacheGroup **cp = &m->rrcache_hash[slot];
3554 while (*cp)
3555 {
3556 CacheRecord **rp = &(*cp)->members;
3557 while (*rp)
3558 {
3559 // Records that answer still-active questions are not candidates for recycling
3560 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
3561 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
3562 rp=&(*rp)->next;
3563 else
3564 {
3565 CacheRecord *rr = *rp;
3566 *rp = (*rp)->next; // Cut record from list
3567 ReleaseCacheRecord(m, rr);
3568 }
3569 }
3570 if ((*cp)->rrcache_tail != rp)
3571 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
3572 (*cp)->rrcache_tail = rp;
3573 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
3574 else ReleaseCacheGroup(m, cp);
3575 }
3576 }
3577 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
3578 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
3579 }
3580
3581 if (m->rrcache_free) // If there are records in the free list, take one
3582 {
3583 e = m->rrcache_free;
3584 m->rrcache_free = e->next;
3585 if (++m->rrcache_totalused >= m->rrcache_report)
3586 {
3587 LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
3588 if (m->rrcache_report < 100) m->rrcache_report += 10;
3589 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
3590 else m->rrcache_report += 1000;
3591 }
3592 mDNSPlatformMemZero(e, sizeof(*e));
3593 }
3594
3595 m->lock_rrcache = 0;
3596
3597 return(e);
3598 }
3599
3600 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
3601 {
3602 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
3603 if (r)
3604 {
3605 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
3606 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
3607 {
3608 r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
3609 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
3610 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
3611 }
3612 }
3613 return(r);
3614 }
3615
3616 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
3617 {
3618 mDNSu16 namelen = DomainNameLength(rr->name);
3619 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
3620 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
3621 cg->next = m->rrcache_hash[slot];
3622 cg->namehash = rr->namehash;
3623 cg->members = mDNSNULL;
3624 cg->rrcache_tail = &cg->members;
3625 cg->name = (domainname*)cg->namestorage;
3626 //LogMsg("GetCacheGroup: %-10s %d-byte cache name %##s",
3627 // (namelen > InlineCacheGroupNameSize) ? "Allocating" : "Inline", namelen, rr->name->c);
3628 if (namelen > InlineCacheGroupNameSize) cg->name = mDNSPlatformMemAllocate(namelen);
3629 if (!cg->name)
3630 {
3631 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
3632 ReleaseCacheEntity(m, (CacheEntity*)cg);
3633 return(mDNSNULL);
3634 }
3635 AssignDomainName(cg->name, rr->name);
3636
3637 if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
3638 m->rrcache_hash[slot] = cg;
3639 if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
3640
3641 return(cg);
3642 }
3643
3644 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
3645 {
3646 if (m->mDNS_busy != m->mDNS_reentrancy+1)
3647 LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m->mDNS_busy, m->mDNS_reentrancy);
3648 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
3649 // a positive answer using an expired record (e.g. from an interface that has gone away).
3650 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
3651 // summary deletion without giving the proper callback to any questions that are monitoring it.
3652 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
3653 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
3654 rr->UnansweredQueries = MaxUnansweredQueries;
3655 rr->resrec.rroriginalttl = 0;
3656 SetNextCacheCheckTimeForRecord(m, rr);
3657 }
3658
3659 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
3660 {
3661 mDNSs32 time;
3662 mDNSPlatformLock(m);
3663 if (m->mDNS_busy)
3664 {
3665 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
3666 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
3667 }
3668
3669 if (m->timenow) time = m->timenow;
3670 else time = mDNS_TimeNow_NoLock(m);
3671 mDNSPlatformUnlock(m);
3672 return(time);
3673 }
3674
3675 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
3676 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
3677 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
3678 #define SetSPSProxyListChanged(X) do { \
3679 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
3680 m->SPSProxyListChanged = (X); } while(0)
3681
3682 // Called from mDNS_Execute() to expire stale proxy records
3683 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
3684 {
3685 m->CurrentRecord = list;
3686 while (m->CurrentRecord)
3687 {
3688 AuthRecord *rr = m->CurrentRecord;
3689 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
3690 {
3691 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
3692 // so we need to cease proxying for *all* records we may have, expired or not.
3693 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
3694 {
3695 if (m->NextScheduledSPS - rr->TimeExpire > 0)
3696 m->NextScheduledSPS = rr->TimeExpire;
3697 }
3698 else // else proxy record expired, so remove it
3699 {
3700 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
3701 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
3702 SetSPSProxyListChanged(rr->resrec.InterfaceID);
3703 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
3704 // Don't touch rr after this -- memory may have been free'd
3705 }
3706 }
3707 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
3708 // new records could have been added to the end of the list as a result of that call.
3709 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
3710 m->CurrentRecord = rr->next;
3711 }
3712 }
3713
3714 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
3715 {
3716 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
3717
3718 if (m->timenow - m->NextScheduledEvent >= 0)
3719 {
3720 int i;
3721 AuthRecord *head, *tail;
3722
3723 verbosedebugf("mDNS_Execute");
3724
3725 if (m->CurrentQuestion)
3726 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
3727 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3728
3729 if (m->CurrentRecord)
3730 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
3731
3732 // 1. If we're past the probe suppression time, we can clear it
3733 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
3734
3735 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
3736 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
3737
3738 // 3. Purge our cache of stale old records
3739 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
3740 {
3741 mDNSu32 slot, numchecked = 0;
3742 m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
3743 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
3744 {
3745 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
3746 {
3747 CacheGroup **cp = &m->rrcache_hash[slot];
3748 m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
3749 while (*cp)
3750 {
3751 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
3752 numchecked++;
3753 CheckCacheExpiration(m, slot, *cp);
3754 if ((*cp)->members) cp=&(*cp)->next;
3755 else ReleaseCacheGroup(m, cp);
3756 }
3757 }
3758 // Even if we didn't need to actually check this slot yet, still need to
3759 // factor its nextcheck time into our overall NextCacheCheck value
3760 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
3761 m->NextCacheCheck = m->rrcache_nextcheck[slot];
3762 }
3763 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
3764 }
3765
3766 if (m->timenow - m->NextScheduledSPS >= 0)
3767 {
3768 m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
3769 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
3770 CheckProxyRecords(m, m->ResourceRecords);
3771 }
3772
3773 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
3774
3775 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
3776 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0) m->AnnounceOwner = 0;
3777
3778 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
3779 {
3780 m->DelaySleep = 0;
3781 if (m->SleepState == SleepState_Transferring)
3782 {
3783 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
3784 BeginSleepProcessing(m);
3785 }
3786 }
3787
3788 // 4. See if we can answer any of our new local questions from the cache
3789 for (i=0; m->NewQuestions && i<1000; i++)
3790 {
3791 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
3792 AnswerNewQuestion(m);
3793 }
3794 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
3795
3796 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
3797 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
3798 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
3799 {
3800 m->LocalRemoveEvents = mDNSfalse;
3801 m->CurrentRecord = m->ResourceRecords;
3802 while (m->CurrentRecord)
3803 {
3804 AuthRecord *rr = m->CurrentRecord;
3805 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3806 {
3807 debugf("mDNS_Execute: Generating local RMV events for %s", ARDisplayString(m, rr));
3808 rr->resrec.RecordType = kDNSRecordTypeShared;
3809 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse);
3810 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
3811 {
3812 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
3813 rr->AnsweredLocalQ = mDNSfalse;
3814 }
3815 }
3816 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
3817 m->CurrentRecord = rr->next;
3818 }
3819 }
3820 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
3821
3822 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
3823 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
3824
3825 head = tail = mDNSNULL;
3826 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
3827 {
3828 AuthRecord *rr = m->NewLocalRecords;
3829 m->NewLocalRecords = m->NewLocalRecords->next;
3830 if (LocalRecordReady(rr))
3831 {
3832 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
3833 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNStrue);
3834 }
3835 else if (!rr->next)
3836 {
3837 // If we have just one record that is not ready, we don't have to unlink and
3838 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
3839 // terminate and set the NewLocalRecords to rr.
3840 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
3841 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
3842 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
3843
3844 head = rr;
3845 }
3846 else
3847 {
3848 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
3849 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
3850 // if this is the first record we are skipping, move to the end of the list.
3851 // if we have already skipped records before, append it at the end.
3852 while (*p && *p != rr) p=&(*p)->next;
3853 if (*p) *p = rr->next; // Cut this record from the list
3854 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
3855 if (!head)
3856 {
3857 while (*p) p=&(*p)->next;
3858 *p = rr;
3859 head = tail = rr;
3860 }
3861 else
3862 {
3863 tail->next = rr;
3864 tail = rr;
3865 }
3866 rr->next = mDNSNULL;
3867 }
3868 }
3869 m->NewLocalRecords = head;
3870 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
3871
3872 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
3873
3874 // 5. Some questions may have picked a new DNS server and the cache may answer these questions now.
3875 AnswerQuestionsForDNSServerChanges(m);
3876
3877 // 6. See what packets we need to send
3878 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
3879 DiscardDeregistrations(m);
3880 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
3881 {
3882 // If the platform code is ready, and we're not suppressing packet generation right now
3883 // then send our responses, probes, and questions.
3884 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
3885 // We send queries next, because there might be final-stage probes that complete their probing here, causing
3886 // them to advance to announcing state, and we want those to be included in any announcements we send out.
3887 // Finally, we send responses, including the previously mentioned records that just completed probing.
3888 m->SuppressSending = 0;
3889
3890 // 7. Send Query packets. This may cause some probing records to advance to announcing state
3891 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
3892 if (m->timenow - m->NextScheduledQuery >= 0)
3893 {
3894 DNSQuestion *q;
3895 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
3896 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
3897 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
3898 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3899 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
3900 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3901 }
3902 if (m->timenow - m->NextScheduledProbe >= 0)
3903 {
3904 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
3905 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
3906 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
3907 }
3908
3909 // 8. Send Response packets, including probing records just advanced to announcing state
3910 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
3911 if (m->timenow - m->NextScheduledResponse >= 0)
3912 {
3913 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
3914 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
3915 }
3916 }
3917
3918 // Clear RandomDelay values, ready to pick a new different value next time
3919 m->RandomQueryDelay = 0;
3920 m->RandomReconfirmDelay = 0;
3921
3922 #ifndef UNICAST_DISABLED
3923 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
3924 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
3925 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
3926 #endif
3927 }
3928
3929 // Note about multi-threaded systems:
3930 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
3931 // performing mDNS API operations that change our next scheduled event time.
3932 //
3933 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
3934 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
3935 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
3936 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
3937 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
3938 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
3939 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
3940 // without blocking. This avoids the race condition between the signal from the other thread arriving
3941 // just *before* or just *after* the main thread enters the blocking primitive.
3942 //
3943 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
3944 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
3945 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
3946 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
3947 // by the time it gets to the timer callback function).
3948
3949 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
3950 return(m->NextScheduledEvent);
3951 }
3952
3953 mDNSlocal void SuspendLLQs(mDNS *m)
3954 {
3955 DNSQuestion *q;
3956 for (q = m->Questions; q; q = q->next)
3957 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
3958 { q->ReqLease = 0; sendLLQRefresh(m, q); }
3959 }
3960
3961 // ActivateUnicastQuery() is called from three places:
3962 // 1. When a new question is created
3963 // 2. On wake from sleep
3964 // 3. When the DNS configuration changes
3965 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
3966 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
3967 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
3968 {
3969 // For now this AutoTunnel stuff is specific to Mac OS X.
3970 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
3971 #if APPLE_OSX_mDNSResponder
3972 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
3973 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
3974 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
3975 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
3976 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
3977 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
3978
3979 if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
3980 !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
3981 {
3982 question->NoAnswer = NoAnswer_Suspended;
3983 AddNewClientTunnel(m, question);
3984 return;
3985 }
3986 #endif // APPLE_OSX_mDNSResponder
3987
3988 if (!question->DuplicateOf)
3989 {
3990 debugf("ActivateUnicastQuery: %##s %s%s%s",
3991 question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
3992 question->CNAMEReferrals = 0;
3993 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
3994 if (question->LongLived)
3995 {
3996 question->state = LLQ_InitialRequest;
3997 question->id = zeroOpaque64;
3998 question->servPort = zeroIPPort;
3999 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
4000 }
4001 if (ScheduleImmediately)
4002 {
4003 question->ThisQInterval = InitialQuestionInterval;
4004 question->LastQTime = m->timenow - question->ThisQInterval;
4005 SetNextQueryTime(m, question);
4006 }
4007 }
4008 }
4009
4010 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
4011 {
4012 DNSQuestion *q;
4013
4014 #ifndef UNICAST_DISABLED
4015 // Retrigger all our uDNS questions
4016 if (m->CurrentQuestion)
4017 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
4018 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4019 m->CurrentQuestion = m->Questions;
4020 while (m->CurrentQuestion)
4021 {
4022 q = m->CurrentQuestion;
4023 m->CurrentQuestion = m->CurrentQuestion->next;
4024 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
4025 }
4026 #endif
4027
4028 // Retrigger all our mDNS questions
4029 for (q = m->Questions; q; q=q->next) // Scan our list of questions
4030 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
4031 {
4032 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
4033 q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
4034 q->LastQTime = m->timenow - q->ThisQInterval;
4035 q->RecentAnswerPkts = 0;
4036 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
4037 m->NextScheduledQuery = m->timenow;
4038 }
4039 }
4040
4041 // ***************************************************************************
4042 #if COMPILER_LIKES_PRAGMA_MARK
4043 #pragma mark -
4044 #pragma mark - Power Management (Sleep/Wake)
4045 #endif
4046
4047 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
4048 {
4049 #ifndef IDLESLEEPCONTROL_DISABLED
4050 mDNSBool allowSleep = mDNStrue;
4051
4052 if (m->SystemSleepOnlyIfWakeOnLAN)
4053 {
4054 // Don't sleep if we are a proxy for any services
4055 if (m->ProxyRecords)
4056 {
4057 allowSleep = mDNSfalse;
4058 LogInfo("Sleep disabled because we are proxying %d records", m->ProxyRecords);
4059 }
4060
4061 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
4062 {
4063 // Scan the list of active interfaces
4064 NetworkInterfaceInfo *intf;
4065 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4066 {
4067 if (intf->McastTxRx)
4068 {
4069 // Disallow sleep if this interface doesn't support NetWake
4070 if (!intf->NetWake)
4071 {
4072 allowSleep = mDNSfalse;
4073 LogInfo("Sleep disabled because %s does not support NetWake", intf->ifname);
4074 break;
4075 }
4076
4077 // Disallow sleep if there is no sleep proxy server
4078 if (FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL) == mDNSNULL)
4079 {
4080 allowSleep = mDNSfalse;
4081 LogInfo("Sleep disabled because %s has no sleep proxy", intf->ifname);
4082 break;
4083 }
4084 }
4085 }
4086 }
4087 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
4088 }
4089
4090 // Call the platform code to enable/disable sleep
4091 mDNSPlatformSetAllowSleep(m, allowSleep);
4092 }
4093
4094 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *intf, const mDNSOpaque16 id)
4095 {
4096 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
4097 const int sps = intf->NextSPSAttempt / 3;
4098 AuthRecord *rr;
4099
4100 if (!intf->SPSAddr[sps].type)
4101 {
4102 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
4103 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
4104 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
4105 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
4106 goto exit;
4107 }
4108
4109 // Mark our mDNS records (not unicast records) for transfer to SPS
4110 if (mDNSOpaque16IsZero(id))
4111 for (rr = m->ResourceRecords; rr; rr=rr->next)
4112 if (rr->resrec.RecordType > kDNSRecordTypeDeregistering)
4113 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
4114 rr->SendRNow = mDNSInterfaceMark; // mark it now
4115
4116 while (1)
4117 {
4118 mDNSu8 *p = m->omsg.data;
4119 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
4120 // For now we follow that same logic for SPS registrations too.
4121 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
4122 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
4123 InitializeDNSMessage(&m->omsg.h, mDNSOpaque16IsZero(id) ? mDNS_NewMessageID(m) : id, UpdateReqFlags);
4124
4125 for (rr = m->ResourceRecords; rr; rr=rr->next)
4126 if (rr->SendRNow || (!mDNSOpaque16IsZero(id) && !AuthRecord_uDNS(rr) && mDNSSameOpaque16(rr->updateid, id) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0))
4127 {
4128 mDNSu8 *newptr;
4129 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
4130 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
4131 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
4132 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
4133 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
4134 if (!newptr)
4135 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
4136 else
4137 {
4138 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, rr));
4139 rr->SendRNow = mDNSNULL;
4140 rr->ThisAPInterval = mDNSPlatformOneSecond;
4141 rr->LastAPTime = m->timenow;
4142 rr->updateid = m->omsg.h.id;
4143 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4144 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
4145 p = newptr;
4146 }
4147 }
4148
4149 if (!m->omsg.h.mDNS_numUpdates) break;
4150 else
4151 {
4152 AuthRecord opt;
4153 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
4154 opt.resrec.rrclass = NormalMaxDNSMessageData;
4155 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
4156 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
4157 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
4158 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
4159 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
4160 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]);
4161 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
4162 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4163 if (!p)
4164 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
4165 else
4166 {
4167 mStatus err;
4168 // Once we've attempted to register, we need to include our OWNER option in our packets when we re-awaken
4169 m->SentSleepProxyRegistration = mDNStrue;
4170
4171 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
4172 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
4173 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
4174 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL);
4175 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
4176 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv6 && intf->NetWakeResolve[sps].ThisQInterval == -1)
4177 {
4178 LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps, intf->NetWakeResolve[sps].qname.c);
4179 intf->NetWakeResolve[sps].qtype = kDNSType_A;
4180 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
4181 return;
4182 }
4183 }
4184 }
4185 }
4186
4187 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
4188
4189 exit:
4190 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
4191 }
4192
4193 // RetrySPSRegistrations is called from SendResponses, with the lock held
4194 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
4195 {
4196 AuthRecord *rr;
4197 NetworkInterfaceInfo *intf;
4198
4199 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
4200 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4201 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
4202 intf->NextSPSAttemptTime++;
4203
4204 // Retry any record registrations that are due
4205 for (rr = m->ResourceRecords; rr; rr=rr->next)
4206 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
4207 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4208 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)
4209 {
4210 LogSPS("RetrySPSRegistrations: %s", ARDisplayString(m, rr));
4211 SendSPSRegistration(m, intf, rr->updateid);
4212 }
4213
4214 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
4215 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4216 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
4217 intf->NextSPSAttempt++;
4218 }
4219
4220 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
4221 {
4222 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
4223 int sps = (int)(question - intf->NetWakeResolve);
4224 (void)m; // Unused
4225 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
4226
4227 if (!AddRecord) return; // Don't care about REMOVE events
4228 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
4229
4230 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
4231
4232 if (answer->rrtype == kDNSType_SRV)
4233 {
4234 // 1. Got the SRV record; now look up the target host's IPv6 link-local address
4235 mDNS_StopQuery(m, question);
4236 intf->SPSPort[sps] = answer->rdata->u.srv.port;
4237 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
4238 question->qtype = kDNSType_AAAA;
4239 mDNS_StartQuery(m, question);
4240 }
4241 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
4242 {
4243 // 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
4244 mDNS_StopQuery(m, question);
4245 question->ThisQInterval = -1;
4246 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
4247 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
4248 mDNS_Lock(m);
4249 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
4250 mDNS_Unlock(m);
4251 }
4252 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == 0)
4253 {
4254 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
4255 mDNS_StopQuery(m, question);
4256 LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps, question->qname.c);
4257 question->qtype = kDNSType_A;
4258 mDNS_StartQuery(m, question);
4259 }
4260 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
4261 {
4262 // 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
4263 mDNS_StopQuery(m, question);
4264 question->ThisQInterval = -1;
4265 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
4266 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
4267 mDNS_Lock(m);
4268 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
4269 mDNS_Unlock(m);
4270 }
4271 }
4272
4273 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
4274 {
4275 AuthRecord *rr;
4276 for (rr = m->ResourceRecords; rr; rr=rr->next)
4277 if (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort))
4278 return mDNStrue;
4279 return mDNSfalse;
4280 }
4281
4282 mDNSlocal void SendSleepGoodbyes(mDNS *const m)
4283 {
4284 AuthRecord *rr;
4285 m->SleepState = SleepState_Sleeping;
4286
4287 #ifndef UNICAST_DISABLED
4288 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
4289 #endif /* UNICAST_DISABLED */
4290
4291 // Mark all the records we need to deregister and send them
4292 for (rr = m->ResourceRecords; rr; rr=rr->next)
4293 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
4294 rr->ImmedAnswer = mDNSInterfaceMark;
4295 SendResponses(m);
4296 }
4297
4298 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
4299 mDNSlocal void BeginSleepProcessing(mDNS *const m)
4300 {
4301 mDNSBool SendGoodbyes = mDNStrue;
4302 const CacheRecord *sps[3] = { mDNSNULL };
4303
4304 m->NextScheduledSPRetry = m->timenow;
4305
4306 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
4307 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
4308 else // If we have at least one advertised service
4309 {
4310 NetworkInterfaceInfo *intf;
4311 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4312 {
4313 if (!intf->NetWake) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
4314 #if APPLE_OSX_mDNSResponder
4315 else if (ActivateLocalProxy(m, intf->ifname) == mStatus_NoError)
4316 {
4317 SendGoodbyes = mDNSfalse;
4318 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
4319 // This will leave m->SleepState set to SleepState_Transferring,
4320 // which is okay because with no outstanding resolves, or updates in flight,
4321 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
4322 }
4323 #endif // APPLE_OSX_mDNSResponder
4324 else
4325 {
4326 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
4327 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
4328 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
4329 else
4330 {
4331 int i;
4332 SendGoodbyes = mDNSfalse;
4333 intf->NextSPSAttempt = 0;
4334 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
4335 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
4336 for (i=0; i<3; i++)
4337 {
4338 #if ForceAlerts
4339 if (intf->SPSAddr[i].type)
4340 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
4341 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
4342 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
4343 #endif
4344 intf->SPSAddr[i].type = mDNSAddrType_None;
4345 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
4346 intf->NetWakeResolve[i].ThisQInterval = -1;
4347 if (sps[i])
4348 {
4349 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
4350 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
4351 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
4352 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
4353 }
4354 }
4355 }
4356 }
4357 }
4358 }
4359
4360 if (SendGoodbyes) // If we didn't find even one Sleep Proxy
4361 {
4362 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
4363 SendSleepGoodbyes(m);
4364 }
4365 }
4366
4367 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4368 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4369 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4370 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
4371 {
4372 AuthRecord *rr;
4373
4374 LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
4375
4376 if (sleep && !m->SleepState) // Going to sleep
4377 {
4378 mDNS_Lock(m);
4379 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
4380 if (m->SPSSocket)
4381 {
4382 mDNSu8 oldstate = m->SPSState;
4383 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
4384 m->SPSState = 2;
4385 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
4386 mDNS_ReclaimLockAfterCallback();
4387 }
4388
4389 m->SleepState = SleepState_Transferring;
4390 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
4391 {
4392 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
4393 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
4394 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
4395 }
4396 else
4397 {
4398 m->DelaySleep = 0;
4399 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
4400 BeginSleepProcessing(m);
4401 }
4402
4403 #ifndef UNICAST_DISABLED
4404 SuspendLLQs(m);
4405 #endif
4406 mDNS_Unlock(m);
4407 // RemoveAutoTunnel6Record needs to be called outside the lock, as it grabs the lock also.
4408 #if APPLE_OSX_mDNSResponder
4409 RemoveAutoTunnel6Record(m);
4410 #endif
4411 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
4412 m->SleepState == SleepState_Transferring ? "Transferring" :
4413 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
4414 }
4415 else if (!sleep) // Waking up
4416 {
4417 mDNSu32 slot;
4418 CacheGroup *cg;
4419 CacheRecord *cr;
4420 NetworkInterfaceInfo *intf;
4421
4422 mDNS_Lock(m);
4423 // Reset SleepLimit back to 0 now that we're awake again.
4424 m->SleepLimit = 0;
4425
4426 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
4427 if (m->SleepState != SleepState_Awake)
4428 {
4429 m->SleepState = SleepState_Awake;
4430 m->SleepSeqNum++;
4431 if (m->SentSleepProxyRegistration) // Include OWNER option in packets for 60 seconds after waking
4432 {
4433 m->SentSleepProxyRegistration = mDNSfalse;
4434 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
4435 }
4436 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
4437 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
4438 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
4439 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
4440 m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
4441 }
4442
4443 if (m->SPSState == 3)
4444 {
4445 m->SPSState = 0;
4446 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower);
4447 }
4448
4449 // In case we gave up waiting and went to sleep before we got an ack from the Sleep Proxy,
4450 // on wake we go through our record list and clear updateid back to zero
4451 for (rr = m->ResourceRecords; rr; rr=rr->next) rr->updateid = zeroID;
4452
4453 // ... and the same for NextSPSAttempt
4454 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
4455
4456 // Restart unicast and multicast queries
4457 mDNSCoreRestartQueries(m);
4458
4459 // and reactivtate service registrations
4460 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
4461 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
4462
4463 // 2. Re-validate our cache records
4464 FORALL_CACHERECORDS(slot, cg, cr)
4465 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
4466
4467 // 3. Retrigger probing and announcing for all our authoritative records
4468 for (rr = m->ResourceRecords; rr; rr=rr->next)
4469 if (AuthRecord_uDNS(rr))
4470 {
4471 ActivateUnicastRegistration(m, rr);
4472 }
4473 else
4474 {
4475 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
4476 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
4477 rr->AnnounceCount = InitialAnnounceCount;
4478 rr->SendNSECNow = mDNSNULL;
4479 InitializeLastAPTime(m, rr);
4480 }
4481
4482 // 4. Refresh NAT mappings
4483 // We don't want to have to assume that all hardware can necessarily keep accurate
4484 // track of passage of time while asleep, so on wake we refresh our NAT mappings
4485 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
4486 // When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
4487 // mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
4488 m->retryIntervalGetAddr = NATMAP_INIT_RETRY;
4489 m->retryGetAddr = m->timenow + mDNSPlatformOneSecond * 5;
4490 LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m->retryGetAddr - m->timenow, m->timenow);
4491 RecreateNATMappings(m);
4492 mDNS_Unlock(m);
4493 }
4494 }
4495
4496 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
4497 {
4498 DNSQuestion *q;
4499 AuthRecord *rr;
4500 NetworkInterfaceInfo *intf;
4501
4502 mDNS_Lock(m);
4503
4504 if (m->DelaySleep) goto notready;
4505
4506 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
4507 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
4508
4509 m->NextScheduledSPRetry = now + 0x40000000UL;
4510
4511 // See if we might need to retransmit any lost Sleep Proxy Registrations
4512 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4513 if (intf->NextSPSAttempt >= 0)
4514 {
4515 if (now - intf->NextSPSAttemptTime >= 0)
4516 {
4517 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
4518 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
4519 SendSPSRegistration(m, intf, zeroID);
4520 // Don't need to "goto notready" here, because if we do still have record registrations
4521 // that have not been acknowledged yet, we'll catch that in the record list scan below.
4522 }
4523 else
4524 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
4525 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
4526 }
4527
4528 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
4529 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4530 {
4531 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
4532 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
4533 {
4534 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
4535 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
4536 goto spsnotready;
4537 }
4538 }
4539
4540 // Scan list of registered records
4541 for (rr = m->ResourceRecords; rr; rr = rr->next)
4542 if (!AuthRecord_uDNS(rr))
4543 if (!mDNSOpaque16IsZero(rr->updateid))
4544 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; }
4545
4546 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
4547 for (q = m->Questions; q; q = q->next)
4548 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
4549 {
4550 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4551 goto notready;
4552 }
4553
4554 // Scan list of registered records
4555 for (rr = m->ResourceRecords; rr; rr = rr->next)
4556 if (AuthRecord_uDNS(rr))
4557 {
4558 if (rr->state == regState_Refresh && rr->tcp)
4559 { LogSPS("mDNSCoreReadyForSleep: waiting for Record Update ID %d %s", mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto notready; }
4560 #if APPLE_OSX_mDNSResponder
4561 if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
4562 #endif
4563 }
4564
4565 mDNS_Unlock(m);
4566 return mDNStrue;
4567
4568 spsnotready:
4569
4570 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
4571 // and allow up to ten seconds more to complete wide-area deregistration instead
4572 if (now - m->SleepLimit >= 0)
4573 {
4574 LogMsg("Failed to register with SPS, now sending goodbyes");
4575
4576 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
4577 if (intf->NetWakeBrowse.ThisQInterval >= 0)
4578 {
4579 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
4580 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
4581 mDNS_DeactivateNetWake_internal(m, intf);
4582 }
4583
4584 for (rr = m->ResourceRecords; rr; rr = rr->next)
4585 if (!AuthRecord_uDNS(rr))
4586 if (!mDNSOpaque16IsZero(rr->updateid))
4587 {
4588 LogSPS("ReadyForSleep clearing updateid for %s", ARDisplayString(m, rr));
4589 rr->updateid = zeroID;
4590 }
4591
4592 // We'd really like to allow up to ten seconds more here,
4593 // but if we don't respond to the sleep notification within 30 seconds
4594 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
4595 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
4596 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
4597 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
4598 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
4599
4600 SendSleepGoodbyes(m);
4601 }
4602
4603 notready:
4604 mDNS_Unlock(m);
4605 return mDNSfalse;
4606 }
4607
4608 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
4609 {
4610 AuthRecord *ar;
4611
4612 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
4613 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
4614 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
4615 // and if that happens we don't want to just give up and go back to sleep and never try again.
4616 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
4617
4618 NATTraversalInfo *nat;
4619 for (nat = m->NATTraversals; nat; nat=nat->next)
4620 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
4621 {
4622 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
4623 if (e - t > 0) e = t;
4624 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
4625 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
4626 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
4627 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
4628 nat->retryInterval / mDNSPlatformOneSecond,
4629 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
4630 (t - now) / mDNSPlatformOneSecond);
4631 }
4632
4633 // This loop checks both the time we need to renew wide-area registrations,
4634 // and the time we need to renew Sleep Proxy registrations
4635 for (ar = m->ResourceRecords; ar; ar = ar->next)
4636 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
4637 {
4638 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
4639 if (e - t > 0) e = t;
4640 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
4641 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
4642 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
4643 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
4644 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
4645 }
4646
4647 return(e - now);
4648 }
4649
4650 // ***************************************************************************
4651 #if COMPILER_LIKES_PRAGMA_MARK
4652 #pragma mark -
4653 #pragma mark - Packet Reception Functions
4654 #endif
4655
4656 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4657
4658 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
4659 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
4660 {
4661 mDNSu8 *responseptr = response->data;
4662 const mDNSu8 *const limit = response->data + sizeof(response->data);
4663 const mDNSu8 *ptr = query->data;
4664 AuthRecord *rr;
4665 mDNSu32 maxttl = 0x70000000;
4666 int i;
4667
4668 // Initialize the response fields so we can answer the questions
4669 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
4670
4671 // ***
4672 // *** 1. Write out the list of questions we are actually going to answer with this packet
4673 // ***
4674 if (LegacyQuery)
4675 {
4676 maxttl = kStaticCacheTTL;
4677 for (i=0; i<query->h.numQuestions; i++) // For each question...
4678 {
4679 DNSQuestion q;
4680 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
4681 if (!ptr) return(mDNSNULL);
4682
4683 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
4684 {
4685 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
4686 { // then put the question in the question section
4687 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
4688 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
4689 break; // break out of the ResponseRecords loop, and go on to the next question
4690 }
4691 }
4692 }
4693
4694 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
4695 }
4696
4697 // ***
4698 // *** 2. Write Answers
4699 // ***
4700 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
4701 if (rr->NR_AnswerTo)
4702 {
4703 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
4704 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
4705 if (p) responseptr = p;
4706 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
4707 }
4708
4709 // ***
4710 // *** 3. Write Additionals
4711 // ***
4712 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
4713 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
4714 {
4715 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
4716 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
4717 if (p) responseptr = p;
4718 else debugf("GenerateUnicastResponse: No more space for additionals");
4719 }
4720
4721 return(responseptr);
4722 }
4723
4724 // AuthRecord *our is our Resource Record
4725 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4726 // Returns 0 if there is no conflict
4727 // Returns +1 if there was a conflict and we won
4728 // Returns -1 if there was a conflict and we lost and have to rename
4729 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
4730 {
4731 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
4732 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
4733 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4734 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4735
4736 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
4737 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
4738 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
4739 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
4740
4741 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
4742 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
4743 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
4744 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
4745
4746 LogMsg("CompareRData ERROR: Invalid state");
4747 return(-1);
4748 }
4749
4750 // See if we have an authoritative record that's identical to this packet record,
4751 // whose canonical DependentOn record is the specified master record.
4752 // The DependentOn pointer is typically used for the TXT record of service registrations
4753 // It indicates that there is no inherent conflict detection for the TXT record
4754 // -- it depends on the SRV record to resolve name conflicts
4755 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4756 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4757 // If the record has no DependentOn, then just return that record's pointer
4758 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4759 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
4760 {
4761 const AuthRecord *r1;
4762 for (r1 = m->ResourceRecords; r1; r1=r1->next)
4763 {
4764 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
4765 {
4766 const AuthRecord *r2 = r1;
4767 while (r2->DependentOn) r2 = r2->DependentOn;
4768 if (r2 == master) return(mDNStrue);
4769 }
4770 }
4771 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
4772 {
4773 if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
4774 {
4775 const AuthRecord *r2 = r1;
4776 while (r2->DependentOn) r2 = r2->DependentOn;
4777 if (r2 == master) return(mDNStrue);
4778 }
4779 }
4780 return(mDNSfalse);
4781 }
4782
4783 // Find the canonical RRSet pointer for this RR received in a packet.
4784 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4785 // pointers (if any) to make sure we return the canonical member of this name/type/class
4786 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4787 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
4788 {
4789 const AuthRecord *rr;
4790 for (rr = m->ResourceRecords; rr; rr=rr->next)
4791 {
4792 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
4793 {
4794 while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
4795 return(rr);
4796 }
4797 }
4798 return(mDNSNULL);
4799 }
4800
4801 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4802 // as one of our records (our) but different rdata.
4803 // 1. If our record is not a type that's supposed to be unique, we don't care.
4804 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4805 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4806 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4807 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4808 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4809 // are members of the same RRSet, then this is not a conflict.
4810 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
4811 {
4812 // If not supposed to be unique, not a conflict
4813 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
4814
4815 // If a dependent record, not a conflict
4816 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
4817 else
4818 {
4819 // If the pktrr matches a member of ourset, not a conflict
4820 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
4821 const AuthRecord *pktset = FindRRSet(m, pktrr);
4822 if (pktset == ourset) return(mDNSfalse);
4823
4824 // For records we're proxying, where we don't know the full
4825 // relationship between the records, having any matching record
4826 // in our AuthRecords list is sufficient evidence of non-conflict
4827 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
4828 }
4829
4830 // Okay, this is a conflict
4831 return(mDNStrue);
4832 }
4833
4834 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4835 // the record list and/or question list.
4836 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4837 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
4838 DNSQuestion *q, AuthRecord *our)
4839 {
4840 int i;
4841 const mDNSu8 *ptr = LocateAuthorities(query, end);
4842 mDNSBool FoundUpdate = mDNSfalse;
4843
4844 for (i = 0; i < query->h.numAuthorities; i++)
4845 {
4846 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
4847 if (!ptr) break;
4848 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
4849 {
4850 FoundUpdate = mDNStrue;
4851 if (PacketRRConflict(m, our, &m->rec.r))
4852 {
4853 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
4854 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
4855 if (!result) result = CompareRData(our, &m->rec.r);
4856 if (result)
4857 {
4858 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
4859 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
4860 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
4861 }
4862 // 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.
4863 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
4864 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
4865 if (result < 0)
4866 {
4867 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
4868 our->ProbeCount = DefaultProbeCountForTypeUnique;
4869 our->AnnounceCount = InitialAnnounceCount;
4870 InitializeLastAPTime(m, our);
4871 goto exit;
4872 }
4873 }
4874 #if 0
4875 else
4876 {
4877 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
4878 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
4879 }
4880 #endif
4881 }
4882 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4883 }
4884 if (!FoundUpdate)
4885 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
4886 exit:
4887 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4888 }
4889
4890 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
4891 {
4892 mDNSu32 slot = HashSlot(pktrr->name);
4893 CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
4894 CacheRecord *rr;
4895 mDNSBool match;
4896 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4897 {
4898 match = !pktrr->InterfaceID ? pktrr->rDNSServer == rr->resrec.rDNSServer : pktrr->InterfaceID == rr->resrec.InterfaceID;
4899 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
4900 }
4901 return(rr);
4902 }
4903
4904 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
4905 // to check our lists and discard any stale duplicates of this record we already have
4906 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
4907 {
4908 if (m->CurrentRecord)
4909 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4910 m->CurrentRecord = thelist;
4911 while (m->CurrentRecord)
4912 {
4913 AuthRecord *const rr = m->CurrentRecord;
4914 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
4915 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
4916 {
4917 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
4918 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
4919 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
4920 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
4921 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4922 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
4923 }
4924 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4925 // new records could have been added to the end of the list as a result of that call.
4926 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4927 m->CurrentRecord = rr->next;
4928 }
4929 }
4930
4931 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
4932 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
4933 {
4934 if (m->CurrentRecord)
4935 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4936 m->CurrentRecord = thelist;
4937 while (m->CurrentRecord)
4938 {
4939 AuthRecord *const rr = m->CurrentRecord;
4940 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
4941 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
4942 {
4943 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
4944 {
4945 // We don't do this here because we know that the host is waking up at this point, so we don't send
4946 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
4947 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
4948 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
4949 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
4950 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
4951 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
4952 #endif
4953 }
4954 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
4955 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
4956 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
4957 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
4958 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
4959 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
4960 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4961 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
4962 }
4963 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4964 // new records could have been added to the end of the list as a result of that call.
4965 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
4966 m->CurrentRecord = rr->next;
4967 }
4968 }
4969
4970 // ProcessQuery examines a received query to see if we have any answers to give
4971 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
4972 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
4973 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
4974 {
4975 mDNSBool FromLocalSubnet = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
4976 AuthRecord *ResponseRecords = mDNSNULL;
4977 AuthRecord **nrp = &ResponseRecords;
4978 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
4979 CacheRecord **eap = &ExpectedAnswers;
4980 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
4981 DNSQuestion **dqp = &DupQuestions;
4982 mDNSs32 delayresponse = 0;
4983 mDNSBool SendLegacyResponse = mDNSfalse;
4984 const mDNSu8 *ptr;
4985 mDNSu8 *responseptr = mDNSNULL;
4986 AuthRecord *rr;
4987 int i;
4988
4989 // ***
4990 // *** 1. Look in Additional Section for an OPT record
4991 // ***
4992 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
4993 if (ptr)
4994 {
4995 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
4996 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
4997 {
4998 const rdataOPT *opt;
4999 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
5000 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5001 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5002 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
5003 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
5004 {
5005 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
5006 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
5007 }
5008 }
5009 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5010 }
5011
5012 // ***
5013 // *** 2. Parse Question Section and mark potential answers
5014 // ***
5015 ptr = query->data;
5016 for (i=0; i<query->h.numQuestions; i++) // For each question...
5017 {
5018 mDNSBool QuestionNeedsMulticastResponse;
5019 int NumAnswersForThisQuestion = 0;
5020 AuthRecord *NSECAnswer = mDNSNULL;
5021 DNSQuestion pktq, *q;
5022 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
5023 if (!ptr) goto exit;
5024
5025 // The only queries that *need* a multicast response are:
5026 // * Queries sent via multicast
5027 // * from port 5353
5028 // * that don't have the kDNSQClass_UnicastResponse bit set
5029 // These queries need multicast responses because other clients will:
5030 // * suppress their own identical questions when they see these questions, and
5031 // * expire their cache records if they don't see the expected responses
5032 // For other queries, we may still choose to send the occasional multicast response anyway,
5033 // to keep our neighbours caches warm, and for ongoing conflict detection.
5034 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
5035 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
5036 pktq.qclass &= ~kDNSQClass_UnicastResponse;
5037
5038 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
5039 // can result in user callbacks which may change the record list and/or question list.
5040 // Also note: we just mark potential answer records here, without trying to build the
5041 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
5042 // from that list while we're in the middle of trying to build it.
5043 if (m->CurrentRecord)
5044 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5045 m->CurrentRecord = m->ResourceRecords;
5046 while (m->CurrentRecord)
5047 {
5048 rr = m->CurrentRecord;
5049 m->CurrentRecord = rr->next;
5050 if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
5051 {
5052 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
5053 {
5054 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5055 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
5056 else if (ResourceRecordIsValidAnswer(rr))
5057 {
5058 NumAnswersForThisQuestion++;
5059 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
5060 // unicast answer back to the source, because timeliness in answering probes is important.
5061
5062 // Notes:
5063 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
5064 // NR_AnswerTo == (mDNSu8*)~1 means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
5065 // NR_AnswerTo == (mDNSu8*)~0 means "definitely answer via multicast" (can't downgrade to unicast later)
5066 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
5067 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
5068 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
5069 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
5070 {
5071 // We only mark this question for sending if it is at least one second since the last time we multicast it
5072 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
5073 // This is to guard against the case where someone blasts us with queries as fast as they can.
5074 if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
5075 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
5076 rr->NR_AnswerTo = (mDNSu8*)~0;
5077 }
5078 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : (mDNSu8*)~1;
5079 }
5080 }
5081 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
5082 {
5083 // If we don't have any answers for this question, but we do own another record with the same name,
5084 // then we'll want to mark it to generate an NSEC record on this interface
5085 if (!NSECAnswer) NSECAnswer = rr;
5086 }
5087 }
5088 }
5089
5090 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
5091 {
5092 NumAnswersForThisQuestion++;
5093 NSECAnswer->SendNSECNow = InterfaceID;
5094 m->NextScheduledResponse = m->timenow;
5095 }
5096
5097 // If we couldn't answer this question, someone else might be able to,
5098 // so use random delay on response to reduce collisions
5099 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
5100
5101 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5102 if (QuestionNeedsMulticastResponse)
5103 #else
5104 // We only do the following accelerated cache expiration and duplicate question suppression processing
5105 // for non-truncated multicast queries with multicast responses.
5106 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
5107 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
5108 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
5109 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
5110 #endif
5111 {
5112 const mDNSu32 slot = HashSlot(&pktq.qname);
5113 CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
5114 CacheRecord *cr;
5115
5116 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5117 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5118 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5119 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5120 #endif
5121 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5122 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
5123 if (!cr->NextInKAList && eap != &cr->NextInKAList)
5124 {
5125 *eap = cr;
5126 eap = &cr->NextInKAList;
5127 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5128 if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
5129 {
5130 // Although MPUnansweredQ is only really used for multi-packet query processing,
5131 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5132 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5133 cr->MPUnansweredQ++;
5134 cr->MPLastUnansweredQT = m->timenow;
5135 cr->MPExpectingKA = mDNStrue;
5136 }
5137 #endif
5138 }
5139
5140 // Check if this question is the same as any of mine.
5141 // We only do this for non-truncated queries. Right now it would be too complicated to try
5142 // to keep track of duplicate suppression state between multiple packets, especially when we
5143 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5144 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5145 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5146 #endif
5147 for (q = m->Questions; q; q=q->next)
5148 if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
5149 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
5150 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
5151 if (q->qtype == pktq.qtype &&
5152 q->qclass == pktq.qclass &&
5153 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
5154 { *dqp = q; dqp = &q->NextInDQList; }
5155 }
5156 }
5157
5158 // ***
5159 // *** 3. Now we can safely build the list of marked answers
5160 // ***
5161 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
5162 if (rr->NR_AnswerTo) // If we marked the record...
5163 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
5164
5165 // ***
5166 // *** 4. Add additional records
5167 // ***
5168 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
5169
5170 // ***
5171 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
5172 // ***
5173 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
5174 {
5175 // Get the record...
5176 CacheRecord *ourcacherr;
5177 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
5178 if (!ptr) goto exit;
5179 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
5180 {
5181 // See if this Known-Answer suppresses any of our currently planned answers
5182 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5183 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5184 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5185
5186 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5187 for (rr=m->ResourceRecords; rr; rr=rr->next)
5188 {
5189 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5190 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
5191 {
5192 if (srcaddr->type == mDNSAddrType_IPv4)
5193 {
5194 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
5195 }
5196 else if (srcaddr->type == mDNSAddrType_IPv6)
5197 {
5198 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
5199 }
5200 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
5201 {
5202 rr->ImmedAnswer = mDNSNULL;
5203 rr->ImmedUnicast = mDNSfalse;
5204 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5205 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
5206 #endif
5207 }
5208 }
5209 }
5210
5211 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
5212
5213 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5214 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5215 // even if the TC bit is not set (the TC bit will *not* be set in the *last* packet of a multi-packet KA list).
5216 if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
5217 {
5218 ourcacherr->MPUnansweredKA++;
5219 ourcacherr->MPExpectingKA = mDNSfalse;
5220 }
5221 #endif
5222
5223 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
5224 // any records that are suppressed by the Known Answer list in this packet.
5225 eap = &ExpectedAnswers;
5226 while (*eap)
5227 {
5228 CacheRecord *cr = *eap;
5229 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
5230 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
5231 else eap = &cr->NextInKAList;
5232 }
5233
5234 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5235 if (!ourcacherr)
5236 {
5237 dqp = &DupQuestions;
5238 while (*dqp)
5239 {
5240 DNSQuestion *q = *dqp;
5241 if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
5242 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
5243 else dqp = &q->NextInDQList;
5244 }
5245 }
5246 }
5247 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5248 }
5249
5250 // ***
5251 // *** 6. Cancel any additionals that were added because of now-deleted records
5252 // ***
5253 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5254 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
5255 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
5256
5257 // ***
5258 // *** 7. Mark the send flags on the records we plan to send
5259 // ***
5260 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
5261 {
5262 if (rr->NR_AnswerTo)
5263 {
5264 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
5265 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
5266
5267 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5268 if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
5269 {
5270 SendMulticastResponse = mDNStrue;
5271 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
5272 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
5273 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
5274 if (rr->NR_AnswerTo == (mDNSu8*)~1) rr->NR_AnswerTo = (mDNSu8*)~0;
5275 }
5276
5277 // If the client insists on a multicast response, then we'd better send one
5278 if (rr->NR_AnswerTo == (mDNSu8*)~0) SendMulticastResponse = mDNStrue;
5279 else if (rr->NR_AnswerTo == (mDNSu8*)~1) SendUnicastResponse = mDNStrue;
5280 else if (rr->NR_AnswerTo) SendLegacyResponse = mDNStrue;
5281
5282 if (SendMulticastResponse || SendUnicastResponse)
5283 {
5284 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5285 rr->ImmedAnswerMarkTime = m->timenow;
5286 #endif
5287 m->NextScheduledResponse = m->timenow;
5288 // If we're already planning to send this on another interface, just send it on all interfaces
5289 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
5290 rr->ImmedAnswer = mDNSInterfaceMark;
5291 else
5292 {
5293 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
5294 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
5295 if (srcaddr->type == mDNSAddrType_IPv4)
5296 {
5297 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
5298 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
5299 }
5300 else if (srcaddr->type == mDNSAddrType_IPv6)
5301 {
5302 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
5303 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
5304 }
5305 }
5306 }
5307 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
5308 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
5309 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
5310 // else, for a simple unique record reply, we can reply immediately; no need for delay
5311 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
5312 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
5313 }
5314 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == (mDNSu8*)~0)
5315 {
5316 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5317 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5318 // then the earlier client is out of luck
5319 rr->ImmedAdditional = InterfaceID;
5320 // No need to set m->NextScheduledResponse here
5321 // We'll send these additional records when we send them, or not, as the case may be
5322 }
5323 }
5324
5325 // ***
5326 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
5327 // ***
5328 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
5329 {
5330 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5331 mDNSs32 oldss = m->SuppressSending;
5332 if (oldss && delayresponse)
5333 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
5334 #endif
5335 // Pick a random delay:
5336 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
5337 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
5338 // This is an integer value, with resolution determined by the platform clock rate.
5339 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
5340 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
5341 // The +49 before dividing is to ensure we round up, not down, to ensure that even
5342 // on platforms where the native clock rate is less than fifty ticks per second,
5343 // we still guarantee that the final calculated delay is at least one platform tick.
5344 // We want to make sure we don't ever allow the delay to be zero ticks,
5345 // because if that happens we'll fail the Bonjour Conformance Test.
5346 // Our final computed delay is 20-120ms for normal delayed replies,
5347 // or 400-500ms in the case of multi-packet known-answer lists.
5348 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
5349 if (m->SuppressSending == 0) m->SuppressSending = 1;
5350 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5351 if (oldss && delayresponse)
5352 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
5353 #endif
5354 }
5355
5356 // ***
5357 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
5358 // ***
5359 if (SendLegacyResponse)
5360 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
5361
5362 exit:
5363 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5364
5365 // ***
5366 // *** 10. Finally, clear our link chains ready for use next time
5367 // ***
5368 while (ResponseRecords)
5369 {
5370 rr = ResponseRecords;
5371 ResponseRecords = rr->NextResponse;
5372 rr->NextResponse = mDNSNULL;
5373 rr->NR_AnswerTo = mDNSNULL;
5374 rr->NR_AdditionalTo = mDNSNULL;
5375 }
5376
5377 while (ExpectedAnswers)
5378 {
5379 CacheRecord *cr = ExpectedAnswers;
5380 ExpectedAnswers = cr->NextInKAList;
5381 cr->NextInKAList = mDNSNULL;
5382
5383 // For non-truncated queries, we can definitively say that we should expect
5384 // to be seeing a response for any records still left in the ExpectedAnswers list
5385 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
5386 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
5387 {
5388 cr->UnansweredQueries++;
5389 cr->LastUnansweredTime = m->timenow;
5390 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5391 if (cr->UnansweredQueries > 1)
5392 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5393 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
5394 #endif
5395 SetNextCacheCheckTimeForRecord(m, cr);
5396 }
5397
5398 // If we've seen multiple unanswered queries for this record,
5399 // then mark it to expire in five seconds if we don't get a response by then.
5400 if (cr->UnansweredQueries >= MaxUnansweredQueries)
5401 {
5402 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5403 // Only show debugging message if this record was not about to expire anyway
5404 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
5405 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5406 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
5407 #endif
5408 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
5409 }
5410 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5411 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5412 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5413 // possible packet loss of up to 20% of the additional KA packets.)
5414 else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
5415 {
5416 // We want to do this conservatively.
5417 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5418 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5419 // By setting the record to expire in four minutes, we achieve two things:
5420 // (a) the 90-95% final expiration queries will be less bunched together
5421 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5422 mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
5423 if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
5424 remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
5425
5426 // Only show debugging message if this record was not about to expire anyway
5427 if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
5428 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5429 cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
5430
5431 if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
5432 cr->UnansweredQueries++; // Treat this as equivalent to one definite unanswered query
5433 cr->MPUnansweredQ = 0; // Clear MPQ/MPKA statistics
5434 cr->MPUnansweredKA = 0;
5435 cr->MPExpectingKA = mDNSfalse;
5436
5437 if (remain < kDefaultReconfirmTimeForNoAnswer)
5438 remain = kDefaultReconfirmTimeForNoAnswer;
5439 mDNS_Reconfirm_internal(m, cr, remain);
5440 }
5441 #endif
5442 }
5443
5444 while (DupQuestions)
5445 {
5446 DNSQuestion *q = DupQuestions;
5447 DupQuestions = q->NextInDQList;
5448 q->NextInDQList = mDNSNULL;
5449 i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
5450 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
5451 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
5452 }
5453
5454 return(responseptr);
5455 }
5456
5457 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
5458 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
5459 const mDNSInterfaceID InterfaceID)
5460 {
5461 mDNSu8 *responseend = mDNSNULL;
5462 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
5463 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
5464
5465 if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
5466 {
5467 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
5468 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
5469 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
5470 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
5471 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
5472 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
5473 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
5474 return;
5475 }
5476
5477 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
5478 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
5479 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
5480 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
5481 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
5482 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
5483 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
5484
5485 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
5486 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
5487
5488 if (responseend) // If responseend is non-null, that means we built a unicast response packet
5489 {
5490 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5491 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
5492 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
5493 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
5494 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
5495 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL);
5496 }
5497 }
5498
5499 #if 0
5500 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
5501 {
5502 DNSServer *s;
5503 (void)m; // Unused
5504 (void)srcaddr; // Unused
5505 for (s = m->DNSServers; s; s = s->next)
5506 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
5507 return(mDNSfalse);
5508 }
5509 #endif
5510
5511 struct UDPSocket_struct
5512 {
5513 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
5514 };
5515
5516 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
5517 {
5518 DNSQuestion *q;
5519 for (q = m->Questions; q; q=q->next)
5520 {
5521 if (!tcp && !q->LocalSocket) continue;
5522 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
5523 mDNSSameOpaque16(q->TargetQID, id) &&
5524 q->qtype == question->qtype &&
5525 q->qclass == question->qclass &&
5526 q->qnamehash == question->qnamehash &&
5527 SameDomainName(&q->qname, &question->qname))
5528 return(q);
5529 }
5530 return(mDNSNULL);
5531 }
5532
5533 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
5534 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
5535 {
5536 DNSQuestion *q;
5537 (void)id;
5538 (void)srcaddr;
5539
5540 // Unicast records have zero as InterfaceID
5541 if (rr->resrec.InterfaceID) return mDNSNULL;
5542
5543 for (q = m->Questions; q; q=q->next)
5544 {
5545 if (!q->DuplicateOf && UnicastResourceRecordAnswersQuestion(&rr->resrec, q))
5546 {
5547 if (!mDNSOpaque16IsZero(q->TargetQID))
5548 {
5549 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
5550
5551 if (mDNSSameOpaque16(q->TargetQID, id))
5552 {
5553 mDNSIPPort srcp;
5554 if (!tcp)
5555 {
5556 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
5557 }
5558 else
5559 {
5560 srcp = q->tcpSrcPort;
5561 }
5562 if (mDNSSameIPPort(srcp, port)) return(q);
5563
5564 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
5565 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
5566 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
5567 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
5568 q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
5569 return(mDNSNULL);
5570 }
5571 }
5572 else
5573 {
5574 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
5575 return(q);
5576 }
5577 }
5578 }
5579 return(mDNSNULL);
5580 }
5581
5582 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
5583 // Currently this applies only to rdata types containing more than one domainname,
5584 // or types where the domainname is not the last item in the structure.
5585 // In addition, NSEC currently requires less space for in-memory storage than its in-packet representation.
5586 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
5587 {
5588 switch (rr->rrtype)
5589 {
5590 case kDNSType_SOA: return sizeof(rdataSOA);
5591 case kDNSType_RP: return sizeof(rdataRP);
5592 case kDNSType_PX: return sizeof(rdataPX);
5593 case kDNSType_NSEC:return sizeof(rdataNSEC);
5594 default: return rr->rdlength;
5595 }
5596 }
5597
5598 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay)
5599 {
5600 CacheRecord *rr = mDNSNULL;
5601 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
5602
5603 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
5604
5605 //if (RDLength > InlineCacheRDSize)
5606 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
5607
5608 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
5609 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
5610 if (!rr) NoCacheAnswer(m, &m->rec.r);
5611 else
5612 {
5613 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
5614 *rr = m->rec.r; // Block copy the CacheRecord object
5615 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
5616 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
5617 rr->DelayDelivery = delay;
5618
5619 // If this is an oversized record with external storage allocated, copy rdata to external storage
5620 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
5621 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
5622 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
5623 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
5624 if (RDLength > InlineCacheRDSize)
5625 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
5626
5627 rr->next = mDNSNULL; // Clear 'next' pointer
5628 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
5629 cg->rrcache_tail = &(rr->next); // Advance tail pointer
5630
5631 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
5632 }
5633 return(rr);
5634 }
5635
5636 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
5637 {
5638 rr->TimeRcvd = m->timenow;
5639 rr->resrec.rroriginalttl = ttl;
5640 rr->UnansweredQueries = 0;
5641 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5642 rr->MPUnansweredQ = 0;
5643 rr->MPUnansweredKA = 0;
5644 rr->MPExpectingKA = mDNSfalse;
5645 #endif
5646 SetNextCacheCheckTimeForRecord(m, rr);
5647 }
5648
5649 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
5650 {
5651 CacheRecord *rr;
5652 const mDNSu32 slot = HashSlot(&q->qname);
5653 CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
5654 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
5655 if (rr->CRActiveQuestion == q)
5656 {
5657 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
5658 RefreshCacheRecord(m, rr, lease);
5659 }
5660 }
5661
5662 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
5663 {
5664 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
5665 else if (LLQType == uDNS_LLQ_Events)
5666 {
5667 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
5668 if (ttl == 0xFFFFFFFF) ttl = 0;
5669 else ttl = kLLQ_DefLease;
5670 }
5671 else // else not LLQ (standard uDNS response)
5672 {
5673 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
5674 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
5675 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
5676
5677 // Adjustment factor to avoid race condition:
5678 // Suppose real record as TTL of 3600, and our local caching server has held it for 3500 seconds, so it returns an aged TTL of 100.
5679 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
5680 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
5681 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
5682 // We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
5683 // the cached copy at our local caching server will already have expired, so the server will be forced
5684 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
5685 ttl += ttl/4 + 2;
5686
5687 // For mDNS, TTL zero means "delete this record"
5688 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
5689 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
5690 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
5691 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
5692 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
5693 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
5694 // (with the current code) result in the server having even less than three seconds to respond
5695 // before we deleted the record and reported a "remove" event to any active questions.
5696 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
5697 // then things really break (e.g. we end up making a negative cache entry).
5698 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
5699 if (ttl < 15) ttl = 15;
5700 }
5701
5702 return ttl;
5703 }
5704
5705 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5706 // the record list and/or question list.
5707 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5708 // InterfaceID non-NULL tells us the interface this multicast response was received on
5709 // InterfaceID NULL tells us this was a unicast response
5710 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
5711 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
5712 const DNSMessage *const response, const mDNSu8 *end,
5713 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
5714 const mDNSInterfaceID InterfaceID)
5715 {
5716 int i;
5717 mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
5718 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
5719 DNSQuestion *llqMatch = mDNSNULL;
5720 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
5721
5722 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
5723 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
5724 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
5725 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
5726 CacheRecord **cfp = &CacheFlushRecords;
5727
5728 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5729 // to guard against spoof responses, then the only credible protection against that is cryptographic
5730 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5731 int firstauthority = response->h.numAnswers;
5732 int firstadditional = firstauthority + response->h.numAuthorities;
5733 int totalrecords = firstadditional + response->h.numAdditionals;
5734 const mDNSu8 *ptr = response->data;
5735 DNSServer *uDNSServer = mDNSNULL;
5736
5737 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
5738 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
5739 srcaddr, dstaddr, InterfaceID,
5740 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
5741 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
5742 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
5743 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
5744
5745 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
5746 // When a DNS client receives a reply with TC
5747 // set, it should ignore that response, and query again, using a
5748 // mechanism, such as a TCP connection, that will permit larger replies.
5749 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
5750 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
5751 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
5752 // <rdar://problem/6690034> Can't bind to Active Directory
5753 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
5754 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
5755 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
5756 // and not even do the TCP query.
5757 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
5758 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
5759
5760 if (LLQType == uDNS_LLQ_Ignore) return;
5761
5762 // 1. We ignore questions (if any) in mDNS response packets
5763 // 2. If this is an LLQ response, we handle it much the same
5764 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
5765 // answer as being the authoritative complete RRSet, and respond by deleting all other
5766 // matching cache records that don't appear in this packet.
5767 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
5768 if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
5769 ptr = LocateAnswers(response, end);
5770 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
5771 // in this response packet are immediately deemed to be invalid.
5772 else
5773 {
5774 mDNSu8 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
5775 mDNSBool failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
5776 mDNSBool returnEarly = mDNSfalse;
5777 // We could possibly combine this with the similar loop at the end of this function --
5778 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
5779 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
5780 // which it was received (or refreshed), and then at the end if we find any cache records which
5781 // answer questions in this packet's question section, but which aren't tagged with this packet's
5782 // packet number, then we deduce they are old and delete them
5783 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
5784 {
5785 DNSQuestion q, *qptr = mDNSNULL;
5786 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
5787 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
5788 {
5789 if (!failure)
5790 {
5791 CacheRecord *rr;
5792 const mDNSu32 slot = HashSlot(&q.qname);
5793 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
5794 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
5795 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
5796 {
5797 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
5798 rr->resrec.InterfaceID, CRDisplayString(m, rr));
5799 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
5800 rr->TimeRcvd = m->timenow - TicksTTL(rr) - 1;
5801 rr->UnansweredQueries = MaxUnansweredQueries;
5802 }
5803 }
5804 else
5805 {
5806 if (qptr)
5807 {
5808 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
5809 PenalizeDNSServer(m, qptr);
5810 }
5811 returnEarly = mDNStrue;
5812 }
5813 }
5814 }
5815 if (returnEarly)
5816 {
5817 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
5818 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
5819 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
5820 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
5821 // not goto exit because we won't have any CacheFlushRecords and we do not want to
5822 // generate negative cache entries (we want to query the next server)
5823 return;
5824 }
5825 }
5826
5827 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
5828 {
5829 // All responses sent via LL multicast are acceptable for caching
5830 // All responses received over our outbound TCP connections are acceptable for caching
5831 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
5832 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
5833 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
5834
5835 const mDNSu8 RecordType =
5836 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
5837 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
5838 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
5839 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5840 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) { m->rec.r.resrec.RecordType = 0; continue; }
5841
5842 // Don't want to cache OPT or TSIG pseudo-RRs
5843 if (m->rec.r.resrec.rrtype == kDNSType_TSIG) { m->rec.r.resrec.RecordType = 0; continue; }
5844 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
5845 {
5846 const rdataOPT *opt;
5847 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
5848 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5849 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5850 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
5851 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
5852 {
5853 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
5854 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
5855 }
5856 m->rec.r.resrec.RecordType = 0;
5857 continue;
5858 }
5859
5860 // if a CNAME record points to itself, then don't add it to the cache
5861 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
5862 {
5863 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
5864 m->rec.r.resrec.RecordType = 0;
5865 continue;
5866 }
5867
5868 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
5869 // In the case of active LLQs, we'll get remove events when the records actually do go away
5870 // In the case of polling LLQs, we assume the record remains valid until the next poll
5871 if (!mDNSOpaque16IsZero(response->h.id))
5872 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
5873
5874 // If response was not sent via LL multicast,
5875 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
5876 if (!ResponseMCast)
5877 {
5878 if (LLQType)
5879 {
5880 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
5881 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
5882 // queries to get ADD/RMV events. To lookup the question, we can't use
5883 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
5884 // has already matched the question using the 64 bit Id in the packet and we use that here.
5885
5886 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
5887 }
5888 else if (!AcceptableResponse || !dstaddr)
5889 {
5890 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
5891 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
5892 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
5893 // we create.
5894
5895 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
5896
5897 // Intialize the DNS server on the resource record which will now filter what questions we answer with
5898 // this record.
5899 //
5900 // We could potentially lookup the DNS server based on the source address, but that may not work always
5901 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
5902 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
5903 // on the "id" and "source port", then this response answers the question and assume the response
5904 // came from the same DNS server that we sent the query to.
5905
5906 if (q != mDNSNULL)
5907 {
5908 AcceptableResponse = mDNStrue;
5909 if (!InterfaceID)
5910 {
5911 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
5912 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
5913 }
5914 }
5915 else
5916 {
5917 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
5918 // the question. The code below does that. So, make this record unacceptable for now
5919 if (!InterfaceID)
5920 {
5921 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
5922 AcceptableResponse = mDNSfalse;
5923 }
5924 }
5925 }
5926 }
5927
5928 // 1. Check that this packet resource record does not conflict with any of ours
5929 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
5930 {
5931 if (m->CurrentRecord)
5932 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5933 m->CurrentRecord = m->ResourceRecords;
5934 while (m->CurrentRecord)
5935 {
5936 AuthRecord *rr = m->CurrentRecord;
5937 m->CurrentRecord = rr->next;
5938 // We accept all multicast responses, and unicast responses resulting from queries we issued
5939 // For other unicast responses, this code accepts them only for responses with an
5940 // (apparently) local source address that pertain to a record of our own that's in probing state
5941 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
5942
5943 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
5944 {
5945 // ... check to see if type and rdata are identical
5946 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
5947 {
5948 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5949 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
5950 {
5951 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5952 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
5953 }
5954 else
5955 {
5956 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
5957 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
5958 }
5959 }
5960 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
5961 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
5962 {
5963 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
5964 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr-> resrec.rdatahash, ARDisplayString(m, rr));
5965
5966 // If this record is marked DependentOn another record for conflict detection purposes,
5967 // then *that* record has to be bumped back to probing state to resolve the conflict
5968 if (rr->DependentOn)
5969 {
5970 while (rr->DependentOn) rr = rr->DependentOn;
5971 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr-> resrec.rdatahash, ARDisplayString(m, rr));
5972 }
5973
5974 // If we've just whacked this record's ProbeCount, don't need to do it again
5975 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
5976 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
5977 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
5978 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
5979 else
5980 {
5981 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
5982 // If we'd previously verified this record, put it back to probing state and try again
5983 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
5984 {
5985 LogMsg("mDNSCoreReceiveResponse: Reseting to Probing: %s", ARDisplayString(m, rr));
5986 rr->resrec.RecordType = kDNSRecordTypeUnique;
5987 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
5988 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
5989 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
5990 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
5991 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
5992 rr->AnnounceCount = InitialAnnounceCount;
5993 InitializeLastAPTime(m, rr);
5994 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
5995 }
5996 // If we're probing for this record, we just failed
5997 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
5998 {
5999 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will rename %s", rr->ProbeCount, ARDisplayString(m, rr));
6000 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6001 }
6002 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
6003 // same machine giving different answers for the reverse mapping record, or there are two machines on the
6004 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
6005 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
6006 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
6007 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
6008 {
6009 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
6010 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
6011 }
6012 else
6013 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
6014 }
6015 }
6016 // Else, matching signature, different type or rdata, but not a considered a conflict.
6017 // If the packet record has the cache-flush bit set, then we check to see if we
6018 // have any record(s) of the same type that we should re-assert to rescue them
6019 // (see note about "multi-homing and bridged networks" at the end of this function).
6020 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
6021 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
6022 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
6023 }
6024 }
6025 }
6026
6027 if (!AcceptableResponse)
6028 {
6029 const CacheRecord *cr;
6030 for (cr = CacheFlushRecords; cr != (CacheRecord*)1; cr = cr->NextInCFList)
6031 {
6032 domainname *target = GetRRDomainNameTarget(&cr->resrec);
6033 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
6034 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
6035 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
6036 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
6037 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
6038
6039 if (target && cr->resrec.rdatahash == m->rec.r.resrec.namehash && SameDomainName(target, m->rec.r.resrec.name))
6040 {
6041 debugf("mDNSCoreReceiveResponse: Found a matching entry for %##s in the CacheFlushRecords", m->rec.r.resrec.name->c);
6042 AcceptableResponse = mDNStrue;
6043 m->rec.r.resrec.rDNSServer = uDNSServer;
6044 break;
6045 }
6046 }
6047 }
6048
6049 // 2. See if we want to add this packet resource record to our cache
6050 // We only try to cache answers if we have a cache to put them in
6051 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
6052 if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
6053 if (m->rrcache_size && AcceptableResponse)
6054 {
6055 const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
6056 CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
6057 CacheRecord *rr;
6058
6059 // 2a. Check if this packet resource record is already in our cache
6060 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6061 {
6062 mDNSBool match = !InterfaceID ? m->rec.r.resrec.rDNSServer == rr->resrec.rDNSServer : rr->resrec.InterfaceID == InterfaceID;
6063 // If we found this exact resource record, refresh its TTL
6064 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
6065 {
6066 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
6067 verbosedebugf("Found record size %5d interface %p already in cache: %s",
6068 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
6069
6070 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6071 {
6072 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
6073 if (rr->NextInCFList == mDNSNULL && cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
6074 { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6075
6076 // If this packet record is marked unique, and our previous cached copy was not, then fix it
6077 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
6078 {
6079 DNSQuestion *q;
6080 for (q = m->Questions; q; q=q->next) if (ResourceRecordAnswersQuestion(&rr->resrec, q)) q->UniqueAnswers++;
6081 rr->resrec.RecordType = m->rec.r.resrec.RecordType;
6082 }
6083 }
6084
6085 if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
6086 {
6087 // If the rdata of the packet record differs in name capitalization from the record in our cache
6088 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
6089 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
6090 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
6091 rr->resrec.rroriginalttl = 0;
6092 rr->TimeRcvd = m->timenow;
6093 rr->UnansweredQueries = MaxUnansweredQueries;
6094 SetNextCacheCheckTimeForRecord(m, rr);
6095 LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m,rr));
6096 LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m,&m->rec.r));
6097 LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
6098 NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
6099 // DO NOT break out here -- we want to continue as if we never found it
6100 }
6101 else if (m->rec.r.resrec.rroriginalttl > 0)
6102 {
6103 DNSQuestion *q;
6104 //if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
6105 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
6106
6107 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
6108 // polling the network once we get a valid response back. For the first time when a new
6109 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
6110 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
6111 // configuration changed, without flushing the cache, we reset the question interval here.
6112 // Currently, we do this for for both multicast and unicast questions as long as the record
6113 // type is unique. For unicast, resource record is always unique and for multicast it is
6114 // true for records like A etc. but not for PTR.
6115 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
6116 {
6117 for (q = m->Questions; q; q=q->next)
6118 {
6119 if (!q->DuplicateOf && !q->LongLived &&
6120 ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
6121 {
6122 q->LastQTime = m->timenow;
6123 q->LastQTxTime = m->timenow;
6124 q->RecentAnswerPkts = 0;
6125 q->ThisQInterval = MaxQuestionInterval;
6126 q->RequestUnicast = mDNSfalse;
6127 q->unansweredQueries = 0;
6128 debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
6129 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
6130 }
6131 }
6132 }
6133 break;
6134 }
6135 else
6136 {
6137 // If the packet TTL is zero, that means we're deleting this record.
6138 // To give other hosts on the network a chance to protest, we push the deletion
6139 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
6140 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
6141 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
6142 // If record's current expiry time is more than a second from now, we set it to expire in one second.
6143 // If the record is already going to expire in less than one second anyway, we leave it alone --
6144 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
6145 debugf("DE for %s", CRDisplayString(m, rr));
6146 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
6147 {
6148 rr->resrec.rroriginalttl = 1;
6149 rr->TimeRcvd = m->timenow;
6150 rr->UnansweredQueries = MaxUnansweredQueries;
6151 SetNextCacheCheckTimeForRecord(m, rr);
6152 }
6153 break;
6154 }
6155 }
6156 }
6157
6158 // If packet resource record not in our cache, add it now
6159 // (unless it is just a deletion of a record we never had, in which case we don't care)
6160 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
6161 {
6162 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
6163 const mDNSs32 delay = AddToCFList ? NonZeroTime(m->timenow + mDNSPlatformOneSecond) :
6164 CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot);
6165 // If unique, assume we may have to delay delivery of this 'add' event.
6166 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
6167 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
6168 // to schedule an mDNS_Execute task at the appropriate time.
6169 rr = CreateNewCacheEntry(m, slot, cg, delay);
6170 if (rr)
6171 {
6172 if (AddToCFList) { *cfp = rr; cfp = &rr->NextInCFList; *cfp = (CacheRecord*)1; }
6173 else if (rr->DelayDelivery) ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
6174 }
6175 }
6176 }
6177 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6178 }
6179
6180 exit:
6181 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6182
6183 // If we've just received one or more records with their cache flush bits set,
6184 // then scan that cache slot to see if there are any old stale records we need to flush
6185 while (CacheFlushRecords != (CacheRecord*)1)
6186 {
6187 CacheRecord *r1 = CacheFlushRecords, *r2;
6188 const mDNSu32 slot = HashSlot(r1->resrec.name);
6189 const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
6190 CacheFlushRecords = CacheFlushRecords->NextInCFList;
6191 r1->NextInCFList = mDNSNULL;
6192
6193 // Look for records in the cache with the same signature as this new one with the cache flush
6194 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
6195 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
6196 // We make these TTL adjustments *only* for records that still have *more* than one second
6197 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
6198 // (and now has half a second remaining) could inadvertently get its life extended, by either
6199 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
6200 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
6201 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
6202 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
6203 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
6204 // To avoid this, we need to ensure that the cache flushing operation will only act to
6205 // *decrease* a record's remaining lifetime, never *increase* it.
6206 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
6207 // For Unicast (null InterfaceID) the DNSservers should also match
6208 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
6209 (r1->resrec.InterfaceID || (r1->resrec.rDNSServer == r2->resrec.rDNSServer)) &&
6210 r1->resrec.rrtype == r2->resrec.rrtype &&
6211 r1->resrec.rrclass == r2->resrec.rrclass)
6212 {
6213 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
6214 // else, if record is old, mark it to be flushed
6215 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
6216 {
6217 // If we find mismatched TTLs in an RRSet, correct them.
6218 // We only do this for records with a TTL of 2 or higher. It's possible to have a
6219 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
6220 // which we treat as a goodbye followed by an addition) and in that case it would be
6221 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
6222 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
6223 // because certain early Bonjour devices are known to have this specific mismatch, and
6224 // there's no point filling syslog with messages about something we already know about.
6225 // We also don't log this for uDNS responses, since a caching name server is obliged
6226 // to give us an aged TTL to correct for how long it has held the record,
6227 // so our received TTLs are expected to vary in that case
6228 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
6229 {
6230 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
6231 mDNSOpaque16IsZero(response->h.id))
6232 LogInfo("Correcting TTL from %4d to %4d for %s",
6233 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
6234 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
6235 }
6236 r2->TimeRcvd = m->timenow;
6237 }
6238 else // else, if record is old, mark it to be flushed
6239 {
6240 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
6241 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
6242 // We set stale records to expire in one second.
6243 // This gives the owner a chance to rescue it if necessary.
6244 // This is important in the case of multi-homing and bridged networks:
6245 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
6246 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
6247 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
6248 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
6249 // By delaying the deletion by one second, we give X a change to notice that this bridging has
6250 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
6251
6252 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
6253 // final expiration queries for this record.
6254
6255 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
6256 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
6257 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
6258 // <rdar://problem/5636422> Updating TXT records is too slow
6259 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
6260 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
6261 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
6262 {
6263 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
6264 r2->resrec.rroriginalttl = 0;
6265 }
6266 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
6267 {
6268 // We only set a record to expire in one second if it currently has *more* than a second to live
6269 // If it's already due to expire in a second or less, we just leave it alone
6270 r2->resrec.rroriginalttl = 1;
6271 r2->UnansweredQueries = MaxUnansweredQueries;
6272 r2->TimeRcvd = m->timenow - 1;
6273 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
6274 // that we marked for deletion via an explicit DE record
6275 }
6276 }
6277 SetNextCacheCheckTimeForRecord(m, r2);
6278 }
6279
6280 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
6281 {
6282 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot);
6283 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
6284 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
6285 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
6286 }
6287 }
6288
6289 // See if we need to generate negative cache entries for unanswered unicast questions
6290 ptr = response->data;
6291 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
6292 {
6293 DNSQuestion q;
6294 DNSQuestion *qptr = mDNSNULL;
6295 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
6296 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
6297 {
6298 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
6299 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
6300 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
6301 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
6302 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
6303 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
6304 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
6305 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
6306 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
6307 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
6308 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
6309 LogInfo("Skipping check to see if we need to generate a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
6310 else
6311 {
6312 CacheRecord *rr, *neg = mDNSNULL;
6313 mDNSu32 slot = HashSlot(&q.qname);
6314 CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
6315 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
6316 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
6317 {
6318 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
6319 if (RRExpireTime(rr) - m->timenow > 0) break;
6320 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
6321 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
6322 }
6323
6324 if (!rr)
6325 {
6326 // We start off assuming a negative caching TTL of 60 seconds
6327 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
6328 mDNSu32 negttl = 60;
6329 int repeat = 0;
6330 const domainname *name = &q.qname;
6331 mDNSu32 hash = q.qnamehash;
6332
6333 // Special case for our special Microsoft Active Directory "local SOA" check.
6334 // Some cheap home gateways don't include an SOA record in the authority section when
6335 // they send negative responses, so we don't know how long to cache the negative result.
6336 // Because we don't want to keep hitting the root name servers with our query to find
6337 // if we're on a network using Microsoft Active Directory using "local" as a private
6338 // internal top-level domain, we make sure to cache the negative result for at least one day.
6339 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
6340
6341 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
6342 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
6343 {
6344 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
6345 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
6346 {
6347 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
6348 mDNSu32 ttl_s = soa->min;
6349 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
6350 // for the SOA record for ".", where the record is reported as non-cacheable
6351 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
6352 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
6353 ttl_s = m->rec.r.resrec.rroriginalttl;
6354 if (negttl < ttl_s) negttl = ttl_s;
6355
6356 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
6357 // with an Authority Section SOA record for d.com, then this is a hint that the authority
6358 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
6359 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
6360 if (q.qtype == kDNSType_SOA)
6361 {
6362 int qcount = CountLabels(&q.qname);
6363 int scount = CountLabels(m->rec.r.resrec.name);
6364 if (qcount - 1 > scount)
6365 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
6366 repeat = qcount - 1 - scount;
6367 }
6368 }
6369 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6370 }
6371
6372 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
6373 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
6374 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
6375 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
6376 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
6377 // so that we back off our polling rate and don't keep hitting the server continually.
6378 if (neg)
6379 {
6380 if (negttl < neg->resrec.rroriginalttl * 2)
6381 negttl = neg->resrec.rroriginalttl * 2;
6382 if (negttl > 3600)
6383 negttl = 3600;
6384 }
6385
6386 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
6387
6388 // If we already had a negative cache entry just update it, else make one or more new negative cache entries
6389 if (neg)
6390 {
6391 debugf("Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
6392 RefreshCacheRecord(m, neg, negttl);
6393 }
6394 else while (1)
6395 {
6396 debugf("mDNSCoreReceiveResponse making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
6397 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
6398 CreateNewCacheEntry(m, slot, cg, 0); // We never need any delivery delay for these generated negative cache records
6399 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6400 if (!repeat) break;
6401 repeat--;
6402 name = (const domainname *)(name->c + 1 + name->c[0]);
6403 hash = DomainNameHashValue(name);
6404 slot = HashSlot(name);
6405 cg = CacheGroupForName(m, slot, hash, name);
6406 }
6407 }
6408 }
6409 }
6410 }
6411 }
6412
6413 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
6414 {
6415 AuthRecord *rr;
6416 for (rr = thelist; rr; rr=rr->next)
6417 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
6418 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
6419 }
6420
6421 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
6422 {
6423 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
6424 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
6425 }
6426
6427 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
6428 {
6429 if (result && result != mStatus_MemFree)
6430 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
6431
6432 if (result == mStatus_NameConflict)
6433 {
6434 LogMsg("Received Conflicting mDNS -- waking %s %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
6435 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password);
6436 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC);
6437 }
6438 else if (result == mStatus_MemFree)
6439 {
6440 m->ProxyRecords--;
6441 mDNSPlatformMemFree(ar);
6442 mDNS_UpdateAllowSleep(m);
6443 }
6444 }
6445
6446 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
6447 const DNSMessage *const msg, const mDNSu8 *end,
6448 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
6449 const mDNSInterfaceID InterfaceID)
6450 {
6451 int i;
6452 AuthRecord opt;
6453 mDNSu8 *p = m->omsg.data;
6454 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
6455 mDNSu32 updatelease = 0;
6456 const mDNSu8 *ptr;
6457
6458 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6459 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6460 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
6461 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
6462 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
6463 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
6464 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
6465
6466 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
6467
6468 if (mDNS_PacketLoggingEnabled)
6469 DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
6470
6471 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
6472 if (ptr)
6473 {
6474 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
6475 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
6476 {
6477 const rdataOPT *o;
6478 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
6479 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
6480 {
6481 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
6482 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
6483 }
6484 }
6485 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6486 }
6487
6488 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
6489
6490 if (!updatelease || !owner.HMAC.l[0])
6491 {
6492 static int msgs = 0;
6493 if (msgs < 100)
6494 {
6495 msgs++;
6496 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
6497 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
6498 }
6499 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
6500 }
6501 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
6502 {
6503 static int msgs = 0;
6504 if (msgs < 100)
6505 {
6506 msgs++;
6507 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
6508 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
6509 }
6510 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
6511 }
6512 else
6513 {
6514 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
6515
6516 if (updatelease > 24 * 60 * 60)
6517 updatelease = 24 * 60 * 60;
6518
6519 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
6520 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
6521
6522 ptr = LocateAuthorities(msg, end);
6523 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
6524 {
6525 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
6526 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
6527 {
6528 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
6529 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
6530 if (!ar) { m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; break; }
6531 else
6532 {
6533 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
6534 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
6535 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
6536 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
6537 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, SPSRecordCallback, ar);
6538 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
6539 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
6540 ar->resrec.rdata->MaxRDLength = RDLengthMem;
6541 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
6542 ar->ForceMCast = mDNStrue;
6543 ar->WakeUp = owner;
6544 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
6545 {
6546 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
6547 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
6548 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
6549 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
6550 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
6551 }
6552 ar->TimeRcvd = m->timenow;
6553 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
6554 if (m->NextScheduledSPS - ar->TimeExpire > 0)
6555 m->NextScheduledSPS = ar->TimeExpire;
6556 mDNS_Register_internal(m, ar);
6557 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
6558 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
6559 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
6560 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
6561 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
6562 if (m->KnownBugs & mDNS_KnownBug_LimitedIPv6)
6563 if (ar->resrec.rrtype == kDNSType_AAAA) ar->resrec.rroriginalttl = 0;
6564 m->ProxyRecords++;
6565 mDNS_UpdateAllowSleep(m);
6566 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
6567 }
6568 }
6569 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6570 }
6571
6572 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
6573 {
6574 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
6575 ClearProxyRecords(m, &owner, m->DuplicateRecords);
6576 ClearProxyRecords(m, &owner, m->ResourceRecords);
6577 }
6578 else
6579 {
6580 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
6581 opt.resrec.rrclass = NormalMaxDNSMessageData;
6582 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
6583 opt.resrec.rdestimate = sizeof(rdataOPT);
6584 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
6585 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
6586 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6587 }
6588 }
6589
6590 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL);
6591 }
6592
6593 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSInterfaceID InterfaceID)
6594 {
6595 if (InterfaceID)
6596 {
6597 AuthRecord *rr;
6598 mDNSu32 updatelease = 60 * 60; // If SPS fails to indicate lease time, assume one hour
6599 const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
6600 if (ptr)
6601 {
6602 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
6603 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
6604 {
6605 const rdataOPT *o;
6606 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
6607 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
6608 if (o->opt == kDNSOpt_Lease)
6609 {
6610 updatelease = o->u.updatelease;
6611 LogSPS("Sleep Proxy granted lease time %4d seconds", updatelease);
6612 }
6613 }
6614 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
6615 }
6616
6617 for (rr = m->ResourceRecords; rr; rr=rr->next)
6618 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6619 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
6620 {
6621 rr->updateid = zeroID;
6622 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
6623 LogSPS("Sleep Proxy registered record %5d %s", updatelease, ARDisplayString(m,rr));
6624 }
6625
6626 }
6627 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
6628 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
6629 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
6630 }
6631
6632 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
6633 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
6634 {
6635 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
6636 {
6637 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
6638 #if ForceAlerts
6639 *(long*)0 = 0;
6640 #endif
6641 }
6642
6643 // Create empty resource record
6644 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
6645 cr->resrec.InterfaceID = InterfaceID;
6646 cr->resrec.rDNSServer = dnsserver;
6647 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
6648 cr->resrec.rrtype = rrtype;
6649 cr->resrec.rrclass = rrclass;
6650 cr->resrec.rroriginalttl = ttl_seconds;
6651 cr->resrec.rdlength = 0;
6652 cr->resrec.rdestimate = 0;
6653 cr->resrec.namehash = namehash;
6654 cr->resrec.rdatahash = 0;
6655 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
6656 cr->resrec.rdata->MaxRDLength = 0;
6657
6658 cr->NextInKAList = mDNSNULL;
6659 cr->TimeRcvd = m->timenow;
6660 cr->DelayDelivery = 0;
6661 cr->NextRequiredQuery = m->timenow;
6662 cr->LastUsed = m->timenow;
6663 cr->CRActiveQuestion = mDNSNULL;
6664 cr->UnansweredQueries = 0;
6665 cr->LastUnansweredTime = 0;
6666 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6667 cr->MPUnansweredQ = 0;
6668 cr->MPLastUnansweredQT = 0;
6669 cr->MPUnansweredKA = 0;
6670 cr->MPExpectingKA = mDNSfalse;
6671 #endif
6672 cr->NextInCFList = mDNSNULL;
6673 }
6674
6675 mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
6676 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
6677 const mDNSInterfaceID InterfaceID)
6678 {
6679 mDNSInterfaceID ifid = InterfaceID;
6680 DNSMessage *msg = (DNSMessage *)pkt;
6681 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
6682 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
6683 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
6684 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
6685 mDNSu8 QR_OP;
6686 mDNSu8 *ptr = mDNSNULL;
6687 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
6688 if (TLS) dstaddr = mDNSNULL;
6689
6690 #ifndef UNICAST_DISABLED
6691 if (mDNSSameAddress(srcaddr, &m->Router))
6692 {
6693 #ifdef _LEGACY_NAT_TRAVERSAL_
6694 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
6695 {
6696 mDNS_Lock(m);
6697 LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
6698 mDNS_Unlock(m);
6699 return;
6700 }
6701 #endif
6702 if (mDNSSameIPPort(srcport, NATPMPPort))
6703 {
6704 mDNS_Lock(m);
6705 uDNS_ReceiveNATPMPPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
6706 mDNS_Unlock(m);
6707 return;
6708 }
6709 }
6710 #ifdef _LEGACY_NAT_TRAVERSAL_
6711 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
6712 #endif
6713
6714 #endif
6715 if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
6716 {
6717 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
6718 return;
6719 }
6720 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
6721 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
6722 ptr = (mDNSu8 *)&msg->h.numQuestions;
6723 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
6724 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
6725 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
6726 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
6727
6728 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
6729
6730 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
6731 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
6732 if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
6733
6734 mDNS_Lock(m);
6735 m->PktNum++;
6736 #ifndef UNICAST_DISABLED
6737 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
6738 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
6739 {
6740 ifid = mDNSInterface_Any;
6741 if (mDNS_PacketLoggingEnabled)
6742 DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
6743 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
6744 // Note: mDNSCore also needs to get access to received unicast responses
6745 }
6746 #endif
6747 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
6748 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
6749 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
6750 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, InterfaceID);
6751 else
6752 {
6753 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
6754 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
6755 if (mDNS_LoggingEnabled)
6756 {
6757 int i = 0;
6758 while (i<end - (mDNSu8 *)pkt)
6759 {
6760 char buffer[128];
6761 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
6762 do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]); while (++i & 15);
6763 LogInfo("%s", buffer);
6764 }
6765 }
6766 }
6767 // Packet reception often causes a change to the task list:
6768 // 1. Inbound queries can cause us to need to send responses
6769 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
6770 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
6771 // 4. Response packets that answer questions may cause our client to issue new questions
6772 mDNS_Unlock(m);
6773 }
6774
6775 // ***************************************************************************
6776 #if COMPILER_LIKES_PRAGMA_MARK
6777 #pragma mark -
6778 #pragma mark - Searcher Functions
6779 #endif
6780
6781 // Targets are considered the same if both queries are untargeted, or
6782 // if both are targeted to the same address+port
6783 // (If Target address is zero, TargetPort is undefined)
6784 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
6785 (mDNSSameAddress(&(A)->Target, &(B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
6786
6787 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
6788 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
6789 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
6790 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
6791 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
6792 //
6793 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
6794 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
6795 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
6796 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
6797 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
6798 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
6799 // breaks this design principle.
6800
6801 // If IsLLQ(Q) is true, it means the question is both:
6802 // (a) long-lived and
6803 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
6804 // for multicast questions, we don't want to treat LongLived as anything special
6805 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
6806
6807 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
6808 {
6809 DNSQuestion *q;
6810 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
6811 // This prevents circular references, where two questions are each marked as a duplicate of the other.
6812 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
6813 // further in the list.
6814 for (q = m->Questions; q && q != question; q=q->next) // Scan our list for another question
6815 if (q->InterfaceID == question->InterfaceID && // with the same InterfaceID,
6816 SameQTarget(q, question) && // and same unicast/multicast target settings
6817 q->qtype == question->qtype && // type,
6818 q->qclass == question->qclass && // class,
6819 IsLLQ(q) == IsLLQ(question) && // and long-lived status matches
6820 (!q->AuthInfo || question->AuthInfo) && // to avoid deadlock, don't make public query dup of a private one
6821 (q->SuppressQuery == question->SuppressQuery) && // Questions that are suppressed/not suppressed
6822 q->qnamehash == question->qnamehash &&
6823 SameDomainName(&q->qname, &question->qname)) // and name
6824 return(q);
6825 return(mDNSNULL);
6826 }
6827
6828 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
6829 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
6830 {
6831 DNSQuestion *q;
6832 for (q = m->Questions; q; q=q->next) // Scan our list of questions
6833 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
6834 if ((q->DuplicateOf = FindDuplicateQuestion(m, q)) == mDNSNULL)
6835 {
6836 // If q used to be a duplicate, but now is not,
6837 // then inherit the state from the question that's going away
6838 q->LastQTime = question->LastQTime;
6839 q->ThisQInterval = question->ThisQInterval;
6840 q->ExpectUnicastResp = question->ExpectUnicastResp;
6841 q->LastAnswerPktNum = question->LastAnswerPktNum;
6842 q->RecentAnswerPkts = question->RecentAnswerPkts;
6843 q->RequestUnicast = question->RequestUnicast;
6844 q->LastQTxTime = question->LastQTxTime;
6845 q->CNAMEReferrals = question->CNAMEReferrals;
6846 q->nta = question->nta;
6847 q->servAddr = question->servAddr;
6848 q->servPort = question->servPort;
6849 q->qDNSServer = question->qDNSServer;
6850 q->validDNSServers = question->validDNSServers;
6851 q->unansweredQueries = question->unansweredQueries;
6852 q->noServerResponse = question->noServerResponse;
6853 q->triedAllServersOnce = question->triedAllServersOnce;
6854
6855 q->TargetQID = question->TargetQID;
6856 q->LocalSocket = question->LocalSocket;
6857
6858 q->state = question->state;
6859 // q->tcp = question->tcp;
6860 q->ReqLease = question->ReqLease;
6861 q->expire = question->expire;
6862 q->ntries = question->ntries;
6863 q->id = question->id;
6864
6865 question->LocalSocket = mDNSNULL;
6866 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
6867 // question->tcp = mDNSNULL;
6868
6869 if (q->LocalSocket)
6870 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
6871
6872 if (q->nta)
6873 {
6874 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
6875 q->nta->ZoneDataContext = q;
6876 }
6877
6878 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
6879 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
6880
6881 if (question->state == LLQ_Established)
6882 {
6883 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
6884 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
6885 }
6886
6887 SetNextQueryTime(m,q);
6888 }
6889 }
6890
6891 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
6892 {
6893 mDNSs32 ptime = 0;
6894 if (server->penaltyTime != 0)
6895 {
6896 ptime = server->penaltyTime - m->timenow;
6897 if (ptime < 0)
6898 {
6899 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
6900 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
6901 // here
6902 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
6903 ptime, server->penaltyTime, m->timenow);
6904 server->penaltyTime = 0;
6905 ptime = 0;
6906 }
6907 }
6908 return ptime;
6909 }
6910
6911 //Checks to see whether the newname is a better match for the name, given the best one we have
6912 //seen so far (given in bestcount).
6913 //Returns -1 if the newname is not a better match
6914 //Returns 0 if the newname is the same as the old match
6915 //Returns 1 if the newname is a better match
6916 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
6917 int bestcount)
6918 {
6919 // If the name contains fewer labels than the new server's domain or the new name
6920 // contains fewer labels than the current best, then it can't possibly be a better match
6921 if (namecount < newcount || newcount < bestcount) return -1;
6922
6923 // If there is no match, return -1 and the caller will skip this newname for
6924 // selection
6925 //
6926 // If we find a match and the number of labels is the same as bestcount, then
6927 // we return 0 so that the caller can do additional logic to pick one of
6928 // the best based on some other factors e.g., penaltyTime
6929 //
6930 // If we find a match and the number of labels is more than bestcount, then we
6931 // return 1 so that the caller can pick this over the old one.
6932 //
6933 // Note: newcount can either be equal or greater than bestcount beause of the
6934 // check above.
6935
6936 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
6937 return bestcount == newcount ? 0 : 1;
6938 else
6939 return -1;
6940 }
6941
6942 // Sets all the Valid DNS servers for a question
6943 mDNSexport void SetValidDNSServers(mDNS *m, DNSQuestion *question)
6944 {
6945 DNSServer *curmatch = mDNSNULL;
6946 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
6947 DNSServer *curr;
6948 int bettermatch, currcount;
6949 int index = 0;
6950
6951 question->validDNSServers = zeroOpaque64;
6952 for (curr = m->DNSServers; curr; curr = curr->next)
6953 {
6954 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
6955 // skip servers that will soon be deleted
6956 if (curr->flags & DNSServer_FlagDelete)
6957 { debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
6958
6959 currcount = CountLabels(&curr->domain);
6960 if ((!curr->scoped && (!question->InterfaceID || (question->InterfaceID == mDNSInterface_Unicast))) || (curr->interface == question->InterfaceID))
6961 {
6962 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
6963
6964 // If we found a better match (bettermatch == 1) then clear all the bits
6965 // corresponding to the old DNSServers that we have may set before and start fresh.
6966 // If we find an equal match, then include that DNSServer also by setting the corresponding
6967 // bit
6968 if ((bettermatch == 1) || (bettermatch == 0))
6969 {
6970 curmatch = curr;
6971 bestmatchlen = currcount;
6972 if (bettermatch) { debugf("SetValidDNSServers: Resetting all the bits"); question->validDNSServers = zeroOpaque64; }
6973 debugf("SetValidDNSServers: Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d", &curr->addr, curr->domain.c, curr->scoped, index);
6974 bit_set_opaque64(question->validDNSServers, index);
6975 }
6976 }
6977 index++;
6978 }
6979 question->noServerResponse = 0;
6980 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
6981 question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
6982 }
6983
6984 // Get the Best server that matches a name. If you find penalized servers, look for the one
6985 // that will come out of the penalty box soon
6986 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSOpaque64 validBits, int *selected, mDNSBool nameMatch)
6987 {
6988 DNSServer *curmatch = mDNSNULL;
6989 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
6990 DNSServer *curr;
6991 mDNSs32 bestPenaltyTime, currPenaltyTime;
6992 int bettermatch, currcount;
6993 int index = 0;
6994 int currindex = -1;
6995
6996 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
6997 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
6998 for (curr = m->DNSServers; curr; curr = curr->next)
6999 {
7000 // skip servers that will soon be deleted
7001 if (curr->flags & DNSServer_FlagDelete)
7002 { debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped); continue; }
7003
7004 // Check if this is a valid DNSServer
7005 if (!bit_get_opaque64(validBits, index)) { debugf("GetBestServer: continuing for index %d", index); index++; continue; }
7006
7007 currcount = CountLabels(&curr->domain);
7008 currPenaltyTime = PenaltyTimeForServer(m, curr);
7009
7010 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
7011 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
7012
7013 // If there are multiple best servers for a given question, we will pick the first one
7014 // if none of them are penalized. If some of them are penalized in that list, we pick
7015 // the least penalized one. BetterMatchForName walks through all best matches and
7016 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
7017 // in the list when there are no penalized servers and least one among them
7018 // when there are some penalized servers
7019 //
7020 // Notes on InterfaceID matching:
7021 //
7022 // 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
7023 // is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
7024 // entries by "scoped" being false. These are like any other unscoped entries except that
7025 // if it is picked e.g., domain match, when the packet is sent out later, the packet will
7026 // be sent out on that interface. Theese entries can be matched by either specifying a
7027 // zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
7028 // the question will cause an extra check on matching the InterfaceID on the question
7029 // against the DNSServer.
7030 //
7031 // 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
7032 // is the new way of specifying an InterfaceID option for DNSServer. These will be considered
7033 // only when the question has non-zero interfaceID.
7034
7035 if ((!curr->scoped && !InterfaceID) || (curr->interface == InterfaceID))
7036 {
7037
7038 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
7039 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
7040 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
7041 // part and still do some redundant steps e.g., InterfaceID match
7042
7043 if (nameMatch) bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
7044 else bettermatch = 0;
7045
7046 // If we found a better match (bettermatch == 1) then we don't need to
7047 // compare penalty times. But if we found an equal match, then we compare
7048 // the penalty times to pick a better match
7049
7050 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
7051 { currindex = index; curmatch = curr; bestmatchlen = currcount; bestPenaltyTime = currPenaltyTime; }
7052 }
7053 index++;
7054 }
7055 if (selected) *selected = currindex;
7056 return curmatch;
7057 }
7058
7059 // Look up a DNS Server, matching by name and InterfaceID
7060 mDNSexport DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID)
7061 {
7062 DNSServer *curmatch = mDNSNULL;
7063 char *ifname = mDNSNULL; // for logging purposes only
7064 mDNSOpaque64 allValid;
7065
7066 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
7067 InterfaceID = mDNSNULL;
7068
7069 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
7070
7071 // By passing in all ones, we make sure that every DNS server is considered
7072 allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
7073
7074 curmatch = GetBestServer(m, name, InterfaceID, allValid, mDNSNULL, mDNStrue);
7075
7076 if (curmatch != mDNSNULL)
7077 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
7078 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
7079 InterfaceID, name);
7080 else
7081 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
7082
7083 return(curmatch);
7084 }
7085
7086 // Look up a DNS Server for a question within its valid DNSServer bits
7087 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
7088 {
7089 DNSServer *curmatch = mDNSNULL;
7090 char *ifname = mDNSNULL; // for logging purposes only
7091 mDNSInterfaceID InterfaceID = question->InterfaceID;
7092 const domainname *name = &question->qname;
7093 int currindex;
7094
7095 if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
7096 InterfaceID = mDNSNULL;
7097
7098 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
7099
7100 if (!mDNSOpaque64IsZero(&question->validDNSServers))
7101 {
7102 curmatch = GetBestServer(m, name, InterfaceID, question->validDNSServers, &currindex, mDNSfalse);
7103 if (currindex != -1) bit_clr_opaque64(question->validDNSServers, currindex);
7104 }
7105
7106 if (curmatch != mDNSNULL)
7107 LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question, &curmatch->addr,
7108 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
7109 InterfaceID, name, DNSTypeName(question->qtype));
7110 else
7111 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question, ifname ? ifname : "None", InterfaceID, name, DNSTypeName(question->qtype));
7112
7113 return(curmatch);
7114 }
7115
7116
7117 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
7118 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
7119
7120 // Called in normal client context (lock not held)
7121 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
7122 {
7123 DNSQuestion *q;
7124 (void)n; // Unused
7125 mDNS_Lock(m);
7126 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
7127 for (q = m->Questions; q; q=q->next)
7128 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
7129 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
7130 #if APPLE_OSX_mDNSResponder
7131 UpdateAutoTunnelDomainStatuses(m);
7132 #endif
7133 mDNS_Unlock(m);
7134 }
7135
7136 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, domainname *qname, mDNSu16 qtype, mDNSInterfaceID InterfaceID)
7137 {
7138 NetworkInterfaceInfo *i;
7139 mDNSs32 iptype;
7140 DomainAuthInfo *AuthInfo;
7141
7142 if (qtype == kDNSType_A) iptype = mDNSAddrType_IPv4;
7143 else if (qtype == kDNSType_AAAA) iptype = mDNSAddrType_IPv6;
7144 else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname, DNSTypeName(qtype)); return mDNSfalse; }
7145
7146 // We still want the ability to be able to listen to the local services and hence
7147 // don't fail .local requests. We always have a loopback interface which we don't
7148 // check here.
7149 if (InterfaceID != mDNSInterface_Unicast && IsLocalDomain(qname)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname, DNSTypeName(qtype)); return mDNSfalse; }
7150
7151 // Skip Private domains as we have special addresses to get the hosts in the Private domain
7152 AuthInfo = GetAuthInfoForName_internal(m, qname);
7153 if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
7154 { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname, DNSTypeName(qtype)); return mDNSfalse; }
7155
7156 // Match on Type, Address and InterfaceID
7157 //
7158 // Check whether we are looking for a name that ends in .local, then presence of a link-local
7159 // address on the interface is sufficient.
7160 for (i = m->HostInterfaces; i; i = i->next)
7161 {
7162 if (i->ip.type != iptype) continue;
7163
7164 if (!InterfaceID || (InterfaceID == mDNSInterface_LocalOnly) || (InterfaceID == mDNSInterface_P2P) ||
7165 (InterfaceID == mDNSInterface_Unicast) || (i->InterfaceID == InterfaceID))
7166 {
7167 if (iptype == mDNSAddrType_IPv4 && !mDNSv4AddressIsLoopback(&i->ip.ip.v4) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v4))
7168 {
7169 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname, DNSTypeName(qtype),
7170 &i->ip.ip.v4);
7171 return mDNSfalse;
7172 }
7173 else if (iptype == mDNSAddrType_IPv6 &&
7174 !mDNSv6AddressIsLoopback(&i->ip.ip.v6) &&
7175 !mDNSv6AddressIsLinkLocal(&i->ip.ip.v6) &&
7176 !mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelHostAddr) &&
7177 !mDNSSameIPv6Address(i->ip.ip.v6, m->AutoTunnelRelayAddrOut))
7178 {
7179 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname, DNSTypeName(qtype),
7180 &i->ip.ip.v6);
7181 return mDNSfalse;
7182 }
7183 }
7184 }
7185 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname, DNSTypeName(qtype));
7186 return mDNStrue;
7187 }
7188
7189 mDNSlocal void CheckSuppressedCurrentQuestion(mDNS *const m, DNSQuestion *q)
7190 {
7191 CacheRecord *rr;
7192 mDNSu32 slot;
7193 CacheGroup *cg;
7194
7195 // Temporarily turn off suppression so that AnswerCurrentQuestionWithResourceRecord
7196 // can answer the question
7197 q->SuppressQuery = mDNSfalse;
7198 slot = HashSlot(&q->qname);
7199 cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
7200 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7201 {
7202 // Don't deliver RMV events for negative records
7203 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
7204 {
7205 LogInfo("CheckSuppressedCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
7206 CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
7207 continue;
7208 }
7209
7210 if (SameNameRecordAnswersQuestion(&rr->resrec, q))
7211 {
7212 LogInfo("CheckSuppressedCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s",
7213 q->qname.c, CRDisplayString(m, rr));
7214
7215 q->CurrentAnswers--;
7216 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
7217 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
7218
7219 if (rr->CRActiveQuestion == q)
7220 {
7221 DNSQuestion *qptr;
7222 // If this was the active question for this cache entry, it was the one that was
7223 // responsible for keeping the cache entry fresh when the cache entry was reaching
7224 // its expiry. We need to handover the responsibility to someone else. Otherwise,
7225 // when the cache entry is about to expire, we won't find an active question
7226 // (pointed by CRActiveQuestion) to refresh the cache.
7227 for (qptr = m->Questions; qptr; qptr=qptr->next)
7228 if (ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
7229 break;
7230
7231 if (qptr)
7232 LogInfo("CheckSuppressedCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
7233 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
7234 qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
7235
7236 rr->CRActiveQuestion = qptr; // Question used to be active; new value may or may not be null
7237 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
7238 }
7239 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
7240 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
7241 }
7242 }
7243 if (m->CurrentQuestion == q) q->SuppressQuery = mDNStrue;
7244 }
7245
7246 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
7247 {
7248 DNSQuestion *q;
7249 for (q = m->NewQuestions; q; q = q->next)
7250 if (q == question) return mDNStrue;
7251 return mDNSfalse;
7252 }
7253
7254 // The caller should hold the lock
7255 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
7256 {
7257 DNSQuestion *q, *qnext;
7258 DNSQuestion *restart = mDNSNULL;
7259
7260 // We look through all questions including new questions. During network change events,
7261 // we potentially restart questions here in this function that ends up as new questions,
7262 // which may be suppressed at this instance. Before it is handled we get another network
7263 // event that changes the status e.g., address becomes available. If we did not process
7264 // new questions, we would never change its SuppressQuery status.
7265 for (q = m->Questions; q ; q = qnext)
7266 {
7267 qnext = q->next;
7268 if (!mDNSOpaque16IsZero(q->TargetQID) && q->SuppressUnusable)
7269 {
7270 mDNSBool old = q->SuppressQuery;
7271 q->SuppressQuery = ShouldSuppressQuery(m, &q->qname, q->qtype, q->InterfaceID);
7272 if (q->SuppressQuery != old)
7273 {
7274 if (q->SuppressQuery)
7275 {
7276 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
7277 // followed by a negative cache response
7278 if (m->CurrentQuestion)
7279 LogMsg("CheckSuppressUnusableQuestions: ERROR m->CurrentQuestion already set: %##s (%s)",
7280 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
7281
7282 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
7283 if (!IsQuestionNew(m, q))
7284 {
7285 m->CurrentQuestion = q;
7286 CheckSuppressedCurrentQuestion(m, q);
7287 if (m->CurrentQuestion != q)
7288 {
7289 m->CurrentQuestion = mDNSNULL;
7290 LogInfo("CheckSuppressUnusableQuestions: Question deleted while giving RMV events");
7291 continue;
7292 }
7293 m->CurrentQuestion = mDNSNULL;
7294 }
7295 else { debugf("CheckSuppressUnusableQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
7296 }
7297
7298 // There are two cases here.
7299 //
7300 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
7301 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
7302 // because when we get the response, if we had entries in the cache already, it will not answer
7303 // this question if the cache entry did not change. Hence, we need to restart
7304 // the query so that it can be answered from the cache.
7305 //
7306 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
7307 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
7308 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
7309 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
7310 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
7311 // immediate response and not want to be blocked behind a question that is querying DNS servers.
7312 // When the question is not suppressed, we don't want two active questions sending packets on the wire.
7313 // This affects both efficiency and also the current design where there is only one active question
7314 // pointed to from a cache entry.
7315 //
7316 // We restart queries in a two step process by first calling stop and build a temporary list which we
7317 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
7318 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
7319 // will soon become the real question) including q->ThisQInterval which might be zero if it was
7320 // suppressed before. At the end when we have restarted all questions, none of them is active as each
7321 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
7322 //
7323 // It is much cleaner and less error prone to build a list of questions and restart at the end.
7324
7325 LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
7326 mDNS_StopQuery_internal(m, q);
7327 q->next = restart;
7328 restart = q;
7329 }
7330 }
7331 }
7332 while (restart)
7333 {
7334 q = restart;
7335 restart = restart->next;
7336 q->next = mDNSNULL;
7337 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
7338 mDNS_StartQuery_internal(m, q);
7339 }
7340 }
7341
7342 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
7343 {
7344 if (question->Target.type && !ValidQuestionTarget(question))
7345 {
7346 LogMsg("Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery?)",
7347 question->Target.type, mDNSVal16(question->TargetPort));
7348 question->Target.type = mDNSAddrType_None;
7349 }
7350
7351 if (!question->Target.type) question->TargetPort = zeroIPPort; // If no question->Target specified clear TargetPort
7352
7353 question->TargetQID =
7354 #ifndef UNICAST_DISABLED
7355 (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
7356 #endif // UNICAST_DISABLED
7357 zeroID;
7358
7359 debugf("mDNS_StartQuery: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
7360
7361 if (m->rrcache_size == 0) // Can't do queries if we have no cache space allocated
7362 return(mStatus_NoCache);
7363 else
7364 {
7365 int i;
7366 DNSQuestion **q;
7367
7368 if (!ValidateDomainName(&question->qname))
7369 {
7370 LogMsg("Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
7371 return(mStatus_Invalid);
7372 }
7373
7374 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
7375 q = &m->Questions;
7376 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) q = &m->LocalOnlyQuestions;
7377 while (*q && *q != question) q=&(*q)->next;
7378
7379 if (*q)
7380 {
7381 LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
7382 question->qname.c, DNSTypeName(question->qtype), question);
7383 return(mStatus_AlreadyRegistered);
7384 }
7385
7386 *q = question;
7387
7388 // If this question is referencing a specific interface, verify it exists
7389 if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
7390 {
7391 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
7392 if (!intf)
7393 LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
7394 question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
7395 }
7396
7397 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
7398 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
7399 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
7400 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
7401 // that to go out immediately.
7402 question->next = mDNSNULL;
7403 question->qnamehash = DomainNameHashValue(&question->qname); // MUST do this before FindDuplicateQuestion()
7404 question->DelayAnswering = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname));
7405 question->LastQTime = m->timenow;
7406 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
7407 question->ExpectUnicastResp = 0;
7408 question->LastAnswerPktNum = m->PktNum;
7409 question->RecentAnswerPkts = 0;
7410 question->CurrentAnswers = 0;
7411 question->LargeAnswers = 0;
7412 question->UniqueAnswers = 0;
7413 question->FlappingInterface1 = mDNSNULL;
7414 question->FlappingInterface2 = mDNSNULL;
7415 // Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
7416 question->AuthInfo = GetAuthInfoForQuestion(m, question);
7417 if (question->SuppressUnusable)
7418 question->SuppressQuery = ShouldSuppressQuery(m, &question->qname, question->qtype, question->InterfaceID);
7419 else
7420 question->SuppressQuery = 0;
7421 question->DuplicateOf = FindDuplicateQuestion(m, question);
7422 question->NextInDQList = mDNSNULL;
7423 question->SendQNow = mDNSNULL;
7424 question->SendOnAll = mDNSfalse;
7425 question->RequestUnicast = 0;
7426 question->LastQTxTime = m->timenow;
7427 question->CNAMEReferrals = 0;
7428
7429 // We'll create our question->LocalSocket on demand, if needed.
7430 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
7431 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
7432 // NAT mapping for receiving inbound add/remove events.
7433 question->LocalSocket = mDNSNULL;
7434 question->deliverAddEvents = mDNSfalse;
7435 question->qDNSServer = mDNSNULL;
7436 question->unansweredQueries = 0;
7437 question->nta = mDNSNULL;
7438 question->servAddr = zeroAddr;
7439 question->servPort = zeroIPPort;
7440 question->tcp = mDNSNULL;
7441 question->NoAnswer = NoAnswer_Normal;
7442
7443 question->state = LLQ_InitialRequest;
7444 question->ReqLease = 0;
7445 question->expire = 0;
7446 question->ntries = 0;
7447 question->id = zeroOpaque64;
7448 question->validDNSServers = zeroOpaque64;
7449 question->triedAllServersOnce = 0;
7450 question->noServerResponse = 0;
7451 if (question->WakeOnResolve)
7452 {
7453 question->WakeOnResolveCount = InitialWakeOnResolveCount;
7454 mDNS_PurgeBeforeResolve(m, question);
7455 }
7456 else
7457 question->WakeOnResolveCount = 0;
7458
7459 if (question->DuplicateOf) question->AuthInfo = question->DuplicateOf->AuthInfo;
7460
7461 for (i=0; i<DupSuppressInfoSize; i++)
7462 question->DupSuppress[i].InterfaceID = mDNSNULL;
7463
7464 debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
7465 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
7466 NextQSendTime(question) - m->timenow,
7467 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
7468 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
7469
7470 if (question->DelayAnswering)
7471 LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
7472 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
7473
7474 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
7475 {
7476 if (!m->NewLocalOnlyQuestions) m->NewLocalOnlyQuestions = question;
7477 }
7478 else
7479 {
7480 if (!m->NewQuestions) m->NewQuestions = question;
7481
7482 // If the question's id is non-zero, then it's Wide Area
7483 // MUST NOT do this Wide Area setup until near the end of
7484 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
7485 // NS, etc.) and if we haven't finished setting up our own question and setting
7486 // m->NewQuestions if necessary then we could end up recursively re-entering
7487 // this routine with the question list data structures in an inconsistent state.
7488 if (!mDNSOpaque16IsZero(question->TargetQID))
7489 {
7490 // Duplicate questions should have the same DNSServers so that when we find
7491 // a matching resource record, all of them get the answers. Calling GetServerForQuestion
7492 // for the duplicate question may get a different DNS server from the original question
7493 if (question->DuplicateOf)
7494 {
7495 question->validDNSServers = question->DuplicateOf->validDNSServers;
7496 question->qDNSServer = question->DuplicateOf->qDNSServer;
7497 LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
7498 question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype),
7499 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
7500 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
7501 }
7502 else
7503 {
7504 SetValidDNSServers(m, question);
7505 question->qDNSServer = GetServerForQuestion(m, question);
7506 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s), DNS Server %#a:%d",
7507 question, question->qname.c, DNSTypeName(question->qtype),
7508 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
7509 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
7510 }
7511 ActivateUnicastQuery(m, question, mDNSfalse);
7512
7513 // If long-lived query, and we don't have our NAT mapping active, start it now
7514 if (question->LongLived && !m->LLQNAT.clientContext)
7515 {
7516 m->LLQNAT.Protocol = NATOp_MapUDP;
7517 m->LLQNAT.IntPort = m->UnicastPort4;
7518 m->LLQNAT.RequestedPort = m->UnicastPort4;
7519 m->LLQNAT.clientCallback = LLQNATCallback;
7520 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal is active
7521 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
7522 }
7523
7524 #if APPLE_OSX_mDNSResponder
7525 if (question->LongLived)
7526 UpdateAutoTunnelDomainStatuses(m);
7527 #endif
7528
7529 }
7530 SetNextQueryTime(m,question);
7531 }
7532
7533 return(mStatus_NoError);
7534 }
7535 }
7536
7537 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
7538 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
7539 {
7540 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
7541 // This function may be called anytime to free the zone information.The question may or may not have stopped.
7542 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
7543 // call it again
7544 if (nta->question.ThisQInterval != -1)
7545 {
7546 mDNS_StopQuery_internal(m, &nta->question);
7547 if (nta->question.ThisQInterval != -1)
7548 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
7549 }
7550 mDNSPlatformMemFree(nta);
7551 }
7552
7553 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
7554 {
7555 const mDNSu32 slot = HashSlot(&question->qname);
7556 CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
7557 CacheRecord *rr;
7558 DNSQuestion **qp = &m->Questions;
7559
7560 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
7561
7562 if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
7563 while (*qp && *qp != question) qp=&(*qp)->next;
7564 if (*qp) *qp = (*qp)->next;
7565 else
7566 {
7567 #if !ForceAlerts
7568 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
7569 #endif
7570 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
7571 question->qname.c, DNSTypeName(question->qtype));
7572 #if ForceAlerts
7573 *(long*)0 = 0;
7574 #endif
7575 return(mStatus_BadReferenceErr);
7576 }
7577
7578 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
7579 UpdateQuestionDuplicates(m, question);
7580 // But don't trash ThisQInterval until afterwards.
7581 question->ThisQInterval = -1;
7582
7583 // If there are any cache records referencing this as their active question, then see if there is any
7584 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
7585 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7586 {
7587 if (rr->CRActiveQuestion == question)
7588 {
7589 DNSQuestion *q;
7590 // Checking for ActiveQuestion filters questions that are suppressed also
7591 // as suppressed questions are not active
7592 for (q = m->Questions; q; q=q->next) // Scan our list of questions
7593 if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
7594 break;
7595 if (q)
7596 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
7597 "CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
7598 rr->CRActiveQuestion = q; // Question used to be active; new value may or may not be null
7599 if (!q) m->rrcache_active--; // If no longer active, decrement rrcache_active count
7600 }
7601 }
7602
7603 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
7604 // bump its pointer forward one question.
7605 if (m->CurrentQuestion == question)
7606 {
7607 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
7608 question->qname.c, DNSTypeName(question->qtype));
7609 m->CurrentQuestion = question->next;
7610 }
7611
7612 if (m->NewQuestions == question)
7613 {
7614 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
7615 question->qname.c, DNSTypeName(question->qtype));
7616 m->NewQuestions = question->next;
7617 }
7618
7619 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
7620
7621 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
7622 question->next = mDNSNULL;
7623
7624 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
7625
7626 // And finally, cancel any associated GetZoneData operation that's still running.
7627 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
7628 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
7629 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
7630 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
7631 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
7632 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
7633 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
7634 {
7635 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
7636 DNSQuestion *q;
7637 for (q = m->Questions; q; q=q->next)
7638 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
7639 if (!q)
7640 {
7641 if (!m->LLQNAT.clientContext) // Should never happen, but just in case...
7642 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
7643 else
7644 {
7645 LogInfo("Stopping LLQNAT");
7646 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
7647 m->LLQNAT.clientContext = mDNSNULL; // Means LLQ NAT Traversal not running
7648 }
7649 }
7650
7651 // If necessary, tell server it can delete this LLQ state
7652 if (question->state == LLQ_Established)
7653 {
7654 question->ReqLease = 0;
7655 sendLLQRefresh(m, question);
7656 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
7657 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
7658 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
7659 // we let that run out its natural course and complete asynchronously.
7660 if (question->tcp)
7661 {
7662 question->tcp->question = mDNSNULL;
7663 question->tcp = mDNSNULL;
7664 }
7665 }
7666 #if APPLE_OSX_mDNSResponder
7667 UpdateAutoTunnelDomainStatuses(m);
7668 #endif
7669 }
7670 // wait until we send the refresh above which needs the nta
7671 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
7672
7673 return(mStatus_NoError);
7674 }
7675
7676 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
7677 {
7678 mStatus status;
7679 mDNS_Lock(m);
7680 status = mDNS_StartQuery_internal(m, question);
7681 mDNS_Unlock(m);
7682 return(status);
7683 }
7684
7685 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
7686 {
7687 mStatus status;
7688 mDNS_Lock(m);
7689 status = mDNS_StopQuery_internal(m, question);
7690 mDNS_Unlock(m);
7691 return(status);
7692 }
7693
7694 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
7695 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
7696 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
7697 // specifically to catch and report if the client callback does try to make API calls
7698 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
7699 {
7700 mStatus status;
7701 DNSQuestion *qq;
7702 mDNS_Lock(m);
7703
7704 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
7705 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
7706
7707 status = mDNS_StopQuery_internal(m, question);
7708 if (status == mStatus_NoError && !qq)
7709 {
7710 const CacheRecord *rr;
7711 const mDNSu32 slot = HashSlot(&question->qname);
7712 CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
7713 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
7714 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7715 if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
7716 {
7717 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
7718 if (question->QuestionCallback)
7719 question->QuestionCallback(m, question, &rr->resrec, mDNSfalse);
7720 }
7721 }
7722 mDNS_Unlock(m);
7723 return(status);
7724 }
7725
7726 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
7727 {
7728 mStatus status;
7729 mDNS_Lock(m);
7730 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
7731 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
7732 mDNS_Unlock(m);
7733 return(status);
7734 }
7735
7736 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
7737 {
7738 mStatus status = mStatus_BadReferenceErr;
7739 CacheRecord *cr;
7740 mDNS_Lock(m);
7741 cr = FindIdenticalRecordInCache(m, rr);
7742 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
7743 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
7744 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
7745 mDNS_Unlock(m);
7746 return(status);
7747 }
7748
7749 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
7750 const domainname *const srv, const domainname *const domain,
7751 const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
7752 {
7753 question->InterfaceID = InterfaceID;
7754 question->Target = zeroAddr;
7755 question->qtype = kDNSType_PTR;
7756 question->qclass = kDNSClass_IN;
7757 question->LongLived = mDNStrue;
7758 question->ExpectUnique = mDNSfalse;
7759 question->ForceMCast = ForceMCast;
7760 question->ReturnIntermed = mDNSfalse;
7761 question->SuppressUnusable = mDNSfalse;
7762 question->WakeOnResolve = mDNSfalse;
7763 question->QuestionCallback = Callback;
7764 question->QuestionContext = Context;
7765 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) return(mStatus_BadParamErr);
7766
7767 return(mDNS_StartQuery_internal(m, question));
7768 }
7769
7770 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
7771 const domainname *const srv, const domainname *const domain,
7772 const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context)
7773 {
7774 mStatus status;
7775 mDNS_Lock(m);
7776 status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, ForceMCast, Callback, Context);
7777 mDNS_Unlock(m);
7778 return(status);
7779 }
7780
7781 mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
7782 {
7783 NetworkInterfaceInfo *intf;
7784 for (intf = m->HostInterfaces; intf; intf = intf->next)
7785 if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
7786 return(mDNSfalse);
7787 }
7788
7789 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
7790 {
7791 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
7792 mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
7793 if (!AddRecord) return;
7794 if (answer->rrtype != kDNSType_SRV) return;
7795
7796 query->info->port = answer->rdata->u.srv.port;
7797
7798 // If this is our first answer, then set the GotSRV flag and start the address query
7799 if (!query->GotSRV)
7800 {
7801 query->GotSRV = mDNStrue;
7802 query->qAv4.InterfaceID = answer->InterfaceID;
7803 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
7804 query->qAv6.InterfaceID = answer->InterfaceID;
7805 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
7806 mDNS_StartQuery(m, &query->qAv4);
7807 // Only do the AAAA query if this machine actually has IPv6 active
7808 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
7809 }
7810 // If this is not our first answer, only re-issue the address query if the target host name has changed
7811 else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
7812 !SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
7813 {
7814 mDNS_StopQuery(m, &query->qAv4);
7815 if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
7816 if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
7817 {
7818 // If we get here, it means:
7819 // 1. This is not our first SRV answer
7820 // 2. The interface ID is different, but the target host and port are the same
7821 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
7822 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
7823 query->qAv4.InterfaceID = query->qSRV.InterfaceID; // Will be mDNSInterface_Any, or a specific interface
7824 query->qAv6.InterfaceID = query->qSRV.InterfaceID;
7825 }
7826 else
7827 {
7828 query->qAv4.InterfaceID = answer->InterfaceID;
7829 AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
7830 query->qAv6.InterfaceID = answer->InterfaceID;
7831 AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
7832 }
7833 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
7834 mDNS_StartQuery(m, &query->qAv4);
7835 // Only do the AAAA query if this machine actually has IPv6 active
7836 if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
7837 }
7838 else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
7839 {
7840 if (++query->Answers >= 100)
7841 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
7842 query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
7843 mDNSVal16(answer->rdata->u.srv.port));
7844 query->ServiceInfoQueryCallback(m, query);
7845 }
7846 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7847 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7848 }
7849
7850 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
7851 {
7852 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
7853 if (!AddRecord) return;
7854 if (answer->rrtype != kDNSType_TXT) return;
7855 if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
7856
7857 query->GotTXT = mDNStrue;
7858 query->info->TXTlen = answer->rdlength;
7859 query->info->TXTinfo[0] = 0; // In case answer->rdlength is zero
7860 mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
7861
7862 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
7863
7864 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7865 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7866 if (query->ServiceInfoQueryCallback && query->GotADD)
7867 {
7868 if (++query->Answers >= 100)
7869 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
7870 query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
7871 query->ServiceInfoQueryCallback(m, query);
7872 }
7873 }
7874
7875 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
7876 {
7877 ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
7878 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
7879 if (!AddRecord) return;
7880
7881 if (answer->rrtype == kDNSType_A)
7882 {
7883 query->info->ip.type = mDNSAddrType_IPv4;
7884 query->info->ip.ip.v4 = answer->rdata->u.ipv4;
7885 }
7886 else if (answer->rrtype == kDNSType_AAAA)
7887 {
7888 query->info->ip.type = mDNSAddrType_IPv6;
7889 query->info->ip.ip.v6 = answer->rdata->u.ipv6;
7890 }
7891 else
7892 {
7893 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
7894 return;
7895 }
7896
7897 query->GotADD = mDNStrue;
7898 query->info->InterfaceID = answer->InterfaceID;
7899
7900 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
7901
7902 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7903 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7904 if (query->ServiceInfoQueryCallback && query->GotTXT)
7905 {
7906 if (++query->Answers >= 100)
7907 debugf(answer->rrtype == kDNSType_A ?
7908 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
7909 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
7910 query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
7911 query->ServiceInfoQueryCallback(m, query);
7912 }
7913 }
7914
7915 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
7916 // If the query is not interface-specific, then InterfaceID may be zero
7917 // Each time the Callback is invoked, the remainder of the fields will have been filled in
7918 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
7919 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
7920 ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
7921 {
7922 mStatus status;
7923 mDNS_Lock(m);
7924
7925 query->qSRV.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7926 query->qSRV.InterfaceID = info->InterfaceID;
7927 query->qSRV.Target = zeroAddr;
7928 AssignDomainName(&query->qSRV.qname, &info->name);
7929 query->qSRV.qtype = kDNSType_SRV;
7930 query->qSRV.qclass = kDNSClass_IN;
7931 query->qSRV.LongLived = mDNSfalse;
7932 query->qSRV.ExpectUnique = mDNStrue;
7933 query->qSRV.ForceMCast = mDNSfalse;
7934 query->qSRV.ReturnIntermed = mDNSfalse;
7935 query->qSRV.SuppressUnusable = mDNSfalse;
7936 query->qSRV.WakeOnResolve = mDNSfalse;
7937 query->qSRV.QuestionCallback = FoundServiceInfoSRV;
7938 query->qSRV.QuestionContext = query;
7939
7940 query->qTXT.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7941 query->qTXT.InterfaceID = info->InterfaceID;
7942 query->qTXT.Target = zeroAddr;
7943 AssignDomainName(&query->qTXT.qname, &info->name);
7944 query->qTXT.qtype = kDNSType_TXT;
7945 query->qTXT.qclass = kDNSClass_IN;
7946 query->qTXT.LongLived = mDNSfalse;
7947 query->qTXT.ExpectUnique = mDNStrue;
7948 query->qTXT.ForceMCast = mDNSfalse;
7949 query->qTXT.ReturnIntermed = mDNSfalse;
7950 query->qTXT.SuppressUnusable = mDNSfalse;
7951 query->qTXT.WakeOnResolve = mDNSfalse;
7952 query->qTXT.QuestionCallback = FoundServiceInfoTXT;
7953 query->qTXT.QuestionContext = query;
7954
7955 query->qAv4.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7956 query->qAv4.InterfaceID = info->InterfaceID;
7957 query->qAv4.Target = zeroAddr;
7958 query->qAv4.qname.c[0] = 0;
7959 query->qAv4.qtype = kDNSType_A;
7960 query->qAv4.qclass = kDNSClass_IN;
7961 query->qAv4.LongLived = mDNSfalse;
7962 query->qAv4.ExpectUnique = mDNStrue;
7963 query->qAv4.ForceMCast = mDNSfalse;
7964 query->qAv4.ReturnIntermed = mDNSfalse;
7965 query->qAv4.SuppressUnusable = mDNSfalse;
7966 query->qAv4.WakeOnResolve = mDNSfalse;
7967 query->qAv4.QuestionCallback = FoundServiceInfo;
7968 query->qAv4.QuestionContext = query;
7969
7970 query->qAv6.ThisQInterval = -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7971 query->qAv6.InterfaceID = info->InterfaceID;
7972 query->qAv6.Target = zeroAddr;
7973 query->qAv6.qname.c[0] = 0;
7974 query->qAv6.qtype = kDNSType_AAAA;
7975 query->qAv6.qclass = kDNSClass_IN;
7976 query->qAv6.LongLived = mDNSfalse;
7977 query->qAv6.ExpectUnique = mDNStrue;
7978 query->qAv6.ForceMCast = mDNSfalse;
7979 query->qAv6.ReturnIntermed = mDNSfalse;
7980 query->qAv6.SuppressUnusable = mDNSfalse;
7981 query->qAv6.WakeOnResolve = mDNSfalse;
7982 query->qAv6.QuestionCallback = FoundServiceInfo;
7983 query->qAv6.QuestionContext = query;
7984
7985 query->GotSRV = mDNSfalse;
7986 query->GotTXT = mDNSfalse;
7987 query->GotADD = mDNSfalse;
7988 query->Answers = 0;
7989
7990 query->info = info;
7991 query->ServiceInfoQueryCallback = Callback;
7992 query->ServiceInfoQueryContext = Context;
7993
7994 // info->name = Must already be set up by client
7995 // info->interface = Must already be set up by client
7996 info->ip = zeroAddr;
7997 info->port = zeroIPPort;
7998 info->TXTlen = 0;
7999
8000 // We use mDNS_StartQuery_internal here because we're already holding the lock
8001 status = mDNS_StartQuery_internal(m, &query->qSRV);
8002 if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
8003 if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
8004
8005 mDNS_Unlock(m);
8006 return(status);
8007 }
8008
8009 mDNSexport void mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
8010 {
8011 mDNS_Lock(m);
8012 // We use mDNS_StopQuery_internal here because we're already holding the lock
8013 if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
8014 if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
8015 if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
8016 if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
8017 mDNS_Unlock(m);
8018 }
8019
8020 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
8021 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
8022 {
8023 question->InterfaceID = InterfaceID;
8024 question->Target = zeroAddr;
8025 question->qtype = kDNSType_PTR;
8026 question->qclass = kDNSClass_IN;
8027 question->LongLived = mDNSfalse;
8028 question->ExpectUnique = mDNSfalse;
8029 question->ForceMCast = mDNSfalse;
8030 question->ReturnIntermed = mDNSfalse;
8031 question->SuppressUnusable = mDNSfalse;
8032 question->WakeOnResolve = mDNSfalse;
8033 question->QuestionCallback = Callback;
8034 question->QuestionContext = Context;
8035 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
8036 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
8037 if (!dom) dom = &localdomain;
8038 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
8039 return(mDNS_StartQuery(m, question));
8040 }
8041
8042 // ***************************************************************************
8043 #if COMPILER_LIKES_PRAGMA_MARK
8044 #pragma mark -
8045 #pragma mark - Responder Functions
8046 #endif
8047
8048 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
8049 {
8050 mStatus status;
8051 mDNS_Lock(m);
8052 status = mDNS_Register_internal(m, rr);
8053 mDNS_Unlock(m);
8054 return(status);
8055 }
8056
8057 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
8058 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
8059 {
8060 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
8061 {
8062 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
8063 return(mStatus_Invalid);
8064 }
8065
8066 mDNS_Lock(m);
8067
8068 // If TTL is unspecified, leave TTL unchanged
8069 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
8070
8071 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
8072 if (rr->NewRData)
8073 {
8074 RData *n = rr->NewRData;
8075 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
8076 if (rr->UpdateCallback)
8077 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
8078 }
8079
8080 rr->NewRData = newrdata;
8081 rr->newrdlength = newrdlength;
8082 rr->UpdateCallback = Callback;
8083
8084 #ifndef UNICAST_DISABLED
8085 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly && rr->resrec.InterfaceID != mDNSInterface_P2P && !IsLocalDomain(rr->resrec.name))
8086 {
8087 mStatus status = uDNS_UpdateRecord(m, rr);
8088 // The caller frees the memory on error, don't retain stale pointers
8089 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
8090 mDNS_Unlock(m);
8091 return(status);
8092 }
8093 #endif
8094
8095 if (rr->resrec.rroriginalttl == newttl &&
8096 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength))
8097 CompleteRDataUpdate(m, rr);
8098 else
8099 {
8100 rr->AnnounceCount = InitialAnnounceCount;
8101 InitializeLastAPTime(m, rr);
8102 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
8103 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
8104 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
8105 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
8106 if (rr->UpdateCredits <= 5)
8107 {
8108 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
8109 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
8110 rr->ThisAPInterval *= 4;
8111 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
8112 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
8113 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
8114 }
8115 rr->resrec.rroriginalttl = newttl;
8116 }
8117
8118 mDNS_Unlock(m);
8119 return(mStatus_NoError);
8120 }
8121
8122 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
8123 // the record list and/or question list.
8124 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8125 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
8126 {
8127 mStatus status;
8128 mDNS_Lock(m);
8129 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
8130 mDNS_Unlock(m);
8131 return(status);
8132 }
8133
8134 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
8135 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
8136
8137 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
8138 {
8139 NetworkInterfaceInfo *intf;
8140 for (intf = m->HostInterfaces; intf; intf = intf->next)
8141 if (intf->Advertise) break;
8142 return(intf);
8143 }
8144
8145 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
8146 {
8147 char buffer[MAX_REVERSE_MAPPING_NAME];
8148 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
8149 if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
8150
8151 // Send dynamic update for non-linklocal IPv4 Addresses
8152 mDNS_SetupResourceRecord(&set->RR_A, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, kDNSRecordTypeUnique, mDNS_HostNameCallback, set);
8153 mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
8154 mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique, mDNSNULL, mDNSNULL);
8155
8156 #if ANSWER_REMOTE_HOSTNAME_QUERIES
8157 set->RR_A .AllowRemoteQuery = mDNStrue;
8158 set->RR_PTR .AllowRemoteQuery = mDNStrue;
8159 set->RR_HINFO.AllowRemoteQuery = mDNStrue;
8160 #endif
8161 // 1. Set up Address record to map from host name ("foo.local.") to IP address
8162 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
8163 AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
8164 if (set->ip.type == mDNSAddrType_IPv4)
8165 {
8166 set->RR_A.resrec.rrtype = kDNSType_A;
8167 set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
8168 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
8169 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
8170 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
8171 }
8172 else if (set->ip.type == mDNSAddrType_IPv6)
8173 {
8174 int i;
8175 set->RR_A.resrec.rrtype = kDNSType_AAAA;
8176 set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
8177 for (i = 0; i < 16; i++)
8178 {
8179 static const char hexValues[] = "0123456789ABCDEF";
8180 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
8181 buffer[i * 4 + 1] = '.';
8182 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
8183 buffer[i * 4 + 3] = '.';
8184 }
8185 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
8186 }
8187
8188 MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
8189 set->RR_PTR.AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
8190 set->RR_PTR.ForceMCast = mDNStrue; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
8191
8192 set->RR_A.RRSet = &primary->RR_A; // May refer to self
8193
8194 mDNS_Register_internal(m, &set->RR_A);
8195 mDNS_Register_internal(m, &set->RR_PTR);
8196
8197 if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
8198 {
8199 mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
8200 AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
8201 set->RR_HINFO.DependentOn = &set->RR_A;
8202 mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
8203 p += 1 + (int)p[0];
8204 mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
8205 mDNS_Register_internal(m, &set->RR_HINFO);
8206 }
8207 else
8208 {
8209 debugf("Not creating HINFO record: platform support layer provided no information");
8210 set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
8211 }
8212 }
8213
8214 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
8215 {
8216 NetworkInterfaceInfo *intf;
8217
8218 // If we still have address records referring to this one, update them
8219 NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
8220 AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
8221 for (intf = m->HostInterfaces; intf; intf = intf->next)
8222 if (intf->RR_A.RRSet == &set->RR_A)
8223 intf->RR_A.RRSet = A;
8224
8225 // Unregister these records.
8226 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
8227 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
8228 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
8229 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
8230 if (set->RR_A. resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
8231 if (set->RR_PTR. resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
8232 if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
8233 }
8234
8235 mDNSexport void mDNS_SetFQDN(mDNS *const m)
8236 {
8237 domainname newmname;
8238 NetworkInterfaceInfo *intf;
8239 AuthRecord *rr;
8240 newmname.c[0] = 0;
8241
8242 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
8243 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
8244
8245 mDNS_Lock(m);
8246
8247 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
8248 else
8249 {
8250 AssignDomainName(&m->MulticastHostname, &newmname);
8251
8252 // 1. Stop advertising our address records on all interfaces
8253 for (intf = m->HostInterfaces; intf; intf = intf->next)
8254 if (intf->Advertise) DeadvertiseInterface(m, intf);
8255
8256 // 2. Start advertising our address records using the new name
8257 for (intf = m->HostInterfaces; intf; intf = intf->next)
8258 if (intf->Advertise) AdvertiseInterface(m, intf);
8259 }
8260
8261 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
8262 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
8263 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
8264
8265 mDNS_Unlock(m);
8266 }
8267
8268 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
8269 {
8270 (void)rr; // Unused parameter
8271
8272 #if MDNS_DEBUGMSGS
8273 {
8274 char *msg = "Unknown result";
8275 if (result == mStatus_NoError) msg = "Name registered";
8276 else if (result == mStatus_NameConflict) msg = "Name conflict";
8277 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
8278 }
8279 #endif
8280
8281 if (result == mStatus_NoError)
8282 {
8283 // Notify the client that the host name is successfully registered
8284 if (m->MainCallback)
8285 m->MainCallback(m, mStatus_NoError);
8286 }
8287 else if (result == mStatus_NameConflict)
8288 {
8289 domainlabel oldlabel = m->hostlabel;
8290
8291 // 1. First give the client callback a chance to pick a new name
8292 if (m->MainCallback)
8293 m->MainCallback(m, mStatus_NameConflict);
8294
8295 // 2. If the client callback didn't do it, add (or increment) an index ourselves
8296 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
8297 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
8298 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
8299 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
8300
8301 // 3. Generate the FQDNs from the hostlabel,
8302 // and make sure all SRV records, etc., are updated to reference our new hostname
8303 mDNS_SetFQDN(m);
8304 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
8305 }
8306 else if (result == mStatus_MemFree)
8307 {
8308 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
8309 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
8310 debugf("mDNS_HostNameCallback: MemFree (ignored)");
8311 }
8312 else
8313 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
8314 }
8315
8316 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
8317 {
8318 NetworkInterfaceInfo *intf;
8319 active->IPv4Available = mDNSfalse;
8320 active->IPv6Available = mDNSfalse;
8321 for (intf = m->HostInterfaces; intf; intf = intf->next)
8322 if (intf->InterfaceID == active->InterfaceID)
8323 {
8324 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
8325 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
8326 }
8327 }
8328
8329 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
8330 {
8331 AuthRecord *rr;
8332 LogInfo("RestartRecordGetZoneData: ResourceRecords");
8333 for (rr = m->ResourceRecords; rr; rr=rr->next)
8334 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
8335 {
8336 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
8337 // Zero out the updateid so that if we have a pending response from the server, it won't
8338 // be accepted as a valid response. If we accept the response, we might free the new "nta"
8339 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
8340 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
8341 }
8342 }
8343
8344 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
8345 {
8346 int i;
8347 set->NetWakeBrowse.ThisQInterval = -1;
8348 for (i=0; i<3; i++)
8349 {
8350 set->NetWakeResolve[i].ThisQInterval = -1;
8351 set->SPSAddr[i].type = mDNSAddrType_None;
8352 }
8353 set->NextSPSAttempt = -1;
8354 set->NextSPSAttemptTime = m->timenow;
8355 }
8356
8357 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
8358 {
8359 NetworkInterfaceInfo *p = m->HostInterfaces;
8360 while (p && p != set) p=p->next;
8361 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
8362
8363 if (set->InterfaceActive)
8364 {
8365 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
8366 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, mDNSfalse, m->SPSBrowseCallback, set);
8367 }
8368 }
8369
8370 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
8371 {
8372 NetworkInterfaceInfo *p = m->HostInterfaces;
8373 while (p && p != set) p=p->next;
8374 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
8375
8376 if (set->NetWakeBrowse.ThisQInterval >= 0)
8377 {
8378 int i;
8379 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
8380
8381 // Stop our browse and resolve operations
8382 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
8383 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
8384
8385 // Make special call to the browse callback to let it know it can to remove all records for this interface
8386 if (m->SPSBrowseCallback)
8387 {
8388 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
8389 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
8390 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8391 }
8392
8393 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
8394 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
8395 InitializeNetWakeState(m, set);
8396 }
8397 }
8398
8399 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
8400 {
8401 AuthRecord *rr;
8402 mDNSBool FirstOfType = mDNStrue;
8403 NetworkInterfaceInfo **p = &m->HostInterfaces;
8404
8405 if (!set->InterfaceID)
8406 { LogMsg("Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
8407
8408 if (!mDNSAddressIsValidNonZero(&set->mask))
8409 { LogMsg("Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
8410
8411 mDNS_Lock(m);
8412
8413 // Assume this interface will be active now, unless we find a duplicate already in the list
8414 set->InterfaceActive = mDNStrue;
8415 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
8416 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
8417
8418 InitializeNetWakeState(m, set);
8419
8420 // Scan list to see if this InterfaceID is already represented
8421 while (*p)
8422 {
8423 if (*p == set)
8424 {
8425 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
8426 mDNS_Unlock(m);
8427 return(mStatus_AlreadyRegistered);
8428 }
8429
8430 if ((*p)->InterfaceID == set->InterfaceID)
8431 {
8432 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
8433 set->InterfaceActive = mDNSfalse;
8434 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
8435 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
8436 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
8437 }
8438
8439 p=&(*p)->next;
8440 }
8441
8442 set->next = mDNSNULL;
8443 *p = set;
8444
8445 if (set->Advertise)
8446 AdvertiseInterface(m, set);
8447
8448 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set->InterfaceID, set->ifname, &set->ip,
8449 set->InterfaceActive ?
8450 "not represented in list; marking active and retriggering queries" :
8451 "already represented in list; marking inactive for now");
8452
8453 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
8454
8455 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
8456 // giving the false impression that there's an active representative of this interface when there really isn't.
8457 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
8458 // even if we believe that we previously had an active representative of this interface.
8459 if (set->McastTxRx && ((m->KnownBugs & mDNS_KnownBug_PhantomInterfaces) || FirstOfType || set->InterfaceActive))
8460 {
8461 DNSQuestion *q;
8462 // Normally, after an interface comes up, we pause half a second before beginning probing.
8463 // This is to guard against cases where there's rapid interface changes, where we could be confused by
8464 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
8465 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
8466 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
8467 // and think it's a conflicting answer to our probe.
8468 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
8469 const mDNSs32 probedelay = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
8470 const mDNSu8 numannounce = flapping ? (mDNSu8)1 : InitialAnnounceCount;
8471
8472 // Use a small amount of randomness:
8473 // In the case of a network administrator turning on an Ethernet hub so that all the
8474 // connected machines establish link at exactly the same time, we don't want them all
8475 // to go and hit the network with identical queries at exactly the same moment.
8476 // We set a random delay of up to InitialQuestionInterval (1/3 second).
8477 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
8478 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
8479 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
8480 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
8481 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
8482 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
8483
8484 if (flapping) LogMsg("RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
8485
8486 LogInfo("RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
8487 if (m->SuppressProbes == 0 ||
8488 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
8489 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
8490
8491 for (q = m->Questions; q; q=q->next) // Scan our list of questions
8492 if (mDNSOpaque16IsZero(q->TargetQID))
8493 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
8494 { // then reactivate this question
8495 // If flapping, delay between first and second queries is nine seconds instead of one second
8496 mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
8497 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
8498 mDNSs32 qdelay = dodelay ? mDNSPlatformOneSecond * 5 : 0;
8499 if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
8500
8501 if (!q->ThisQInterval || q->ThisQInterval > initial)
8502 {
8503 q->ThisQInterval = initial;
8504 q->RequestUnicast = 2; // Set to 2 because is decremented once *before* we check it
8505 }
8506 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
8507 q->RecentAnswerPkts = 0;
8508 SetNextQueryTime(m,q);
8509 }
8510
8511 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
8512 // we now need them to re-probe if necessary, and then re-announce.
8513 for (rr = m->ResourceRecords; rr; rr=rr->next)
8514 if (!AuthRecord_uDNS(rr))
8515 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
8516 {
8517 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
8518 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
8519 if (rr->AnnounceCount < numannounce) rr->AnnounceCount = numannounce;
8520 rr->SendNSECNow = mDNSNULL;
8521 InitializeLastAPTime(m, rr);
8522 }
8523 }
8524
8525 RestartRecordGetZoneData(m);
8526
8527 CheckSuppressUnusableQuestions(m);
8528
8529 mDNS_UpdateAllowSleep(m);
8530
8531 mDNS_Unlock(m);
8532 return(mStatus_NoError);
8533 }
8534
8535 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
8536 // the record list and/or question list.
8537 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8538 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
8539 {
8540 NetworkInterfaceInfo **p = &m->HostInterfaces;
8541
8542 mDNSBool revalidate = mDNSfalse;
8543 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
8544 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
8545 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
8546 if (m->KnownBugs & mDNS_KnownBug_PhantomInterfaces) revalidate = mDNStrue;
8547
8548 mDNS_Lock(m);
8549
8550 // Find this record in our list
8551 while (*p && *p != set) p=&(*p)->next;
8552 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
8553
8554 mDNS_DeactivateNetWake_internal(m, set);
8555
8556 // Unlink this record from our list
8557 *p = (*p)->next;
8558 set->next = mDNSNULL;
8559
8560 if (!set->InterfaceActive)
8561 {
8562 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
8563 NetworkInterfaceInfo *intf;
8564 for (intf = m->HostInterfaces; intf; intf = intf->next)
8565 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
8566 UpdateInterfaceProtocols(m, intf);
8567 }
8568 else
8569 {
8570 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
8571 if (intf)
8572 {
8573 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
8574 " making it active", set->InterfaceID, set->ifname, &set->ip);
8575 if (intf->InterfaceActive)
8576 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
8577 intf->InterfaceActive = mDNStrue;
8578 UpdateInterfaceProtocols(m, intf);
8579
8580 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
8581
8582 // See if another representative *of the same type* exists. If not, we mave have gone from
8583 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
8584 for (intf = m->HostInterfaces; intf; intf = intf->next)
8585 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
8586 break;
8587 if (!intf) revalidate = mDNStrue;
8588 }
8589 else
8590 {
8591 mDNSu32 slot;
8592 CacheGroup *cg;
8593 CacheRecord *rr;
8594 DNSQuestion *q;
8595 DNSServer *s;
8596
8597 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
8598 " marking questions etc. dormant", set->InterfaceID, set->ifname, &set->ip);
8599
8600 if (set->McastTxRx && flapping)
8601 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
8602
8603 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
8604 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
8605 for (q = m->Questions; q; q=q->next)
8606 {
8607 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
8608 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
8609 {
8610 q->FlappingInterface2 = q->FlappingInterface1;
8611 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
8612 }
8613 }
8614
8615 // 2. Flush any cache records received on this interface
8616 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
8617 FORALL_CACHERECORDS(slot, cg, rr)
8618 if (rr->resrec.InterfaceID == set->InterfaceID)
8619 {
8620 // If this interface is deemed flapping,
8621 // postpone deleting the cache records in case the interface comes back again
8622 if (set->McastTxRx && flapping)
8623 {
8624 // For a flapping interface we want these record to go away after 30 seconds
8625 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
8626 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
8627 // if the interface does come back, any relevant questions will be reactivated anyway
8628 rr->UnansweredQueries = MaxUnansweredQueries;
8629 }
8630 else
8631 mDNS_PurgeCacheResourceRecord(m, rr);
8632 }
8633
8634 // 3. Any DNS servers specific to this interface are now unusable
8635 for (s = m->DNSServers; s; s = s->next)
8636 if (s->interface == set->InterfaceID)
8637 {
8638 s->interface = mDNSInterface_Any;
8639 s->teststate = DNSServer_Disabled;
8640 }
8641 }
8642 }
8643
8644 // If we were advertising on this interface, deregister those address and reverse-lookup records now
8645 if (set->Advertise) DeadvertiseInterface(m, set);
8646
8647 // If we have any cache records received on this interface that went away, then re-verify them.
8648 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
8649 // giving the false impression that there's an active representative of this interface when there really isn't.
8650 // Don't need to do this when shutting down, because *all* interfaces are about to go away
8651 if (revalidate && !m->ShutdownTime)
8652 {
8653 mDNSu32 slot;
8654 CacheGroup *cg;
8655 CacheRecord *rr;
8656 FORALL_CACHERECORDS(slot, cg, rr)
8657 if (rr->resrec.InterfaceID == set->InterfaceID)
8658 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
8659 }
8660
8661 CheckSuppressUnusableQuestions(m);
8662
8663 mDNS_UpdateAllowSleep(m);
8664
8665 mDNS_Unlock(m);
8666 }
8667
8668 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
8669 {
8670 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
8671 (void)m; // Unused parameter
8672
8673 #if MDNS_DEBUGMSGS
8674 {
8675 char *msg = "Unknown result";
8676 if (result == mStatus_NoError) msg = "Name Registered";
8677 else if (result == mStatus_NameConflict) msg = "Name Conflict";
8678 else if (result == mStatus_MemFree) msg = "Memory Free";
8679 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
8680 }
8681 #endif
8682
8683 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
8684 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
8685
8686 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
8687 if (result == mStatus_NameConflict)
8688 {
8689 sr->Conflict = mDNStrue; // Record that this service set had a conflict
8690 mDNS_DeregisterService(m, sr); // Unlink the records from our list
8691 return;
8692 }
8693
8694 if (result == mStatus_MemFree)
8695 {
8696 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
8697 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
8698 // every record is finished cleaning up.
8699 mDNSu32 i;
8700 ExtraResourceRecord *e = sr->Extras;
8701
8702 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
8703 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
8704 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
8705 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
8706 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
8707
8708 while (e)
8709 {
8710 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
8711 e = e->next;
8712 }
8713
8714 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
8715 // then we can now report the NameConflict to the client
8716 if (sr->Conflict) result = mStatus_NameConflict;
8717
8718 }
8719
8720 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered": "Registered"), sr->RR_PTR.resrec.name->c);
8721 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
8722 // function is allowed to do anything, including deregistering this service and freeing its memory.
8723 if (sr->ServiceCallback)
8724 sr->ServiceCallback(m, sr, result);
8725 }
8726
8727 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
8728 {
8729 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
8730 if (sr->ServiceCallback)
8731 sr->ServiceCallback(m, sr, result);
8732 }
8733
8734 // Note:
8735 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
8736 // Type is service type (e.g. "_ipp._tcp.")
8737 // Domain is fully qualified domain name (i.e. ending with a null label)
8738 // We always register a TXT, even if it is empty (so that clients are not
8739 // left waiting forever looking for a nonexistent record.)
8740 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
8741 // then the default host name (m->MulticastHostname) is automatically used
8742 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
8743 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
8744 const domainlabel *const name, const domainname *const type, const domainname *const domain,
8745 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
8746 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
8747 const mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context)
8748 {
8749 mStatus err;
8750 mDNSu32 i;
8751
8752 sr->ServiceCallback = Callback;
8753 sr->ServiceContext = Context;
8754 sr->Conflict = mDNSfalse;
8755
8756 sr->Extras = mDNSNULL;
8757 sr->NumSubTypes = NumSubTypes;
8758 sr->SubTypes = SubTypes;
8759
8760 // Initialize the AuthRecord objects to sane values
8761 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
8762 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, ServiceCallback, sr);
8763 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, ServiceCallback, sr);
8764 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, ServiceCallback, sr);
8765 mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, ServiceCallback, sr);
8766
8767 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
8768 if (mDNSIPPortIsZero(port))
8769 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, mDNSInterface_Any, NSSCallback, sr));
8770
8771 // If the client is registering an oversized TXT record,
8772 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
8773 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
8774 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
8775
8776 // Set up the record names
8777 // For now we only create an advisory record for the main type, not for subtypes
8778 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
8779 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
8780 return(mStatus_BadParamErr);
8781 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
8782 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
8783 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
8784
8785 // 1. Set up the ADV record rdata to advertise our service type
8786 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
8787
8788 // 2. Set up the PTR record rdata to point to our service name
8789 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
8790 // Note: uDNS registration code assumes that Additional1 points to the SRV record
8791 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
8792 sr->RR_PTR.Additional1 = &sr->RR_SRV;
8793 sr->RR_PTR.Additional2 = &sr->RR_TXT;
8794
8795 // 2a. Set up any subtype PTRs to point to our service name
8796 // If the client is using subtypes, it is the client's responsibility to have
8797 // already set the first label of the record name to the subtype being registered
8798 for (i=0; i<NumSubTypes; i++)
8799 {
8800 domainname st;
8801 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
8802 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
8803 AppendDomainName(&st, type);
8804 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, ServiceCallback, sr);
8805 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
8806 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
8807 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
8808 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
8809 }
8810
8811 // 3. Set up the SRV record rdata.
8812 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
8813 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
8814 sr->RR_SRV.resrec.rdata->u.srv.port = port;
8815
8816 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
8817 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
8818 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
8819
8820 // 4. Set up the TXT record rdata,
8821 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
8822 // Note: uDNS registration code assumes that DependentOn points to the SRV record
8823 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
8824 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
8825 {
8826 sr->RR_TXT.resrec.rdlength = txtlen;
8827 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
8828 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
8829 }
8830 sr->RR_TXT.DependentOn = &sr->RR_SRV;
8831
8832 mDNS_Lock(m);
8833 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
8834 // that if the SRV cannot find a target, rest of the records that belong to this service
8835 // will not be activated.
8836 err = mDNS_Register_internal(m, &sr->RR_SRV);
8837 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
8838 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
8839 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
8840 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
8841 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
8842 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
8843 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
8844 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
8845 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
8846
8847 mDNS_Unlock(m);
8848
8849 if (err) mDNS_DeregisterService(m, sr);
8850 return(err);
8851 }
8852
8853 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
8854 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl)
8855 {
8856 ExtraResourceRecord **e;
8857 mStatus status;
8858
8859 extra->next = mDNSNULL;
8860 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
8861 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, ServiceCallback, sr);
8862 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
8863
8864 mDNS_Lock(m);
8865 e = &sr->Extras;
8866 while (*e) e = &(*e)->next;
8867
8868 if (ttl == 0) ttl = kStandardTTL;
8869
8870 extra->r.DependentOn = &sr->RR_SRV;
8871
8872 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
8873 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
8874
8875 status = mDNS_Register_internal(m, &extra->r);
8876 if (status == mStatus_NoError) *e = extra;
8877
8878 mDNS_Unlock(m);
8879 return(status);
8880 }
8881
8882 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
8883 mDNSRecordCallback MemFreeCallback, void *Context)
8884 {
8885 ExtraResourceRecord **e;
8886 mStatus status;
8887
8888 mDNS_Lock(m);
8889 e = &sr->Extras;
8890 while (*e && *e != extra) e = &(*e)->next;
8891 if (!*e)
8892 {
8893 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
8894 status = mStatus_BadReferenceErr;
8895 }
8896 else
8897 {
8898 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
8899 extra->r.RecordCallback = MemFreeCallback;
8900 extra->r.RecordContext = Context;
8901 *e = (*e)->next;
8902 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
8903 }
8904 mDNS_Unlock(m);
8905 return(status);
8906 }
8907
8908 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
8909 {
8910 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
8911 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
8912 domainlabel name1, name2;
8913 domainname type, domain;
8914 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
8915 ExtraResourceRecord *extras = sr->Extras;
8916 mStatus err;
8917
8918 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
8919 if (!newname)
8920 {
8921 name2 = name1;
8922 IncrementLabelSuffix(&name2, mDNStrue);
8923 newname = &name2;
8924 }
8925
8926 if (SameDomainName(&domain, &localdomain))
8927 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
8928 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
8929
8930 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
8931 host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
8932 sr->SubTypes, sr->NumSubTypes,
8933 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext);
8934
8935 // mDNS_RegisterService() just reset sr->Extras to NULL.
8936 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
8937 // through the old list of extra records, and re-add them to our freshly created service registration
8938 while (!err && extras)
8939 {
8940 ExtraResourceRecord *e = extras;
8941 extras = extras->next;
8942 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl);
8943 }
8944
8945 return(err);
8946 }
8947
8948 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
8949 // which may change the record list and/or question list.
8950 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8951 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
8952 {
8953 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
8954 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
8955
8956 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
8957 {
8958 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
8959 return(mStatus_BadReferenceErr);
8960 }
8961 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
8962 {
8963 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
8964 // Avoid race condition:
8965 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
8966 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
8967 // If the client happens to deregister the service in the middle of that process, then
8968 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
8969 // instead of incorrectly promoting it to mStatus_NameConflict.
8970 // This race condition is exposed particularly when the conformance test generates
8971 // a whole batch of simultaneous conflicts across a range of services all advertised
8972 // using the same system default name, and if we don't take this precaution then
8973 // we end up incrementing m->nicelabel multiple times instead of just once.
8974 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
8975 sr->Conflict = mDNSfalse;
8976 return(mStatus_NoError);
8977 }
8978 else
8979 {
8980 mDNSu32 i;
8981 mStatus status;
8982 ExtraResourceRecord *e;
8983 mDNS_Lock(m);
8984 e = sr->Extras;
8985
8986 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
8987 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
8988 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
8989 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
8990
8991 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
8992
8993 // We deregister all of the extra records, but we leave the sr->Extras list intact
8994 // in case the client wants to do a RenameAndReregister and reinstate the registration
8995 while (e)
8996 {
8997 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
8998 e = e->next;
8999 }
9000
9001 for (i=0; i<sr->NumSubTypes; i++)
9002 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
9003
9004 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
9005 mDNS_Unlock(m);
9006 return(status);
9007 }
9008 }
9009
9010 // Create a registration that asserts that no such service exists with this name.
9011 // This can be useful where there is a given function is available through several protocols.
9012 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
9013 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
9014 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
9015 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
9016 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
9017 const domainlabel *const name, const domainname *const type, const domainname *const domain,
9018 const domainname *const host,
9019 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context)
9020 {
9021 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, Callback, Context);
9022 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
9023 rr->resrec.rdata->u.srv.priority = 0;
9024 rr->resrec.rdata->u.srv.weight = 0;
9025 rr->resrec.rdata->u.srv.port = zeroIPPort;
9026 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
9027 else rr->AutoTarget = Target_AutoHost;
9028 return(mDNS_Register(m, rr));
9029 }
9030
9031 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
9032 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
9033 {
9034 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, mDNSNULL, mDNSNULL);
9035 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
9036 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
9037 return(mDNS_Register(m, rr));
9038 }
9039
9040 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
9041 {
9042 AuthRecord *r;
9043 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
9044 return mDNSfalse;
9045 }
9046
9047 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
9048 {
9049 DNSQuestion *q;
9050 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
9051 return mDNSfalse;
9052 }
9053
9054 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
9055 {
9056 mDNSOpaque16 id;
9057 int i;
9058
9059 for (i=0; i<10; i++)
9060 {
9061 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
9062 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
9063 }
9064
9065 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
9066
9067 return id;
9068 }
9069
9070 // ***************************************************************************
9071 #if COMPILER_LIKES_PRAGMA_MARK
9072 #pragma mark -
9073 #pragma mark - Sleep Proxy Server
9074 #endif
9075
9076 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
9077 {
9078 // If we see an ARP from a machine we think is sleeping, then either
9079 // (i) the machine has woken, or
9080 // (ii) it's just a stray old packet from before the machine slept
9081 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
9082 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
9083 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
9084 // 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*
9085 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
9086 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
9087
9088 rr->resrec.RecordType = kDNSRecordTypeUnique;
9089 rr->ProbeCount = DefaultProbeCountForTypeUnique;
9090
9091 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
9092 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
9093 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
9094 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
9095 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
9096 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
9097 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
9098 InitializeLastAPTime(m, rr);
9099 else
9100 {
9101 rr->AnnounceCount = InitialAnnounceCount;
9102 rr->ThisAPInterval = mDNSPlatformOneSecond;
9103 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
9104 SetNextAnnounceProbeTime(m, rr);
9105 }
9106 }
9107
9108 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
9109 {
9110 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
9111 AuthRecord *rr;
9112 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
9113 if (!intf) return;
9114
9115 mDNS_Lock(m);
9116
9117 // Pass 1:
9118 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
9119 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
9120 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
9121 // The times we might need to react to an ARP Announcement are:
9122 // (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
9123 // (ii) if it's a conflicting Announcement from another host
9124 // -- and we check for these in Pass 2 below.
9125 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
9126 {
9127 for (rr = m->ResourceRecords; rr; rr=rr->next)
9128 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
9129 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
9130 {
9131 static const char msg1[] = "ARP Req from owner -- re-probing";
9132 static const char msg2[] = "Ignoring ARP Request from ";
9133 static const char msg3[] = "Creating Local ARP Cache entry ";
9134 static const char msg4[] = "Answering ARP Request from ";
9135 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
9136 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
9137 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
9138 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
9139 intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
9140 if (msg == msg1) RestartARPProbing(m, rr);
9141 else if (msg == msg3) mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
9142 else if (msg == msg4) SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
9143 }
9144 }
9145
9146 // Pass 2:
9147 // 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.
9148 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
9149 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
9150 // 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.
9151 // If we see an apparently conflicting ARP, we check the sender hardware address:
9152 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
9153 // 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.
9154 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
9155 debugf("ARP from self for %.4a", &arp->tpa);
9156 else
9157 {
9158 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
9159 for (rr = m->ResourceRecords; rr; rr=rr->next)
9160 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
9161 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa))
9162 {
9163 RestartARPProbing(m, rr);
9164 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
9165 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
9166 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
9167 &arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
9168 else
9169 {
9170 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
9171 &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
9172 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
9173 }
9174 }
9175 }
9176
9177 mDNS_Unlock(m);
9178 }
9179
9180 /*
9181 // Option 1 is Source Link Layer Address Option
9182 // Option 2 is Target Link Layer Address Option
9183 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
9184 {
9185 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
9186 while (options < end)
9187 {
9188 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
9189 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
9190 options += options[1] * 8;
9191 }
9192 return mDNSNULL;
9193 }
9194 */
9195
9196 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
9197 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
9198 {
9199 AuthRecord *rr;
9200 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
9201 if (!intf) return;
9202
9203 mDNS_Lock(m);
9204
9205 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
9206 if (ndp->type == NDP_Sol)
9207 {
9208 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
9209 (void)end;
9210 for (rr = m->ResourceRecords; rr; rr=rr->next)
9211 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
9212 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
9213 {
9214 static const char msg1[] = "NDP Req from owner -- re-probing";
9215 static const char msg2[] = "Ignoring NDP Request from ";
9216 static const char msg3[] = "Creating Local NDP Cache entry ";
9217 static const char msg4[] = "Answering NDP Request from ";
9218 static const char msg5[] = "Answering NDP Probe from ";
9219 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
9220 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
9221 sha && mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
9222 spa && mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
9223 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
9224 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
9225 if (msg == msg1) RestartARPProbing(m, rr);
9226 else if (msg == msg3)
9227 {
9228 if (!(m->KnownBugs & mDNS_KnownBug_LimitedIPv6))
9229 mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
9230 }
9231 else if (msg == msg4) SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha );
9232 else if (msg == msg5) SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
9233 }
9234 }
9235
9236 // 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.
9237 if (mDNSSameEthAddress(sha, &intf->MAC))
9238 debugf("NDP from self for %.16a", &ndp->target);
9239 else
9240 {
9241 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
9242 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
9243 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
9244 // Hence it is the NDP target address we care about, not the actual packet source address.
9245 if (ndp->type == NDP_Adv) spa = &ndp->target;
9246 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
9247 for (rr = m->ResourceRecords; rr; rr=rr->next)
9248 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
9249 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa))
9250 {
9251 RestartARPProbing(m, rr);
9252 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
9253 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
9254 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
9255 else
9256 {
9257 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
9258 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
9259 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
9260 }
9261 }
9262 }
9263
9264 mDNS_Unlock(m);
9265 }
9266
9267 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
9268 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
9269 {
9270 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
9271 mDNSBool wake = mDNSfalse;
9272
9273 switch (protocol)
9274 {
9275 #define XX wake ? "Received" : "Ignoring", end-p
9276 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
9277 break;
9278
9279 case 0x06: {
9280 #define SSH_AsNumber 22
9281 static const mDNSIPPort SSH = { { SSH_AsNumber >> 8, SSH_AsNumber & 0xFF } };
9282
9283 // Plan to wake if
9284 // (a) RST is not set, AND
9285 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
9286 wake = (!(t->tcp.flags & 4) && (t->tcp.flags & 3) != 1);
9287
9288 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
9289 // except for ssh connections, where we'll wake for plain data packets too
9290 if (!mDNSSameIPPort(port, SSH) && !(t->tcp.flags & 2)) wake = mDNSfalse;
9291
9292 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
9293 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
9294 (t->tcp.flags & 2) ? " SYN" : "",
9295 (t->tcp.flags & 1) ? " FIN" : "",
9296 (t->tcp.flags & 4) ? " RST" : "");
9297 }
9298 break;
9299
9300 case 0x11: {
9301 #define ARD_AsNumber 3283
9302 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
9303 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
9304 if (udplen >= sizeof(UDPHeader))
9305 {
9306 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
9307 wake = mDNStrue;
9308
9309 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
9310 if (mDNSSameIPPort(port, IPSECPort))
9311 {
9312 // Specifically ignore NAT keepalive packets
9313 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
9314 else
9315 {
9316 // Skip over the Non-ESP Marker if present
9317 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
9318 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
9319 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
9320 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
9321 if ((ike->Version & 0x10) == 0x10)
9322 {
9323 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
9324 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
9325 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
9326 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
9327 }
9328 }
9329 }
9330
9331 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
9332 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
9333 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
9334 // UDP header (8 bytes)
9335 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
9336 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
9337
9338 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
9339 }
9340 }
9341 break;
9342
9343 case 0x3A: if (&t->bytes[len] <= end)
9344 {
9345 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
9346 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
9347 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
9348 }
9349 break;
9350
9351 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
9352 break;
9353 }
9354
9355 if (wake)
9356 {
9357 AuthRecord *rr, *r2;
9358
9359 mDNS_Lock(m);
9360 for (rr = m->ResourceRecords; rr; rr=rr->next)
9361 if (rr->resrec.InterfaceID == InterfaceID &&
9362 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
9363 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
9364 {
9365 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
9366 for (r2 = m->ResourceRecords; r2; r2=r2->next)
9367 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
9368 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
9369 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
9370 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
9371 break;
9372 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
9373 if (r2)
9374 {
9375 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
9376 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
9377 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
9378 }
9379 else
9380 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
9381 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
9382 }
9383 mDNS_Unlock(m);
9384 }
9385 }
9386
9387 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
9388 {
9389 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
9390 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
9391 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
9392 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
9393 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
9394
9395 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
9396 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
9397 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
9398 // since it points to a an address 14 bytes before pkt.
9399 const EthernetHeader *const eth = (const EthernetHeader *)p;
9400 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
9401 mDNSAddr src, dst;
9402 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
9403
9404 // Is ARP? Length must be at least 14 + 28 = 42 bytes
9405 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
9406 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
9407 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
9408 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
9409 {
9410 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
9411 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
9412 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
9413 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
9414 if (end >= trans + RequiredCapLen(pkt->v4.protocol))
9415 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
9416 }
9417 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
9418 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
9419 {
9420 const mDNSu8 *const trans = p + 54;
9421 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
9422 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
9423 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
9424 if (end >= trans + RequiredCapLen(pkt->v6.pro))
9425 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
9426 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
9427 }
9428 }
9429
9430 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
9431 {
9432 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d %#s",
9433 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, &m->nicelabel);
9434 }
9435
9436 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
9437 {
9438 if (result == mStatus_NameConflict)
9439 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
9440 else if (result == mStatus_MemFree)
9441 {
9442 if (m->SleepState)
9443 m->SPSState = 3;
9444 else
9445 {
9446 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
9447 if (m->SPSState)
9448 {
9449 domainlabel name;
9450 ConstructSleepProxyServerName(m, &name);
9451 mDNS_RegisterService(m, srs,
9452 &name, &SleepProxyServiceType, &localdomain,
9453 mDNSNULL, m->SPSSocket->port, // Host, port
9454 (mDNSu8 *)"", 1, // TXT data, length
9455 mDNSNULL, 0, // Subtypes (none)
9456 mDNSInterface_Any, // Interface ID
9457 SleepProxyServerCallback, mDNSNULL); // Callback and context
9458 }
9459 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
9460 }
9461 }
9462 }
9463
9464 // Called with lock held
9465 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower)
9466 {
9467 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
9468 mDNS_DropLockBeforeCallback();
9469
9470 // If turning off SPS, close our socket
9471 // (Do this first, BEFORE calling mDNS_DeregisterService below)
9472 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
9473
9474 // If turning off, or changing type, deregister old name
9475 if (m->SPSState == 1 && sps != m->SPSType)
9476 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
9477
9478 // Record our new SPS parameters
9479 m->SPSType = sps;
9480 m->SPSPortability = port;
9481 m->SPSMarginalPower = marginalpower;
9482 m->SPSTotalPower = totpower;
9483
9484 // If turning on, open socket and advertise service
9485 if (sps)
9486 {
9487 if (!m->SPSSocket)
9488 {
9489 m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
9490 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
9491 }
9492 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
9493 }
9494 else if (m->SPSState)
9495 {
9496 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
9497 m->NextScheduledSPS = m->timenow;
9498 }
9499 fail:
9500 mDNS_ReclaimLockAfterCallback();
9501 }
9502
9503 // ***************************************************************************
9504 #if COMPILER_LIKES_PRAGMA_MARK
9505 #pragma mark -
9506 #pragma mark - Startup and Shutdown
9507 #endif
9508
9509 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
9510 {
9511 if (storage && numrecords)
9512 {
9513 mDNSu32 i;
9514 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
9515 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
9516 storage[numrecords-1].next = m->rrcache_free;
9517 m->rrcache_free = storage;
9518 m->rrcache_size += numrecords;
9519 }
9520 }
9521
9522 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
9523 {
9524 mDNS_Lock(m);
9525 mDNS_GrowCache_internal(m, storage, numrecords);
9526 mDNS_Unlock(m);
9527 }
9528
9529 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
9530 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
9531 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
9532 {
9533 mDNSu32 slot;
9534 mDNSs32 timenow;
9535 mStatus result;
9536
9537 if (!rrcachestorage) rrcachesize = 0;
9538
9539 m->p = p;
9540 m->KnownBugs = 0;
9541 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
9542 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
9543 m->DivertMulticastAdvertisements = mDNSfalse;
9544 m->mDNSPlatformStatus = mStatus_Waiting;
9545 m->UnicastPort4 = zeroIPPort;
9546 m->UnicastPort6 = zeroIPPort;
9547 m->PrimaryMAC = zeroEthAddr;
9548 m->MainCallback = Callback;
9549 m->MainContext = Context;
9550 m->rec.r.resrec.RecordType = 0;
9551
9552 // For debugging: To catch and report locking failures
9553 m->mDNS_busy = 0;
9554 m->mDNS_reentrancy = 0;
9555 m->ShutdownTime = 0;
9556 m->lock_rrcache = 0;
9557 m->lock_Questions = 0;
9558 m->lock_Records = 0;
9559
9560 // Task Scheduling variables
9561 result = mDNSPlatformTimeInit();
9562 if (result != mStatus_NoError) return(result);
9563 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
9564 timenow = mDNS_TimeNow_NoLock(m);
9565
9566 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
9567 m->timenow_last = timenow;
9568 m->NextScheduledEvent = timenow;
9569 m->SuppressSending = timenow;
9570 m->NextCacheCheck = timenow + 0x78000000;
9571 m->NextScheduledQuery = timenow + 0x78000000;
9572 m->NextScheduledProbe = timenow + 0x78000000;
9573 m->NextScheduledResponse = timenow + 0x78000000;
9574 m->NextScheduledNATOp = timenow + 0x78000000;
9575 m->NextScheduledSPS = timenow + 0x78000000;
9576 m->RandomQueryDelay = 0;
9577 m->RandomReconfirmDelay = 0;
9578 m->PktNum = 0;
9579 m->LocalRemoveEvents = mDNSfalse;
9580 m->SleepState = SleepState_Awake;
9581 m->SleepSeqNum = 0;
9582 m->SystemWakeOnLANEnabled = mDNSfalse;
9583 m->SentSleepProxyRegistration = mDNSfalse;
9584 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
9585 m->DelaySleep = 0;
9586 m->SleepLimit = 0;
9587
9588 // These fields only required for mDNS Searcher...
9589 m->Questions = mDNSNULL;
9590 m->NewQuestions = mDNSNULL;
9591 m->CurrentQuestion = mDNSNULL;
9592 m->LocalOnlyQuestions = mDNSNULL;
9593 m->NewLocalOnlyQuestions = mDNSNULL;
9594 m->rrcache_size = 0;
9595 m->rrcache_totalused = 0;
9596 m->rrcache_active = 0;
9597 m->rrcache_report = 10;
9598 m->rrcache_free = mDNSNULL;
9599
9600 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
9601 {
9602 m->rrcache_hash[slot] = mDNSNULL;
9603 m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
9604 }
9605
9606 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
9607
9608 // Fields below only required for mDNS Responder...
9609 m->hostlabel.c[0] = 0;
9610 m->nicelabel.c[0] = 0;
9611 m->MulticastHostname.c[0] = 0;
9612 m->HIHardware.c[0] = 0;
9613 m->HISoftware.c[0] = 0;
9614 m->ResourceRecords = mDNSNULL;
9615 m->DuplicateRecords = mDNSNULL;
9616 m->NewLocalRecords = mDNSNULL;
9617 m->CurrentRecord = mDNSNULL;
9618 m->HostInterfaces = mDNSNULL;
9619 m->ProbeFailTime = 0;
9620 m->NumFailedProbes = 0;
9621 m->SuppressProbes = 0;
9622
9623 #ifndef UNICAST_DISABLED
9624 m->NextuDNSEvent = timenow + 0x78000000;
9625 m->NextSRVUpdate = timenow + 0x78000000;
9626
9627 m->DNSServers = mDNSNULL;
9628
9629 m->Router = zeroAddr;
9630 m->AdvertisedV4 = zeroAddr;
9631 m->AdvertisedV6 = zeroAddr;
9632
9633 m->AuthInfoList = mDNSNULL;
9634
9635 m->ReverseMap.ThisQInterval = -1;
9636 m->StaticHostname.c[0] = 0;
9637 m->FQDN.c[0] = 0;
9638 m->Hostnames = mDNSNULL;
9639 m->AutoTunnelHostAddr.b[0] = 0;
9640 m->AutoTunnelHostAddrActive = mDNSfalse;
9641 m->AutoTunnelLabel.c[0] = 0;
9642
9643 m->StartWABQueries = mDNSfalse;
9644 m->RegisterAutoTunnel6 = mDNStrue;
9645
9646 // NAT traversal fields
9647 m->NATTraversals = mDNSNULL;
9648 m->CurrentNATTraversal = mDNSNULL;
9649 m->retryIntervalGetAddr = 0; // delta between time sent and retry
9650 m->retryGetAddr = timenow + 0x78000000; // absolute time when we retry
9651 m->ExternalAddress = zerov4Addr;
9652
9653 m->NATMcastRecvskt = mDNSNULL;
9654 m->LastNATupseconds = 0;
9655 m->LastNATReplyLocalTime = timenow;
9656 m->LastNATMapResultCode = NATErr_None;
9657
9658 m->UPnPInterfaceID = 0;
9659 m->SSDPSocket = mDNSNULL;
9660 m->SSDPWANPPPConnection = mDNSfalse;
9661 m->UPnPRouterPort = zeroIPPort;
9662 m->UPnPSOAPPort = zeroIPPort;
9663 m->UPnPRouterURL = mDNSNULL;
9664 m->UPnPWANPPPConnection = mDNSfalse;
9665 m->UPnPSOAPURL = mDNSNULL;
9666 m->UPnPRouterAddressString = mDNSNULL;
9667 m->UPnPSOAPAddressString = mDNSNULL;
9668 m->SPSType = 0;
9669 m->SPSPortability = 0;
9670 m->SPSMarginalPower = 0;
9671 m->SPSTotalPower = 0;
9672 m->SPSState = 0;
9673 m->SPSProxyListChanged = mDNSNULL;
9674 m->SPSSocket = mDNSNULL;
9675 m->SPSBrowseCallback = mDNSNULL;
9676 m->ProxyRecords = 0;
9677
9678 #endif
9679
9680 #if APPLE_OSX_mDNSResponder
9681 m->TunnelClients = mDNSNULL;
9682
9683 #if ! NO_WCF
9684 CHECK_WCF_FUNCTION(WCFConnectionNew)
9685 {
9686 m->WCF = WCFConnectionNew();
9687 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
9688 }
9689 #endif
9690
9691 #endif
9692
9693 result = mDNSPlatformInit(m);
9694
9695 #ifndef UNICAST_DISABLED
9696 // It's better to do this *after* the platform layer has set up the
9697 // interface list and security credentials
9698 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
9699 #endif
9700
9701 return(result);
9702 }
9703
9704 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
9705 {
9706 if (m->SPSState == 1)
9707 {
9708 domainlabel name, newname;
9709 domainname type, domain;
9710 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
9711 ConstructSleepProxyServerName(m, &newname);
9712 if (!SameDomainLabelCS(name.c, newname.c))
9713 {
9714 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
9715 // When SleepProxyServerCallback gets the mStatus_MemFree message,
9716 // it will reregister the service under the new name
9717 m->SPSState = 2;
9718 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
9719 }
9720 }
9721
9722 if (m->MainCallback)
9723 m->MainCallback(m, mStatus_ConfigChanged);
9724 }
9725
9726 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
9727 {
9728 (void)m; // unused
9729 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
9730 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
9731 }
9732
9733 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
9734 {
9735 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
9736 cr->resrec.rrtype == kDNSType_A ||
9737 cr->resrec.rrtype == kDNSType_AAAA ||
9738 cr->resrec.rrtype == kDNSType_SRV;
9739
9740 (void) lameduck;
9741 (void) ptr;
9742 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
9743 purge ? "purging" : "reconfirming",
9744 lameduck ? "lame duck" : "new",
9745 ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
9746
9747 if (purge)
9748 {
9749 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
9750 mDNS_PurgeCacheResourceRecord(m, cr);
9751 }
9752 else
9753 {
9754 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
9755 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
9756 }
9757 }
9758
9759 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
9760 {
9761 const mDNSu32 slot = HashSlot(&q->qname);
9762 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
9763 CacheRecord *rp;
9764
9765 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
9766 {
9767 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
9768 {
9769 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
9770 mDNS_PurgeCacheResourceRecord(m, rp);
9771 }
9772 }
9773 }
9774
9775 mDNSlocal void CacheRecordResetDNSServer(mDNS *const m, DNSQuestion *q, DNSServer *new)
9776 {
9777 const mDNSu32 slot = HashSlot(&q->qname);
9778 CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
9779 CacheRecord *rp;
9780 mDNSBool found = mDNSfalse;
9781 mDNSBool foundNew = mDNSfalse;
9782 DNSServer *old = q->qDNSServer;
9783 mDNSBool newQuestion = IsQuestionNew(m, q);
9784 DNSQuestion *qptr;
9785
9786 // This function is called when the DNSServer is updated to the new question. There may already be
9787 // some cache entries matching the old DNSServer and/or new DNSServer. There are four cases. In the
9788 // following table, "Yes" denotes that a cache entry was found for old/new DNSServer.
9789 //
9790 // old DNSServer new DNSServer
9791 //
9792 // Case 1 Yes Yes
9793 // Case 2 No Yes
9794 // Case 3 Yes No
9795 // Case 4 No No
9796 //
9797 // Case 1: There are cache entries for both old and new DNSServer. We handle this case by simply
9798 // expiring the old Cache entries, deliver a RMV event (if an ADD event was delivered before)
9799 // followed by the ADD event of the cache entries corresponding to the new server. This
9800 // case happens when we pick a DNSServer, issue a query and get a valid response and create
9801 // cache entries after which it stops responding. Another query (non-duplicate) picks a different
9802 // DNSServer and creates identical cache entries (perhaps through records in Additional records).
9803 // Now if the first one expires and tries to pick the new DNSServer (the original DNSServer
9804 // is not responding) we will find cache entries corresponding to both DNSServers.
9805 //
9806 // Case 2: There are no cache entries for the old DNSServer but there are some for the new DNSServer.
9807 // This means we should deliver an ADD event. Normally ADD events are delivered by
9808 // AnswerNewQuestion if it is a new question. So, we check to see if it is a new question
9809 // and if so, leave it to AnswerNewQuestion to deliver it. Otherwise, we use
9810 // AnswerQuestionsForDNSServerChanges to deliver the ADD event. This case happens when a
9811 // question picks a DNS server for which AnswerNewQuestion could not deliver an answer even
9812 // though there were potential cache entries but DNSServer did not match. Now when we
9813 // pick a new DNSServer, those cache entries may answer this question.
9814 //
9815 // Case 3: There are the cache entries for the old DNSServer but none for the new. We just move
9816 // the old cache entries to point to the new DNSServer and the caller is expected to
9817 // do a purge or reconfirm to delete or validate the RDATA. We don't need to do anything
9818 // special for delivering ADD events, as it should have been done/will be done by
9819 // AnswerNewQuestion. This case happens when we picked a DNSServer, sent the query and
9820 // got a response and the cache is expired now and we are reissuing the question but the
9821 // original DNSServer does not respond.
9822 //
9823 // Case 4: There are no cache entries either for the old or for the new DNSServer. There is nothing
9824 // much we can do here.
9825 //
9826 // Case 2 and 3 are the most common while case 4 is possible when no DNSServers are working. Case 1
9827 // is relatively less likely to happen in practice
9828
9829 // Temporarily set the DNSServer to look for the matching records for the new DNSServer.
9830 q->qDNSServer = new;
9831 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
9832 {
9833 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
9834 {
9835 LogInfo("CacheRecordResetDNSServer: Found cache record %##s for new DNSServer address: %#a", rp->resrec.name->c,
9836 (rp->resrec.rDNSServer != mDNSNULL ? &rp->resrec.rDNSServer->addr : mDNSNULL));
9837 foundNew = mDNStrue;
9838 break;
9839 }
9840 }
9841 q->qDNSServer = old;
9842
9843 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
9844 {
9845 if (SameNameRecordAnswersQuestion(&rp->resrec, q))
9846 {
9847 // Case1
9848 found = mDNStrue;
9849 if (foundNew)
9850 {
9851 LogInfo("CacheRecordResetDNSServer: Flushing Resourcerecord %##s, before:%#a, after:%#a", rp->resrec.name->c,
9852 (rp->resrec.rDNSServer != mDNSNULL ? &rp->resrec.rDNSServer->addr : mDNSNULL),
9853 (new != mDNSNULL ? &new->addr : mDNSNULL));
9854 mDNS_PurgeCacheResourceRecord(m, rp);
9855 if (newQuestion)
9856 {
9857 // "q" is not a duplicate question. If it is a newQuestion, then the CRActiveQuestion can't be
9858 // possibly set as it is set only when we deliver the ADD event to the question.
9859 if (rp->CRActiveQuestion != mDNSNULL)
9860 {
9861 LogMsg("CacheRecordResetDNSServer: ERROR!!: CRActiveQuestion %p set, current question %p, name %##s", rp->CRActiveQuestion, q, q->qname.c);
9862 rp->CRActiveQuestion = mDNSNULL;
9863 }
9864 // if this is a new question, then we never delivered an ADD yet, so don't deliver the RMV.
9865 continue;
9866 }
9867 }
9868 LogInfo("CacheRecordResetDNSServer: resetting cache record %##s DNSServer address before:%#a,"
9869 " after:%#a, CRActiveQuestion %p", rp->resrec.name->c, (rp->resrec.rDNSServer != mDNSNULL ?
9870 &rp->resrec.rDNSServer->addr : mDNSNULL), (new != mDNSNULL ? &new->addr : mDNSNULL),
9871 rp->CRActiveQuestion);
9872 // Though we set it to the new DNS server, the caller is *assumed* to do either a purge
9873 // or reconfirm or send out questions to the "new" server to verify whether the cached
9874 // RDATA is valid
9875 rp->resrec.rDNSServer = new;
9876 }
9877 }
9878
9879 // Case 1 and Case 2
9880 if ((found && foundNew) || (!found && foundNew))
9881 {
9882 if (newQuestion)
9883 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
9884 else if (QuerySuppressed(q))
9885 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for suppressed question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
9886 else
9887 {
9888 LogInfo("CacheRecordResetDNSServer: deliverAddEvents set for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
9889 q->deliverAddEvents = mDNStrue;
9890 for (qptr = q->next; qptr; qptr = qptr->next)
9891 if (qptr->DuplicateOf == q) qptr->deliverAddEvents = mDNStrue;
9892 }
9893 return;
9894 }
9895
9896 // Case 3 and Case 4
9897 return;
9898 }
9899
9900 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
9901 {
9902 DNSQuestion *qptr;
9903
9904 // 1. Whenever we change the DNS server, we change the message identifier also so that response
9905 // from the old server is not accepted as a response from the new server but only messages
9906 // from the new server are accepted as valid responses. We do it irrespective of whether "new"
9907 // is NULL or not. It is possible that we send two queries, no responses, pick a new DNS server
9908 // which is NULL and now the response comes back and will try to penalize the DNS server which
9909 // is NULL. By setting the messageID here, we will not accept that as a valid response.
9910
9911 q->TargetQID = mDNS_NewMessageID(m);
9912
9913 // 2. Move the old cache records to point them at the new DNSServer so that we can deliver the ADD/RMV events
9914 // appropriately. At any point in time, we want all the cache records point only to one DNSServer for a given
9915 // question. "DNSServer" here is the DNSServer object and not the DNS server itself. It is possible to
9916 // have the same DNS server address in two objects, one scoped and another not scoped. But, the cache is per
9917 // DNSServer object. By maintaining the question and the cache entries point to the same DNSServer
9918 // always, the cache maintenance and delivery of ADD/RMV events becomes simpler.
9919 //
9920 // CacheRecordResetDNSServer should be called only once for the non-duplicate question as once the cache
9921 // entries are moved to point to the new DNSServer, we don't need to call it for the duplicate question
9922 // and it is wrong to call for the duplicate question as it's decision to mark deliverAddevents will be
9923 // incorrect.
9924
9925 if (q->DuplicateOf)
9926 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
9927 else
9928 CacheRecordResetDNSServer(m, q, new);
9929
9930 // 3. Make sure all the duplicate questions point to the same DNSServer so that delivery
9931 // of events for all of them are consistent. Duplicates for a question are always inserted
9932 // after in the list.
9933 q->qDNSServer = new;
9934 for (qptr = q->next ; qptr; qptr = qptr->next)
9935 {
9936 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
9937 }
9938 }
9939
9940 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
9941 {
9942 mDNSu32 slot;
9943 CacheGroup *cg;
9944 CacheRecord *cr;
9945
9946 mDNSAddr v4, v6, r;
9947 domainname fqdn;
9948 DNSServer *ptr, **p = &m->DNSServers;
9949 const DNSServer *oldServers = m->DNSServers;
9950 DNSQuestion *q;
9951
9952 debugf("uDNS_SetupDNSConfig: entry");
9953
9954 // Let the platform layer get the current DNS information
9955 // The m->StartWABQueries boolean is so that we lazily get the search domain list only on-demand
9956 // and start the domain enumeration queries. (no need to hit the network with domain enumeration
9957 // queries until we actually need that information).
9958
9959 uDNS_SetupSearchDomains(m, m->StartWABQueries ? (UDNS_START_WAB_QUERY | UDNS_START_CF_QUERY) :
9960 (UDNS_START_CF_QUERY));
9961
9962 mDNS_Lock(m);
9963
9964 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
9965 {
9966 ptr->penaltyTime = 0;
9967 ptr->flags |= DNSServer_FlagDelete;
9968 }
9969
9970 mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL);
9971
9972 // Mark the records to be flushed that match a new resolver. We need to do this before
9973 // we walk the questions below where we change the DNSServer pointer of the cache
9974 // record
9975 FORALL_CACHERECORDS(slot, cg, cr)
9976 {
9977 if (cr->resrec.InterfaceID) continue;
9978
9979 // We just mark them for purge or reconfirm. We can't affect the DNSServer pointer
9980 // here as the code below that calls CacheRecordResetDNSServer relies on this
9981 //
9982 // The new DNSServer may be a scoped or non-scoped one. We use the active question's
9983 // InterfaceID for looking up the right DNS server
9984 ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL);
9985
9986 // Purge or Reconfirm if this cache entry would use the new DNS server
9987 if (ptr && (ptr != cr->resrec.rDNSServer))
9988 {
9989 // As the DNSServers for this cache record is not the same anymore, we don't
9990 // want any new questions to pick this old value
9991 if (cr->CRActiveQuestion == mDNSNULL)
9992 {
9993 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s", CRDisplayString(m, cr));
9994 mDNS_PurgeCacheResourceRecord(m, cr);
9995 }
9996 else
9997 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
9998 }
9999 }
10000 // Update our qDNSServer pointers before we go and free the DNSServer object memory
10001 for (q = m->Questions; q; q=q->next)
10002 if (!mDNSOpaque16IsZero(q->TargetQID))
10003 {
10004 DNSServer *s, *t;
10005 DNSQuestion *qptr;
10006 if (q->DuplicateOf) continue;
10007 SetValidDNSServers(m, q);
10008 q->triedAllServersOnce = 0;
10009 s = GetServerForQuestion(m, q);
10010 t = q->qDNSServer;
10011 if (t != s)
10012 {
10013 // If DNS Server for this question has changed, reactivate it
10014 debugf("uDNS_SetupDNSConfig: Updating DNS Server from %p %#a:%d (%##s) to %p %#a:%d (%##s) for %##s (%s)",
10015 t, t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), t ? t->domain.c : (mDNSu8*)"",
10016 s, s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), s ? s->domain.c : (mDNSu8*)"",
10017 q->qname.c, DNSTypeName(q->qtype));
10018
10019 // After we reset the DNSServer pointer on the cache records here, three things could happen:
10020 //
10021 // 1) The query gets sent out and when the actual response comes back later it is possible
10022 // that the response has the same RDATA, in which case we update our cache entry.
10023 // If the response is different, then the entry will expire and a new entry gets added.
10024 // For the latter case to generate a RMV followed by ADD events, we need to reset the DNS
10025 // server here to match the question and the cache record.
10026 //
10027 // 2) We might have marked the cache entries for purge above and for us to be able to generate the RMV
10028 // events for the questions, the DNSServer on the question should match the Cache Record
10029 //
10030 // 3) We might have marked the cache entries for reconfirm above, for which we send the query out which is
10031 // the same as the first case above.
10032
10033 DNSServerChangeForQuestion(m, q, s);
10034 q->unansweredQueries = 0;
10035 // We still need to pick a new DNSServer for the questions that have been
10036 // suppressed, but it is wrong to activate the query as DNS server change
10037 // could not possibly change the status of SuppressUnusable questions
10038 if (!QuerySuppressed(q))
10039 {
10040 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
10041 ActivateUnicastQuery(m, q, mDNStrue);
10042 // ActivateUnicastQuery is called for duplicate questions also as it does something
10043 // special for AutoTunnel questions
10044 for (qptr = q->next ; qptr; qptr = qptr->next)
10045 {
10046 if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
10047 }
10048 }
10049 }
10050 else
10051 {
10052 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
10053 q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), q->DuplicateOf, q->SuppressUnusable);
10054 for (qptr = q->next ; qptr; qptr = qptr->next)
10055 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
10056 }
10057 }
10058
10059 while (*p)
10060 {
10061 if (((*p)->flags & DNSServer_FlagDelete) != 0)
10062 {
10063 // Scan our cache, looking for uDNS records that we would have queried this server for.
10064 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
10065 // different DNS servers can give different answers to the same question.
10066 ptr = *p;
10067 FORALL_CACHERECORDS(slot, cg, cr)
10068 {
10069 if (cr->resrec.InterfaceID) continue;
10070 if (cr->resrec.rDNSServer == ptr)
10071 {
10072 // If we don't have an active question for this cache record, neither Purge can
10073 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
10074 // pointer on the record NULL so that we don't point to freed memory (We might dereference
10075 // DNSServer pointers from resource record for logging purposes).
10076 //
10077 // If there is an active question, point to its DNSServer as long as it does not point to the
10078 // freed one. We already went through the questions above and made them point at either the
10079 // new server or NULL if there is no server and also affected the cache entries that match
10080 // this question. Hence, whenever we hit a resource record with a DNSServer that is just
10081 // about to be deleted, we should never have an active question. The code below just tries to
10082 // be careful logging messages if we ever hit this case.
10083
10084 if (cr->CRActiveQuestion)
10085 {
10086 DNSQuestion *qptr = cr->CRActiveQuestion;
10087 if (qptr->qDNSServer == mDNSNULL)
10088 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) with DNSServer Address NULL, Server to be deleted %#a",
10089 CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), &ptr->addr);
10090 else
10091 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) DNSServer Address %#a, Server to be deleted %#a",
10092 CRDisplayString(m, cr), qptr->qname.c, DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr, &ptr->addr);
10093
10094 if (qptr->qDNSServer == ptr)
10095 {
10096 qptr->validDNSServers = zeroOpaque64;
10097 qptr->qDNSServer = mDNSNULL;
10098 cr->resrec.rDNSServer = mDNSNULL;
10099 }
10100 else
10101 {
10102 cr->resrec.rDNSServer = qptr->qDNSServer;
10103 }
10104 }
10105 else
10106 {
10107 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
10108 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
10109 cr->resrec.rDNSServer = mDNSNULL;
10110 }
10111
10112 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
10113 }
10114 }
10115 *p = (*p)->next;
10116 debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
10117 mDNSPlatformMemFree(ptr);
10118 NumUnicastDNSServers--;
10119 }
10120 else
10121 {
10122 (*p)->flags &= ~DNSServer_FlagNew;
10123 p = &(*p)->next;
10124 }
10125 }
10126
10127 // 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).
10128 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
10129 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
10130 // 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.
10131 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
10132 {
10133 int count = 0;
10134 FORALL_CACHERECORDS(slot, cg, cr) if (!cr->resrec.InterfaceID) { mDNS_PurgeCacheResourceRecord(m, cr); count++; }
10135 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
10136 m->DNSServers ? "DNS server became" : "No DNS servers", count);
10137
10138 // Force anything that needs to get zone data to get that information again
10139 RestartRecordGetZoneData(m);
10140 }
10141
10142 // Did our FQDN change?
10143 if (!SameDomainName(&fqdn, &m->FQDN))
10144 {
10145 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
10146
10147 AssignDomainName(&m->FQDN, &fqdn);
10148
10149 if (m->FQDN.c[0])
10150 {
10151 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
10152 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
10153 }
10154 }
10155
10156 mDNS_Unlock(m);
10157
10158 // handle router and primary interface changes
10159 v4 = v6 = r = zeroAddr;
10160 v4.type = r.type = mDNSAddrType_IPv4;
10161
10162 if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
10163 {
10164 mDNS_SetPrimaryInterfaceInfo(m,
10165 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
10166 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
10167 !mDNSIPv4AddressIsZero(r .ip.v4) ? &r : mDNSNULL);
10168 }
10169 else
10170 {
10171 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
10172 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
10173 }
10174
10175 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
10176 return mStatus_NoError;
10177 }
10178
10179 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
10180 {
10181 m->mDNSPlatformStatus = result;
10182 if (m->MainCallback)
10183 {
10184 mDNS_Lock(m);
10185 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
10186 m->MainCallback(m, mStatus_NoError);
10187 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
10188 mDNS_Unlock(m);
10189 }
10190 }
10191
10192 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
10193 {
10194 m->CurrentRecord = start;
10195 while (m->CurrentRecord)
10196 {
10197 AuthRecord *rr = m->CurrentRecord;
10198 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
10199 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
10200 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
10201 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
10202 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
10203 else if (rr->AnnounceCount > 1)
10204 {
10205 rr->AnnounceCount = 1;
10206 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
10207 }
10208 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10209 // new records could have been added to the end of the list as a result of that call.
10210 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10211 m->CurrentRecord = rr->next;
10212 }
10213 }
10214
10215 mDNSexport void mDNS_StartExit(mDNS *const m)
10216 {
10217 NetworkInterfaceInfo *intf;
10218 AuthRecord *rr;
10219
10220 mDNS_Lock(m);
10221
10222 LogInfo("mDNS_StartExit");
10223 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
10224
10225 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0);
10226
10227 #if APPLE_OSX_mDNSResponder
10228 #if ! NO_WCF
10229 CHECK_WCF_FUNCTION(WCFConnectionDealloc)
10230 {
10231 if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
10232 }
10233 #endif
10234 #endif
10235
10236 #ifndef UNICAST_DISABLED
10237 {
10238 SearchListElem *s;
10239 SuspendLLQs(m);
10240 // Don't need to do SleepRecordRegistrations() here
10241 // because we deregister all records and services later in this routine
10242 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
10243
10244 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
10245 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
10246 // and we may crash because the list still contains dangling pointers.
10247 for (s = SearchList; s; s = s->next)
10248 while (s->AuthRecs)
10249 {
10250 ARListElem *dereg = s->AuthRecs;
10251 s->AuthRecs = s->AuthRecs->next;
10252 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
10253 }
10254 }
10255 #endif
10256
10257 for (intf = m->HostInterfaces; intf; intf = intf->next)
10258 if (intf->Advertise)
10259 DeadvertiseInterface(m, intf);
10260
10261 // Shut down all our active NAT Traversals
10262 while (m->NATTraversals)
10263 {
10264 NATTraversalInfo *t = m->NATTraversals;
10265 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
10266
10267 // After stopping the NAT Traversal, we zero out the fields.
10268 // This has particularly important implications for our AutoTunnel records --
10269 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
10270 // handlers to just turn around and attempt to re-register those same records.
10271 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
10272 // to not do this.
10273 t->ExternalAddress = zerov4Addr;
10274 t->ExternalPort = zeroIPPort;
10275 t->RequestedPort = zeroIPPort;
10276 t->Lifetime = 0;
10277 t->Result = mStatus_NoError;
10278 }
10279
10280 // Make sure there are nothing but deregistering records remaining in the list
10281 if (m->CurrentRecord)
10282 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10283
10284 // We're in the process of shutting down, so queries, etc. are no longer available.
10285 // Consequently, determining certain information, e.g. the uDNS update server's IP
10286 // address, will not be possible. The records on the main list are more likely to
10287 // already contain such information, so we deregister the duplicate records first.
10288 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
10289 DeregLoop(m, m->DuplicateRecords);
10290 LogInfo("mDNS_StartExit: Deregistering resource records");
10291 DeregLoop(m, m->ResourceRecords);
10292
10293 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
10294 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
10295 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
10296 {
10297 m->NextScheduledResponse = m->timenow;
10298 m->SuppressSending = 0;
10299 }
10300
10301 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
10302 else LogInfo("mDNS_StartExit: No deregistering records remain");
10303
10304 for (rr = m->DuplicateRecords; rr; rr = rr->next)
10305 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
10306
10307 // If any deregistering records remain, send their deregistration announcements before we exit
10308 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
10309
10310 mDNS_Unlock(m);
10311
10312 LogInfo("mDNS_StartExit: done");
10313 }
10314
10315 mDNSexport void mDNS_FinalExit(mDNS *const m)
10316 {
10317 mDNSu32 rrcache_active = 0;
10318 mDNSu32 rrcache_totalused = 0;
10319 mDNSu32 slot;
10320 AuthRecord *rr;
10321
10322 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
10323 mDNSPlatformClose(m);
10324
10325 rrcache_totalused = m->rrcache_totalused;
10326 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
10327 {
10328 while (m->rrcache_hash[slot])
10329 {
10330 CacheGroup *cg = m->rrcache_hash[slot];
10331 while (cg->members)
10332 {
10333 CacheRecord *cr = cg->members;
10334 cg->members = cg->members->next;
10335 if (cr->CRActiveQuestion) rrcache_active++;
10336 ReleaseCacheRecord(m, cr);
10337 }
10338 cg->rrcache_tail = &cg->members;
10339 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
10340 }
10341 }
10342 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
10343 if (rrcache_active != m->rrcache_active)
10344 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
10345
10346 for (rr = m->ResourceRecords; rr; rr = rr->next)
10347 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
10348
10349 LogInfo("mDNS_FinalExit: done");
10350 }