1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2006 Apple Computer, Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
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.
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).
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.)
39 #include "DNSCommon.h" // Defines general DNS untility routines
40 #include "uDNS.h" // Defines entry points into unicast-specific routines
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)
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)
57 #if APPLE_OSX_mDNSResponder
59 #include <WebFilterDNS/WebFilterDNS.h>
62 WCFConnection
*WCFConnectionNew(void) __attribute__((weak_import
));
63 void WCFConnectionDealloc(WCFConnection
* c
) __attribute__((weak_import
));
65 // Do we really need to define a macro for "if"?
66 #define CHECK_WCF_FUNCTION(X) if (X)
72 #endif // APPLE_OSX_mDNSResponder
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
);
79 // ***************************************************************************
80 #if COMPILER_LIKES_PRAGMA_MARK
81 #pragma mark - Program Constants
87 // Any records bigger than this are considered 'large' records
88 #define SmallRecordLimit 1024
90 #define kMaxUpdateCredits 10
91 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
93 mDNSexport
const char *const mDNS_DomainTypeNames
[] =
95 "b._dns-sd._udp.", // Browse
96 "db._dns-sd._udp.", // Default Browse
97 "lb._dns-sd._udp.", // Automatic Browse
98 "r._dns-sd._udp.", // Registration
99 "dr._dns-sd._udp." // Default Registration
102 #ifdef UNICAST_DISABLED
103 #define uDNS_IsActiveQuery(q, u) mDNSfalse
106 // ***************************************************************************
107 #if COMPILER_LIKES_PRAGMA_MARK
109 #pragma mark - General Utility Functions
112 mDNSexport
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
114 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
115 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
118 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1) *(long*)0 = 0;
121 if (ActiveQuestion(q
))
123 // Depending on whether this is a multicast or unicast question we want to set either:
124 // m->NextScheduledQuery = NextQSendTime(q) or
125 // m->NextuDNSEvent = NextQSendTime(q)
126 mDNSs32
*const timer
= mDNSOpaque16IsZero(q
->TargetQID
) ? &m
->NextScheduledQuery
: &m
->NextuDNSEvent
;
127 if (*timer
- NextQSendTime(q
) > 0)
128 *timer
= NextQSendTime(q
);
132 mDNSexport CacheGroup
*CacheGroupForName(const mDNS
*const m
, const mDNSu32 slot
, const mDNSu32 namehash
, const domainname
*const name
)
135 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
136 if (cg
->namehash
== namehash
&& SameDomainName(cg
->name
, name
))
141 mDNSlocal CacheGroup
*CacheGroupForRecord(const mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
143 return(CacheGroupForName(m
, slot
, rr
->namehash
, rr
->name
));
146 mDNSexport mDNSBool
mDNS_AddressIsLocalSubnet(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, const mDNSAddr
*addr
)
148 NetworkInterfaceInfo
*intf
;
150 if (addr
->type
== mDNSAddrType_IPv4
)
152 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
153 if (mDNSv4AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
154 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
155 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
156 if (((intf
->ip
.ip
.v4
.NotAnInteger
^ addr
->ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0)
160 if (addr
->type
== mDNSAddrType_IPv6
)
162 if (mDNSv6AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
163 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
164 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
165 if ((((intf
->ip
.ip
.v6
.l
[0] ^ addr
->ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
166 (((intf
->ip
.ip
.v6
.l
[1] ^ addr
->ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
167 (((intf
->ip
.ip
.v6
.l
[2] ^ addr
->ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
168 (((intf
->ip
.ip
.v6
.l
[3] ^ addr
->ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0))
175 mDNSlocal NetworkInterfaceInfo
*FirstInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
177 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
178 while (intf
&& intf
->InterfaceID
!= InterfaceID
) intf
= intf
->next
;
182 mDNSexport
char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
184 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
185 return(intf
? intf
->ifname
: mDNSNULL
);
188 // For a single given DNSQuestion, deliver an add/remove result for the single given AuthRecord
189 // Used by AnswerAllLocalQuestionsWithLocalAuthRecord() and AnswerNewLocalOnlyQuestion()
190 mDNSlocal
void AnswerLocalQuestionWithLocalAuthRecord(mDNS
*const m
, DNSQuestion
*q
, AuthRecord
*rr
, QC_result AddRecord
)
192 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
193 if (!(rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
))
195 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
196 AddRecord
? "Add" : "Rmv", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
200 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
201 if (AddRecord
) rr
->AnsweredLocalQ
= mDNStrue
;
202 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
203 if (q
->QuestionCallback
&& !q
->NoAnswer
)
205 q
->CurrentAnswers
+= AddRecord
? 1 : -1;
206 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
208 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
211 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
212 // delivers the appropriate add/remove events to listening questions:
213 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
214 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
215 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
216 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
217 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
219 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
220 // and by mDNS_Deregister_internal()
222 mDNSlocal
void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
224 if (m
->CurrentQuestion
)
225 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
226 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
228 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
229 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
231 DNSQuestion
*q
= m
->CurrentQuestion
;
232 m
->CurrentQuestion
= q
->next
;
233 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
234 AnswerLocalQuestionWithLocalAuthRecord(m
, q
, rr
, AddRecord
); // MUST NOT dereference q again
237 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
238 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
240 m
->CurrentQuestion
= m
->Questions
;
241 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
243 DNSQuestion
*q
= m
->CurrentQuestion
;
244 m
->CurrentQuestion
= q
->next
;
245 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
246 AnswerLocalQuestionWithLocalAuthRecord(m
, q
, rr
, AddRecord
); // MUST NOT dereference q again
250 m
->CurrentQuestion
= mDNSNULL
;
253 // ***************************************************************************
254 #if COMPILER_LIKES_PRAGMA_MARK
256 #pragma mark - Resource Record Utility Functions
259 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
261 #define ResourceRecordIsValidAnswer(RR) ( ((RR)-> resrec.RecordType & kDNSRecordTypeActiveMask) && \
262 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
263 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
264 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
266 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
267 (ResourceRecordIsValidAnswer(RR) && \
268 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
270 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
271 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
273 #define InitialAnnounceCount ((mDNSu8)8)
275 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
276 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
277 // and then if the machine fails to wake, 3 goodbye packets).
278 #define GoodbyeCount ((mDNSu8)3)
279 #define WakeupCount ((mDNSu8)18)
281 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
282 // This means that because the announce interval is doubled after sending the first packet, the first
283 // observed on-the-wire inter-packet interval between announcements is actually one second.
284 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
285 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
286 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
287 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
289 #define DefaultAPIntervalForRecordType(X) ((X) & kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
290 (X) & kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
291 (X) & kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
293 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
294 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
295 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
296 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
298 #define MaxUnansweredQueries 4
300 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
301 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
302 // TTL and rdata may differ.
303 // This is used for cache flush management:
304 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
305 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
307 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
309 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
311 mDNSlocal mDNSBool
SameResourceRecordNameClassInterface(const AuthRecord
*const r1
, const AuthRecord
*const r2
)
313 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
314 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
315 if (r1
->resrec
.InterfaceID
&&
316 r2
->resrec
.InterfaceID
&&
317 r1
->resrec
.InterfaceID
!= r2
->resrec
.InterfaceID
) return(mDNSfalse
);
319 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
&&
320 r1
->resrec
.namehash
== r2
->resrec
.namehash
&&
321 SameDomainName(r1
->resrec
.name
, r2
->resrec
.name
));
324 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
325 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
326 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
327 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
328 // so a response of any type should match, even if it is not actually the type the client plans to use.
330 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
331 // and require the rrtypes to match for the rdata to be considered potentially conflicting
332 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
334 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
335 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
336 if (pktrr
->resrec
.InterfaceID
&&
337 authrr
->resrec
.InterfaceID
&&
338 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
339 if (!(authrr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) || authrr
->WakeUp
.HMAC
.l
[0])
340 if (pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
342 pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&&
343 pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&&
344 SameDomainName(pktrr
->resrec
.name
, authrr
->resrec
.name
));
347 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
348 // This is the information that the requester believes to be correct.
349 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
350 // This is the information that we believe to be correct.
351 // We've already determined that we plan to give this answer on this interface
352 // (either the record is non-specific, or it is specific to this interface)
353 // so now we just need to check the name, type, class, rdata and TTL.
354 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
356 // If RR signature is different, or data is different, then don't suppress our answer
357 if (!IdenticalResourceRecord(&ka
->resrec
, &rr
->resrec
)) return(mDNSfalse
);
359 // If the requester's indicated TTL is less than half the real TTL,
360 // we need to give our answer before the requester's copy expires.
361 // If the requester's indicated TTL is at least half the real TTL,
362 // then we can suppress our answer this time.
363 // If the requester's indicated TTL is greater than the TTL we believe,
364 // then that's okay, and we don't need to do anything about it.
365 // (If two responders on the network are offering the same information,
366 // that's okay, and if they are offering the information with different TTLs,
367 // the one offering the lower TTL should defer to the one offering the higher TTL.)
368 return(mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
371 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
373 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
375 if ((rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
> mDNSPlatformOneSecond
* 10)
377 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr
->ProbeCount
, (rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
, ARDisplayString(m
, rr
));
378 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m
->SuppressProbes
, m
->timenow
, m
->SuppressProbes
- m
->timenow
);
380 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
381 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
382 // Some defensive code:
383 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
384 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
385 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
386 if (m
->NextScheduledProbe
- m
->timenow
< 0)
387 m
->NextScheduledProbe
= m
->timenow
;
389 else if (rr
->AnnounceCount
&& (ResourceRecordIsValidAnswer(rr
) || rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
))
391 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
392 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
396 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
398 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
399 rr
->ThisAPInterval
= rr
->AddressProxy
.type
? mDNSPlatformOneSecond
: DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
401 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
402 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
403 // records that are going to probe, then we delay its first announcement so that it will
404 // go out synchronized with the first announcement for the other records that *are* probing.
405 // This is a minor performance tweak that helps keep groups of related records synchronized together.
406 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
407 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
408 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
409 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
410 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
414 // If we have no probe suppression time set, or it is in the past, set it now
415 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
417 // To allow us to aggregate probes when a group of services are registered together,
418 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
419 // 1/4 second wait; probe
420 // 1/4 second wait; probe
421 // 1/4 second wait; probe
422 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
423 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
425 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
426 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
427 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledProbe
);
428 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
429 m
->SuppressProbes
= m
->timenow
;
431 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
432 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
433 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledQuery
);
434 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
435 m
->SuppressProbes
= m
->timenow
;
437 // except... don't expect to be able to send before the m->SuppressSending timer fires
438 if (m
->SuppressSending
&& m
->SuppressProbes
- m
->SuppressSending
< 0)
439 m
->SuppressProbes
= NonZeroTime(m
->SuppressSending
);
441 if (m
->SuppressProbes
- m
->timenow
> mDNSPlatformOneSecond
* 8)
443 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
444 m
->SuppressProbes
- m
->timenow
,
445 m
->NextScheduledProbe
- m
->timenow
,
446 m
->NextScheduledQuery
- m
->timenow
,
448 m
->SuppressSending
- m
->timenow
);
449 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
452 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
454 else if (m
->SuppressProbes
&& m
->SuppressProbes
- m
->timenow
>= 0)
455 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
+ DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
457 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
459 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
460 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
461 // After three probes one second apart with no answer, we conclude the client is now sleeping
462 // and we can begin broadcasting our announcements to take over ownership of that IP address.
463 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
464 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
465 if (rr
->AddressProxy
.type
) rr
->LastAPTime
= m
->timenow
;
467 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
468 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
469 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
470 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
471 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
472 if (m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
473 if (rr
->WakeUp
.HMAC
.l
[0] && rr
->resrec
.rrtype
== kDNSType_AAAA
)
474 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
+ mDNSPlatformOneSecond
* 10;
476 // Set LastMCTime to now, to inhibit multicast responses
477 // (no need to send additional multicast responses when we're announcing anyway)
478 rr
->LastMCTime
= m
->timenow
;
479 rr
->LastMCInterface
= mDNSInterfaceMark
;
481 SetNextAnnounceProbeTime(m
, rr
);
484 mDNSlocal
const domainname
*SetUnicastTargetToHostName(mDNS
*const m
, AuthRecord
*rr
)
486 const domainname
*target
;
489 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
490 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
491 // with the port number in our advertised SRV record automatically tracking the external mapped port.
492 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
493 if (!AuthInfo
|| !AuthInfo
->AutoTunnel
) rr
->AutoTarget
= Target_AutoHostAndNATMAP
;
496 target
= GetServiceTarget(m
, rr
);
497 if (!target
|| target
->c
[0] == 0)
499 // defer registration until we've got a target
500 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m
, rr
));
501 rr
->state
= regState_NoTarget
;
506 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target
->c
, ARDisplayString(m
,rr
));
511 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
512 // Eventually we should unify this with GetServiceTarget() in uDNS.c
513 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
515 domainname
*const target
= GetRRDomainNameTarget(&rr
->resrec
);
516 const domainname
*newname
= &m
->MulticastHostname
;
518 if (!target
) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr
->resrec
.rrtype
));
520 if (!(rr
->ForceMCast
|| rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
|| IsLocalDomain(&rr
->namestorage
)))
522 const domainname
*const n
= SetUnicastTargetToHostName(m
, rr
);
524 else { target
->c
[0] = 0; SetNewRData(&rr
->resrec
, mDNSNULL
, 0); return; }
527 if (target
&& SameDomainName(target
, newname
))
528 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
->c
, target
->c
);
530 if (target
&& !SameDomainName(target
, newname
))
532 AssignDomainName(target
, newname
);
533 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
535 // If we're in the middle of probing this record, we need to start again,
536 // because changing its rdata may change the outcome of the tie-breaker.
537 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
538 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
540 // If we've announced this record, we really should send a goodbye packet for the old rdata before
541 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
542 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
543 if (rr
->RequireGoodbye
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
544 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
545 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
547 rr
->AnnounceCount
= InitialAnnounceCount
;
548 rr
->RequireGoodbye
= mDNSfalse
;
549 InitializeLastAPTime(m
, rr
);
553 mDNSlocal
void AcknowledgeRecord(mDNS
*const m
, AuthRecord
*const rr
)
555 if (rr
->RecordCallback
)
557 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
558 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
559 rr
->Acknowledged
= mDNStrue
;
560 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
561 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
562 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
566 mDNSexport
void ActivateUnicastRegistration(mDNS
*const m
, AuthRecord
*const rr
)
568 // Make sure that we don't activate the SRV record and associated service records, if it is in
569 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
570 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
571 // the target becomes available, the records will be reregistered.
572 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
574 AuthRecord
*srvRR
= mDNSNULL
;
575 if (rr
->resrec
.rrtype
== kDNSType_PTR
)
576 srvRR
= rr
->Additional1
;
577 else if (rr
->resrec
.rrtype
== kDNSType_TXT
)
578 srvRR
= rr
->DependentOn
;
581 if (srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
583 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
587 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
588 ARDisplayString(m
, srvRR
), srvRR
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
589 rr
->state
= srvRR
->state
;
594 if (rr
->state
== regState_NoTarget
)
596 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m
, rr
));
599 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
600 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
601 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
602 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
603 // 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.
604 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
606 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m
, rr
), rr
->state
);
607 rr
->state
= regState_DeregPending
;
611 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m
, rr
), rr
->state
);
612 rr
->state
= regState_Pending
;
615 rr
->AnnounceCount
= 0;
616 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
617 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
618 rr
->expire
= 0; // Forget about all the leases, start fresh
619 rr
->uselease
= mDNStrue
;
620 rr
->updateid
= zeroID
;
621 rr
->SRVChanged
= mDNSfalse
;
622 rr
->updateError
= mStatus_NoError
;
623 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
624 // The records might already be registered with the server and hence could have NAT state.
625 if (rr
->NATinfo
.clientContext
)
627 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
628 rr
->NATinfo
.clientContext
= mDNSNULL
;
630 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
631 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
632 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
633 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
636 // Two records qualify to be local duplicates if:
637 // (a) the RecordTypes are the same, or
638 // (b) one is Unique and the other Verified
639 // (c) either is in the process of deregistering
640 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
641 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
642 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
644 #define RecordIsLocalDuplicate(A,B) \
645 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(&(A)->resrec, &(B)->resrec))
647 // Exported so uDNS.c can call this
648 mDNSexport mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
650 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
652 AuthRecord
**p
= &m
->ResourceRecords
;
653 AuthRecord
**d
= &m
->DuplicateRecords
;
655 if ((mDNSs32
)rr
->resrec
.rroriginalttl
<= 0)
656 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr
->resrec
.rroriginalttl
, ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
658 if (!rr
->resrec
.RecordType
)
659 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
662 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m
, rr
)); return(mStatus_ServiceNotRunning
); }
664 if (m
->DivertMulticastAdvertisements
&& !AuthRecord_uDNS(rr
))
666 mDNSInterfaceID previousID
= rr
->resrec
.InterfaceID
;
667 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
) rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
668 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
670 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
671 if (intf
&& !intf
->Advertise
) rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
673 if (rr
->resrec
.InterfaceID
!= previousID
)
674 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m
, rr
));
677 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
678 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
681 LogMsg("Error! Tried to register AuthRecord %p %##s (%s) that's already in the list",
682 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
683 return(mStatus_AlreadyRegistered
);
688 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
689 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
692 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
693 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
694 return(mStatus_Invalid
);
696 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
)))
698 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
699 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
700 return(mStatus_Invalid
);
704 // If this resource record is referencing a specific interface, make sure it exists
705 if (rr
->resrec
.InterfaceID
&& rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
&& rr
->resrec
.InterfaceID
!= mDNSInterface_P2P
)
707 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
710 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr
->resrec
.InterfaceID
);
711 return(mStatus_BadReferenceErr
);
717 // Field Group 1: The actual information pertaining to this resource record
718 // Set up by client prior to call
720 // Field Group 2: Persistent metadata for Authoritative Records
721 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
722 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
723 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
724 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
725 // rr->Callback = already set in mDNS_SetupResourceRecord
726 // rr->Context = already set in mDNS_SetupResourceRecord
727 // rr->RecordType = already set in mDNS_SetupResourceRecord
728 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
729 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
730 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
731 if (rr
->AutoTarget
&& target
) target
->c
[0] = 0;
733 // Field Group 3: Transient state for Authoritative Records
734 rr
->Acknowledged
= mDNSfalse
;
735 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
736 rr
->AnnounceCount
= InitialAnnounceCount
;
737 rr
->RequireGoodbye
= mDNSfalse
;
738 rr
->AnsweredLocalQ
= mDNSfalse
;
739 rr
->IncludeInProbe
= mDNSfalse
;
740 rr
->ImmedUnicast
= mDNSfalse
;
741 rr
->SendNSECNow
= mDNSNULL
;
742 rr
->ImmedAnswer
= mDNSNULL
;
743 rr
->ImmedAdditional
= mDNSNULL
;
744 rr
->SendRNow
= mDNSNULL
;
745 rr
->v4Requester
= zerov4Addr
;
746 rr
->v6Requester
= zerov6Addr
;
747 rr
->NextResponse
= mDNSNULL
;
748 rr
->NR_AnswerTo
= mDNSNULL
;
749 rr
->NR_AdditionalTo
= mDNSNULL
;
750 if (!rr
->AutoTarget
) InitializeLastAPTime(m
, rr
);
751 // rr->LastAPTime = Set for us in InitializeLastAPTime()
752 // rr->LastMCTime = Set for us in InitializeLastAPTime()
753 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
754 rr
->NewRData
= mDNSNULL
;
756 rr
->UpdateCallback
= mDNSNULL
;
757 rr
->UpdateCredits
= kMaxUpdateCredits
;
758 rr
->NextUpdateCredit
= 0;
759 rr
->UpdateBlocked
= 0;
761 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
762 if (rr
->WakeUp
.HMAC
.l
[0] && !rr
->AddressProxy
.type
) rr
->AnnounceCount
= 2;
764 // Field Group 4: Transient uDNS state for Authoritative Records
765 rr
->state
= regState_Zero
;
769 rr
->updateid
= zeroID
;
770 rr
->zone
= rr
->resrec
.name
;
775 rr
->InFlightRData
= 0;
776 rr
->InFlightRDLen
= 0;
780 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
781 // rr->resrec.name->c = MUST be set by client
782 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
783 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
784 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
785 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
787 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
788 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
789 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
790 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rr
->resrec
.rdlength
== 0) { rr
->resrec
.rdlength
= 1; rr
->resrec
.rdata
->u
.txt
.c
[0] = 0; }
794 SetTargetToHostName(m
, rr
); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
795 #ifndef UNICAST_DISABLED
796 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
797 // 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.
798 if (rr
->state
== regState_NoTarget
)
800 // Initialize the target so that we don't crash while logging etc.
801 domainname
*tar
= GetRRDomainNameTarget(&rr
->resrec
);
802 if (tar
) tar
->c
[0] = 0;
803 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m
, rr
));
809 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
810 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
813 if (!ValidateDomainName(rr
->resrec
.name
))
814 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
816 // Don't do this until *after* we've set rr->resrec.rdlength
817 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
818 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
820 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
821 rr
->resrec
.rdatahash
= target
? DomainNameHashValue(target
) : RDataHashValue(&rr
->resrec
);
823 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
825 // If this is supposed to be unique, make sure we don't have any name conflicts
826 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
828 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
829 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
831 const AuthRecord
*s2
= r
->RRSet
? r
->RRSet
: r
;
832 if (s1
!= s2
&& SameResourceRecordSignature(r
, rr
) && !IdenticalSameNameRecord(&r
->resrec
, &rr
->resrec
))
835 if (r
) // If we found a conflict, set RecordType = kDNSRecordTypeDeregistering so we'll deliver the callback
837 debugf("Name conflict %p %##s (%s)", rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
838 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
839 rr
->resrec
.rroriginalttl
= 0;
840 rr
->ImmedAnswer
= mDNSInterfaceMark
;
841 m
->LocalRemoveEvents
= mDNStrue
;
842 m
->NextScheduledResponse
= m
->timenow
;
847 // For uDNS records, we don't support duplicate checks at this time
848 #ifndef UNICAST_DISABLED
849 if (AuthRecord_uDNS(rr
))
851 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
852 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
853 // 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.
854 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
855 while (*p
) p
=&(*p
)->next
;
857 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
859 rr
->AnnounceCount
= 0;
860 if (rr
->state
!= regState_NoTarget
) ActivateUnicastRegistration(m
, rr
);
861 return(mStatus_NoError
); // <--- Note: For unicast records, code currently bails out at this point
865 // Now that we've finished building our new record, make sure it's not identical to one we already have
866 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
867 if (RecordIsLocalDuplicate(r
, rr
))
869 if (r
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) r
->AnnounceCount
= 0;
875 debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m
,rr
));
877 // If the previous copy of this record is already verified unique,
878 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
879 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
880 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
881 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
886 debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m
,rr
));
887 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
891 if (!AuthRecord_uDNS(rr
)) // This check is superfluous, given that for unicast records we (currently) bail out above
893 // For records that are not going to probe, acknowledge them right away
894 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
895 AcknowledgeRecord(m
, rr
);
897 // Adding a record may affect whether or not we should sleep
898 mDNS_UpdateAllowSleep(m
);
901 return(mStatus_NoError
);
904 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
906 m
->ProbeFailTime
= m
->timenow
;
907 m
->NumFailedProbes
++;
908 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
909 // If a bunch of hosts have all been configured with the same name, then they'll all
910 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
911 // up to name-10. After that they'll start adding random increments in the range 1-100,
912 // so they're more likely to branch out in the available namespace and settle on a set of
913 // unique names quickly. If after five more tries the host is still conflicting, then we
914 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
915 if (m
->NumFailedProbes
>= 15)
917 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
918 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
919 m
->NumFailedProbes
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
923 mDNSlocal
void CompleteRDataUpdate(mDNS
*const m
, AuthRecord
*const rr
)
925 RData
*OldRData
= rr
->resrec
.rdata
;
926 mDNSu16 OldRDLen
= rr
->resrec
.rdlength
;
927 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
928 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
929 if (rr
->UpdateCallback
)
930 rr
->UpdateCallback(m
, rr
, OldRData
, OldRDLen
); // ... and let the client know
933 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
934 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
935 // Exported so uDNS.c can call this
936 mDNSexport mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
939 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
940 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
942 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
946 // We found our record on the main list. See if there are any duplicates that need special handling.
947 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
949 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
950 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
951 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
) if (RecordIsLocalDuplicate(r2
, rr
)) r2
->ProbeCount
= 0xFF;
955 // Before we delete the record (and potentially send a goodbye packet)
956 // first see if we have a record on the duplicate list ready to take over from it.
957 AuthRecord
**d
= &m
->DuplicateRecords
;
958 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
961 AuthRecord
*dup
= *d
;
962 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
963 dup
, rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
964 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
965 dup
->next
= rr
->next
; // And then...
966 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
967 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
968 dup
->ProbeCount
= rr
->ProbeCount
;
969 dup
->AnnounceCount
= rr
->AnnounceCount
;
970 dup
->RequireGoodbye
= rr
->RequireGoodbye
;
971 dup
->AnsweredLocalQ
= rr
->AnsweredLocalQ
;
972 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
973 dup
->ImmedUnicast
= rr
->ImmedUnicast
;
974 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
975 dup
->v4Requester
= rr
->v4Requester
;
976 dup
->v6Requester
= rr
->v6Requester
;
977 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
978 dup
->LastAPTime
= rr
->LastAPTime
;
979 dup
->LastMCTime
= rr
->LastMCTime
;
980 dup
->LastMCInterface
= rr
->LastMCInterface
;
981 dup
->Private
= rr
->Private
;
982 dup
->state
= rr
->state
;
983 rr
->RequireGoodbye
= mDNSfalse
;
984 rr
->AnsweredLocalQ
= mDNSfalse
;
990 // We didn't find our record on the main list; try the DuplicateRecords list instead.
991 p
= &m
->DuplicateRecords
;
992 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
993 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
994 if (*p
) rr
->RequireGoodbye
= mDNSfalse
;
995 if (*p
) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
996 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1001 // No need to log an error message if we already know this is a potentially repeated deregistration
1002 if (drt
!= mDNS_Dereg_repeat
)
1003 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr
, ARDisplayString(m
,rr
));
1004 return(mStatus_BadReferenceErr
);
1007 // If this is a shared record and we've announced it at least once,
1008 // we need to retract that announcement before we delete the record
1010 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1011 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1012 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1013 // mechanism to cope with the client callback modifying the question list while that's happening.
1014 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1015 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1016 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1017 // records, thereby invoking yet more callbacks, without limit.
1018 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1019 // actual goodbye packets.
1021 #ifndef UNICAST_DISABLED
1022 if (AuthRecord_uDNS(rr
))
1024 if (rr
->RequireGoodbye
)
1026 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1027 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1028 m
->LocalRemoveEvents
= mDNStrue
;
1029 uDNS_DeregisterRecord(m
, rr
);
1030 // At this point unconditionally we bail out
1031 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1032 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1033 // process and will complete asynchronously. Either way we don't need to do anything more here.
1034 return(mStatus_NoError
);
1036 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1037 // from the server. In that case, if the records have been part of a group update, clear the
1038 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1039 rr
->updateid
= zeroID
;
1041 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1042 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1043 // This happens today when we turn on/off interface where we get multiple network transitions
1044 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1045 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1046 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1047 // NAT state here takes care of the case where we did not send goodbyes at all.
1048 if (rr
->NATinfo
.clientContext
)
1050 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1051 rr
->NATinfo
.clientContext
= mDNSNULL
;
1053 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1054 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1056 #endif // UNICAST_DISABLED
1058 if (RecordType
== kDNSRecordTypeUnregistered
)
1059 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m
, rr
));
1060 else if (RecordType
== kDNSRecordTypeDeregistering
)
1062 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m
, rr
));
1063 return(mStatus_BadReferenceErr
);
1066 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1067 // We may want to consider changing this code so that we generate local-only question "rmv"
1068 // events (and maybe goodbye packets too) for unique records as well as for shared records
1069 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1070 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1071 // clause will execute here and the record will be cut from the list.
1072 if (rr
->WakeUp
.HMAC
.l
[0] ||
1073 (RecordType
== kDNSRecordTypeShared
&& (rr
->RequireGoodbye
|| rr
->AnsweredLocalQ
)))
1075 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m
, rr
));
1076 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1077 rr
->resrec
.rroriginalttl
= 0;
1078 rr
->AnnounceCount
= rr
->WakeUp
.HMAC
.l
[0] ? WakeupCount
: (drt
== mDNS_Dereg_rapid
) ? 1 : GoodbyeCount
;
1079 rr
->ThisAPInterval
= mDNSPlatformOneSecond
* 2;
1080 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1081 m
->LocalRemoveEvents
= mDNStrue
;
1082 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
1083 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
1087 *p
= rr
->next
; // Cut this record from the list
1088 // If someone is about to look at this, bump the pointer forward
1089 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
1090 if (m
->NewLocalRecords
== rr
) m
->NewLocalRecords
= rr
->next
;
1091 rr
->next
= mDNSNULL
;
1093 // Should we generate local remove events here?
1094 // i.e. something like:
1095 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1097 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m
, rr
));
1098 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
1100 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
1101 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1102 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1104 // If we have an update queued up which never executed, give the client a chance to free that memory
1105 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
1108 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1109 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1110 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1111 // so any attempt to touch rr after this is likely to lead to a crash.
1112 if (drt
!= mDNS_Dereg_conflict
)
1114 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1115 LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m
, rr
));
1116 if (rr
->RecordCallback
)
1117 rr
->RecordCallback(m
, rr
, mStatus_MemFree
); // MUST NOT touch rr after this
1118 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1122 RecordProbeFailure(m
, rr
);
1123 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1124 if (rr
->RecordCallback
)
1125 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
); // MUST NOT touch rr after this
1126 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1127 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1128 // Note that with all the client callbacks going on, by the time we get here all the
1129 // records we marked may have been explicitly deregistered by the client anyway.
1130 r2
= m
->DuplicateRecords
;
1133 if (r2
->ProbeCount
!= 0xFF) r2
= r2
->next
;
1134 else { mDNS_Deregister_internal(m
, r2
, mDNS_Dereg_conflict
); r2
= m
->DuplicateRecords
; }
1138 mDNS_UpdateAllowSleep(m
);
1139 return(mStatus_NoError
);
1142 // ***************************************************************************
1143 #if COMPILER_LIKES_PRAGMA_MARK
1145 #pragma mark - Packet Sending Functions
1148 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
1150 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
1153 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1154 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1155 // The referenced record will definitely be acceptable (by recursive application of this rule)
1156 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
1157 rr
->NR_AdditionalTo
= add
;
1158 *nrpp
= &rr
->NextResponse
;
1160 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1163 mDNSlocal
void AddAdditionalsToResponseList(mDNS
*const m
, AuthRecord
*ResponseRecords
, AuthRecord
***nrpp
, const mDNSInterfaceID InterfaceID
)
1165 AuthRecord
*rr
, *rr2
;
1166 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
1168 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1169 // later in the "for" loop, and we will follow further "additional" links then.)
1170 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
1171 AddRecordToResponseList(nrpp
, rr
->Additional1
, rr
);
1173 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
1174 AddRecordToResponseList(nrpp
, rr
->Additional2
, rr
);
1176 // For SRV records, automatically add the Address record(s) for the target host
1177 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
1179 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
1180 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
1181 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
1182 rr
->resrec
.rdatahash
== rr2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
1183 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, rr2
->resrec
.name
))
1184 AddRecordToResponseList(nrpp
, rr2
, rr
);
1186 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
)) // For A or AAAA, put counterpart as additional
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
.namehash
== rr2
->resrec
.namehash
&& // ... and have the same name
1192 SameDomainName(rr
->resrec
.name
, rr2
->resrec
.name
))
1193 AddRecordToResponseList(nrpp
, rr2
, rr
);
1195 else if (rr
->resrec
.rrtype
== kDNSType_PTR
) // For service PTR, see if we want to add DeviceInfo record
1197 if (ResourceRecordIsValidInterfaceAnswer(&m
->DeviceInfo
, InterfaceID
) &&
1198 SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
1199 AddRecordToResponseList(nrpp
, &m
->DeviceInfo
, rr
);
1204 mDNSlocal
void SendDelayedUnicastResponse(mDNS
*const m
, const mDNSAddr
*const dest
, const mDNSInterfaceID InterfaceID
)
1207 AuthRecord
*ResponseRecords
= mDNSNULL
;
1208 AuthRecord
**nrp
= &ResponseRecords
;
1210 // Make a list of all our records that need to be unicast to this destination
1211 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1213 // If we find we can no longer unicast this answer, clear ImmedUnicast
1214 if (rr
->ImmedAnswer
== mDNSInterfaceMark
||
1215 mDNSSameIPv4Address(rr
->v4Requester
, onesIPv4Addr
) ||
1216 mDNSSameIPv6Address(rr
->v6Requester
, onesIPv6Addr
) )
1217 rr
->ImmedUnicast
= mDNSfalse
;
1219 if (rr
->ImmedUnicast
&& rr
->ImmedAnswer
== InterfaceID
)
1220 if ((dest
->type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->v4Requester
, dest
->ip
.v4
)) ||
1221 (dest
->type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->v6Requester
, dest
->ip
.v6
)))
1223 rr
->ImmedAnswer
= mDNSNULL
; // Clear the state fields
1224 rr
->ImmedUnicast
= mDNSfalse
;
1225 rr
->v4Requester
= zerov4Addr
;
1226 rr
->v6Requester
= zerov6Addr
;
1227 if (rr
->NextResponse
== mDNSNULL
&& nrp
!= &rr
->NextResponse
) // rr->NR_AnswerTo
1228 { rr
->NR_AnswerTo
= (mDNSu8
*)~0; *nrp
= rr
; nrp
= &rr
->NextResponse
; }
1232 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
1234 while (ResponseRecords
)
1236 mDNSu8
*responseptr
= m
->omsg
.data
;
1238 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
1240 // Put answers in the packet
1241 while (ResponseRecords
&& ResponseRecords
->NR_AnswerTo
)
1243 rr
= ResponseRecords
;
1244 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1245 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
1246 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
);
1247 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
1248 if (!newptr
&& m
->omsg
.h
.numAnswers
) break; // If packet full, send it now
1249 if (newptr
) responseptr
= newptr
;
1250 ResponseRecords
= rr
->NextResponse
;
1251 rr
->NextResponse
= mDNSNULL
;
1252 rr
->NR_AnswerTo
= mDNSNULL
;
1253 rr
->NR_AdditionalTo
= mDNSNULL
;
1254 rr
->RequireGoodbye
= mDNStrue
;
1257 // Add additionals, if there's space
1258 while (ResponseRecords
&& !ResponseRecords
->NR_AnswerTo
)
1260 rr
= ResponseRecords
;
1261 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1262 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
1263 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
1264 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
1266 if (newptr
) responseptr
= newptr
;
1267 if (newptr
&& m
->omsg
.h
.numAnswers
) rr
->RequireGoodbye
= mDNStrue
;
1268 else if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
->ImmedAnswer
= mDNSInterfaceMark
;
1269 ResponseRecords
= rr
->NextResponse
;
1270 rr
->NextResponse
= mDNSNULL
;
1271 rr
->NR_AnswerTo
= mDNSNULL
;
1272 rr
->NR_AdditionalTo
= mDNSNULL
;
1275 if (m
->omsg
.h
.numAnswers
)
1276 mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, mDNSInterface_Any
, mDNSNULL
, dest
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
);
1280 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1281 // and the client's mStatus_MemFree callback will have been invoked
1282 mDNSexport
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
1284 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m
, rr
));
1285 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1286 // it should go ahead and immediately dispose of this registration
1287 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
1288 rr
->RequireGoodbye
= mDNSfalse
;
1289 rr
->WakeUp
.HMAC
= zeroEthAddr
;
1290 if (rr
->AnsweredLocalQ
) { AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
); rr
->AnsweredLocalQ
= mDNSfalse
; }
1291 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
); // Don't touch rr after this
1294 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1295 // any deregistering records that remain in the m->ResourceRecords list.
1296 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1297 // which may change the record list and/or question list.
1298 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1299 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
1301 if (m
->CurrentRecord
)
1302 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
1303 m
->CurrentRecord
= m
->ResourceRecords
;
1305 while (m
->CurrentRecord
)
1307 AuthRecord
*rr
= m
->CurrentRecord
;
1308 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1309 CompleteDeregistration(m
, rr
); // Don't touch rr after this
1311 m
->CurrentRecord
= rr
->next
;
1315 mDNSlocal mStatus
GetLabelDecimalValue(const mDNSu8
*const src
, mDNSu8
*dst
)
1318 if (src
[0] < 1 || src
[0] > 3) return(mStatus_Invalid
);
1319 for (i
=1; i
<=src
[0]; i
++)
1321 if (src
[i
] < '0' || src
[i
] > '9') return(mStatus_Invalid
);
1322 val
= val
* 10 + src
[i
] - '0';
1324 if (val
> 255) return(mStatus_Invalid
);
1326 return(mStatus_NoError
);
1329 mDNSlocal mStatus
GetIPv4FromName(mDNSAddr
*const a
, const domainname
*const name
)
1331 int skip
= CountLabels(name
) - 6;
1332 if (skip
< 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name
); return mStatus_Invalid
; }
1333 if (GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+3)->c
, &a
->ip
.v4
.b
[0]) ||
1334 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+2)->c
, &a
->ip
.v4
.b
[1]) ||
1335 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+1)->c
, &a
->ip
.v4
.b
[2]) ||
1336 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+0)->c
, &a
->ip
.v4
.b
[3])) return mStatus_Invalid
;
1337 a
->type
= mDNSAddrType_IPv4
;
1338 return(mStatus_NoError
);
1341 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
1342 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
1343 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1345 mDNSlocal mStatus
GetIPv6FromName(mDNSAddr
*const a
, const domainname
*const name
)
1348 const domainname
*n
;
1350 int skip
= CountLabels(name
) - 34;
1351 if (skip
< 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name
); return mStatus_Invalid
; }
1353 n
= SkipLeadingLabels(name
, skip
);
1354 for (i
=0; i
<16; i
++)
1356 if (n
->c
[0] != 1) return mStatus_Invalid
;
1357 l
= HexVal(n
->c
[1]);
1358 n
= (const domainname
*)(n
->c
+ 2);
1360 if (n
->c
[0] != 1) return mStatus_Invalid
;
1361 h
= HexVal(n
->c
[1]);
1362 n
= (const domainname
*)(n
->c
+ 2);
1364 if (l
<0 || h
<0) return mStatus_Invalid
;
1365 a
->ip
.v6
.b
[15-i
] = (mDNSu8
)((h
<< 4) | l
);
1368 a
->type
= mDNSAddrType_IPv6
;
1369 return(mStatus_NoError
);
1372 mDNSlocal mDNSs32
ReverseMapDomainType(const domainname
*const name
)
1374 int skip
= CountLabels(name
) - 2;
1377 const domainname
*suffix
= SkipLeadingLabels(name
, skip
);
1378 if (SameDomainName(suffix
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4
;
1379 if (SameDomainName(suffix
, (const domainname
*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6
;
1381 return(mDNSAddrType_None
);
1384 mDNSlocal
void SendARP(mDNS
*const m
, const mDNSu8 op
, const AuthRecord
*const rr
,
1385 const mDNSv4Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const dst
)
1388 mDNSu8
*ptr
= m
->omsg
.data
;
1389 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1390 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
1392 // 0x00 Destination address
1393 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
1395 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1396 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
1398 // 0x0C ARP Ethertype (0x0806)
1399 *ptr
++ = 0x08; *ptr
++ = 0x06;
1402 *ptr
++ = 0x00; *ptr
++ = 0x01; // Hardware address space; Ethernet = 1
1403 *ptr
++ = 0x08; *ptr
++ = 0x00; // Protocol address space; IP = 0x0800
1404 *ptr
++ = 6; // Hardware address length
1405 *ptr
++ = 4; // Protocol address length
1406 *ptr
++ = 0x00; *ptr
++ = op
; // opcode; Request = 1, Response = 2
1408 // 0x16 Sender hardware address (our MAC address)
1409 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[i
];
1411 // 0x1C Sender protocol address
1412 for (i
=0; i
<4; i
++) *ptr
++ = spa
->b
[i
];
1414 // 0x20 Target hardware address
1415 for (i
=0; i
<6; i
++) *ptr
++ = tha
->b
[i
];
1417 // 0x26 Target protocol address
1418 for (i
=0; i
<4; i
++) *ptr
++ = tpa
->b
[i
];
1420 // 0x2A Total ARP Packet length 42 bytes
1421 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
1424 mDNSlocal mDNSu16
CheckSum(const void *const data
, mDNSs32 length
, mDNSu32 sum
)
1426 const mDNSu16
*ptr
= data
;
1427 while (length
> 0) { length
-= 2; sum
+= *ptr
++; }
1428 sum
= (sum
& 0xFFFF) + (sum
>> 16);
1429 sum
= (sum
& 0xFFFF) + (sum
>> 16);
1430 return(sum
!= 0xFFFF ? sum
: 0);
1433 mDNSlocal mDNSu16
IPv6CheckSum(const mDNSv6Addr
*const src
, const mDNSv6Addr
*const dst
, const mDNSu8 protocol
, const void *const data
, const mDNSu32 length
)
1435 IPv6PseudoHeader ph
;
1438 ph
.len
.b
[0] = length
>> 24;
1439 ph
.len
.b
[1] = length
>> 16;
1440 ph
.len
.b
[2] = length
>> 8;
1441 ph
.len
.b
[3] = length
;
1445 ph
.pro
.b
[3] = protocol
;
1446 return CheckSum(&ph
, sizeof(ph
), CheckSum(data
, length
, 0));
1449 mDNSlocal
void SendNDP(mDNS
*const m
, const mDNSu8 op
, const mDNSu8 flags
, const AuthRecord
*const rr
,
1450 const mDNSv6Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv6Addr
*const tpa
, const mDNSEthAddr
*const dst
)
1453 mDNSOpaque16 checksum
;
1454 mDNSu8
*ptr
= m
->omsg
.data
;
1455 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1456 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1457 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1458 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] } };
1459 const mDNSv6Addr
*const v6dst
= (op
== NDP_Sol
) ? &mc
: tpa
;
1460 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1461 if (!intf
) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
1463 // 0x00 Destination address
1464 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
1465 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1466 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1467 // link with a pointless link-layer multicast.
1468 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1469 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1473 // *ptr++ = tpa->b[0xD];
1474 // *ptr++ = tpa->b[0xE];
1475 // *ptr++ = tpa->b[0xF];
1477 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1478 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
1480 // 0x0C IPv6 Ethertype (0x86DD)
1481 *ptr
++ = 0x86; *ptr
++ = 0xDD;
1484 *ptr
++ = 0x60; *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00; // Version, Traffic Class, Flow Label
1485 *ptr
++ = 0x00; *ptr
++ = 0x20; // Length
1486 *ptr
++ = 0x3A; // Protocol == ICMPv6
1487 *ptr
++ = 0xFF; // Hop Limit
1489 // 0x16 Sender IPv6 address
1490 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
1492 // 0x26 Destination IPv6 address
1493 for (i
=0; i
<16; i
++) *ptr
++ = v6dst
->b
[i
];
1496 *ptr
++ = op
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
1497 *ptr
++ = 0x00; // Code
1498 *ptr
++ = 0x00; *ptr
++ = 0x00; // Checksum placeholder (0x38, 0x39)
1500 *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00;
1502 if (op
== NDP_Sol
) // Neighbor Solicitation. The NDP "target" is the address we seek.
1505 for (i
=0; i
<16; i
++) *ptr
++ = tpa
->b
[i
];
1506 // 0x4E Source Link-layer Address
1507 // <http://www.ietf.org/rfc/rfc2461.txt>
1508 // MUST NOT be included when the source IP address is the unspecified address.
1509 // Otherwise, on link layers that have addresses this option MUST be included
1510 // in multicast solicitations and SHOULD be included in unicast solicitations.
1511 if (!mDNSIPv6AddressIsZero(*spa
))
1513 *ptr
++ = NDP_SrcLL
; // Option Type 1 == Source Link-layer Address
1514 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
1515 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
1518 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
1521 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
1522 // 0x4E Target Link-layer Address
1523 *ptr
++ = NDP_TgtLL
; // Option Type 2 == Target Link-layer Address
1524 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
1525 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
1528 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
1529 m
->omsg
.data
[0x13] = ptr
- &m
->omsg
.data
[0x36]; // Compute actual length
1530 checksum
.NotAnInteger
= ~IPv6CheckSum(spa
, v6dst
, 0x3A, &m
->omsg
.data
[0x36], m
->omsg
.data
[0x13]);
1531 m
->omsg
.data
[0x38] = checksum
.b
[0];
1532 m
->omsg
.data
[0x39] = checksum
.b
[1];
1534 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
1537 mDNSlocal
void SetupOwnerOpt(const mDNS
*const m
, const NetworkInterfaceInfo
*const intf
, rdataOPT
*const owner
)
1539 owner
->u
.owner
.vers
= 0;
1540 owner
->u
.owner
.seq
= m
->SleepSeqNum
;
1541 owner
->u
.owner
.HMAC
= m
->PrimaryMAC
;
1542 owner
->u
.owner
.IMAC
= intf
->MAC
;
1543 owner
->u
.owner
.password
= zeroEthAddr
;
1545 // Don't try to compute the optlen until *after* we've set up the data fields
1546 // 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
1547 owner
->opt
= kDNSOpt_Owner
;
1548 owner
->optlen
= DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) - 4;
1551 mDNSlocal
void GrantUpdateCredit(AuthRecord
*rr
)
1553 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
1554 else rr
->NextUpdateCredit
= NonZeroTime(rr
->NextUpdateCredit
+ kUpdateCreditRefreshInterval
);
1557 // Note about acceleration of announcements to facilitate automatic coalescing of
1558 // multiple independent threads of announcements into a single synchronized thread:
1559 // The announcements in the packet may be at different stages of maturity;
1560 // One-second interval, two-second interval, four-second interval, and so on.
1561 // After we've put in all the announcements that are due, we then consider
1562 // whether there are other nearly-due announcements that are worth accelerating.
1563 // To be eligible for acceleration, a record MUST NOT be older (further along
1564 // its timeline) than the most mature record we've already put in the packet.
1565 // In other words, younger records can have their timelines accelerated to catch up
1566 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
1567 // Older records cannot have their timelines accelerated; this would just widen
1568 // the gap between them and their younger bretheren and get them even more out of sync.
1570 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
1571 // the record list and/or question list.
1572 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1573 mDNSlocal
void SendResponses(mDNS
*const m
)
1576 AuthRecord
*rr
, *r2
;
1577 mDNSs32 maxExistingAnnounceInterval
= 0;
1578 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
1580 m
->NextScheduledResponse
= m
->timenow
+ 0x78000000;
1582 if (m
->SleepState
== SleepState_Transferring
) RetrySPSRegistrations(m
);
1584 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1585 if (rr
->ImmedUnicast
)
1587 mDNSAddr v4
= { mDNSAddrType_IPv4
, {{{0}}} };
1588 mDNSAddr v6
= { mDNSAddrType_IPv6
, {{{0}}} };
1589 v4
.ip
.v4
= rr
->v4Requester
;
1590 v6
.ip
.v6
= rr
->v6Requester
;
1591 if (!mDNSIPv4AddressIsZero(rr
->v4Requester
)) SendDelayedUnicastResponse(m
, &v4
, rr
->ImmedAnswer
);
1592 if (!mDNSIPv6AddressIsZero(rr
->v6Requester
)) SendDelayedUnicastResponse(m
, &v6
, rr
->ImmedAnswer
);
1593 if (rr
->ImmedUnicast
)
1595 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m
, rr
));
1596 rr
->ImmedUnicast
= mDNSfalse
;
1601 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
1604 // Run through our list of records, and decide which ones we're going to announce on all interfaces
1605 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1607 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
1608 if (TimeToAnnounceThisRecord(rr
, m
->timenow
))
1610 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1612 if (!rr
->WakeUp
.HMAC
.l
[0])
1614 if (rr
->AnnounceCount
) rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send goodbye packet on all interfaces
1618 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr
->AnnounceCount
-3, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
1619 SendWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.IMAC
, &rr
->WakeUp
.password
);
1620 for (r2
= rr
; r2
; r2
=r2
->next
)
1621 if (r2
->AnnounceCount
&& r2
->resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.IMAC
, &rr
->WakeUp
.IMAC
))
1623 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
1624 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
1625 if (r2
->AddressProxy
.type
== mDNSAddrType_IPv6
&& r2
->AnnounceCount
== WakeupCount
)
1627 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
1628 r2
->AnnounceCount
-3, &r2
->WakeUp
.HMAC
, &r2
->WakeUp
.IMAC
, ARDisplayString(m
,r2
));
1629 SendNDP(m
, NDP_Adv
, NDP_Override
, r2
, &r2
->AddressProxy
.ip
.v6
, &r2
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
1631 r2
->LastAPTime
= m
->timenow
;
1632 if (--r2
->AnnounceCount
<= GoodbyeCount
) r2
->WakeUp
.HMAC
= zeroEthAddr
;
1636 else if (ResourceRecordIsValidAnswer(rr
))
1638 if (rr
->AddressProxy
.type
)
1640 rr
->AnnounceCount
--;
1641 rr
->ThisAPInterval
*= 2;
1642 rr
->LastAPTime
= m
->timenow
;
1643 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv4
)
1645 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
1646 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
1647 SendARP(m
, 1, rr
, &rr
->AddressProxy
.ip
.v4
, &zeroEthAddr
, &rr
->AddressProxy
.ip
.v4
, &onesEthAddr
);
1649 else if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
1651 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
1652 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
1653 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
1658 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
1659 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
1660 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
1661 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
1667 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
1668 // Eligible records that are more than half-way to their announcement time are accelerated
1669 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1670 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
1671 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
1672 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
1673 !rr
->AddressProxy
.type
&& // Don't include ARP Annoucements when considering which records to accelerate
1674 ResourceRecordIsValidAnswer(rr
)))
1675 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
1677 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
1678 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
1679 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
1680 // then all that means is that it won't get sent -- which would not be the end of the world.
1681 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1683 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
1684 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
1685 if (RRTypeIsAddressType(r2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
1686 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
1687 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
1688 rr
->resrec
.rdatahash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
1689 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, r2
->resrec
.name
) &&
1690 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
1691 r2
->ImmedAdditional
= r2
->resrec
.InterfaceID
; // ... then mark this address record for sending too
1692 // We also make sure we send the DeviceInfo TXT record too, if necessary
1693 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
1694 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
1695 if (rr
->ImmedAnswer
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->resrec
.rrtype
== kDNSType_PTR
)
1696 if (ResourceRecordIsValidAnswer(&m
->DeviceInfo
) && SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
1698 if (!m
->DeviceInfo
.ImmedAnswer
) m
->DeviceInfo
.ImmedAnswer
= rr
->ImmedAnswer
;
1699 else m
->DeviceInfo
.ImmedAnswer
= mDNSInterfaceMark
;
1703 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
1704 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
1705 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
1706 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
1707 // -- 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
1708 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
1709 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1710 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1712 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
1714 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
1715 if (ResourceRecordIsValidAnswer(r2
))
1716 if (r2
->ImmedAnswer
!= mDNSInterfaceMark
&&
1717 r2
->ImmedAnswer
!= rr
->ImmedAnswer
&& SameResourceRecordSignature(r2
, rr
))
1718 r2
->ImmedAnswer
= !r2
->ImmedAnswer
? rr
->ImmedAnswer
: mDNSInterfaceMark
;
1720 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
1722 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
1723 if (ResourceRecordIsValidAnswer(r2
))
1724 if (r2
->ImmedAdditional
!= rr
->ImmedAdditional
&& SameResourceRecordSignature(r2
, rr
))
1725 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
1729 // Now set SendRNow state appropriately
1730 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1732 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
1734 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
1735 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
1736 rr
->LastMCTime
= m
->timenow
;
1737 rr
->LastMCInterface
= rr
->ImmedAnswer
;
1738 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
1739 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
1741 rr
->AnnounceCount
--;
1742 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
1743 rr
->ThisAPInterval
*= 2;
1744 rr
->LastAPTime
= m
->timenow
;
1745 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
1748 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
1750 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
1751 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
1752 rr
->LastMCTime
= m
->timenow
;
1753 rr
->LastMCInterface
= rr
->ImmedAnswer
;
1755 SetNextAnnounceProbeTime(m
, rr
);
1756 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
1760 // *** 2. Loop through interface list, sending records as appropriate
1765 const int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
1767 int numAnnounce
= 0;
1769 mDNSu8
*responseptr
= m
->omsg
.data
;
1771 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
1773 // First Pass. Look for:
1774 // 1. Deregistering records that need to send their goodbye packet
1775 // 2. Updated records that need to retract their old data
1776 // 3. Answers and announcements we need to send
1777 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1779 if (rr
->SendRNow
== intf
->InterfaceID
)
1781 RData
*OldRData
= rr
->resrec
.rdata
;
1782 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
1783 mDNSu8 active
= (mDNSu8
)
1784 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
1785 (m
->SleepState
!= SleepState_Sleeping
|| intf
->SPSAddr
[0].type
|| intf
->SPSAddr
[1].type
|| intf
->SPSAddr
[2].type
));
1787 if (rr
->NewRData
&& active
)
1789 // See if we should send a courtesy "goodbye" for the old data before we replace it.
1790 if (ResourceRecordIsValidAnswer(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
1792 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, 0);
1793 if (newptr
) { responseptr
= newptr
; numDereg
++; rr
->RequireGoodbye
= mDNSfalse
; }
1794 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
1796 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
1799 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1800 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
1801 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, active
? rr
->resrec
.rroriginalttl
: 0);
1802 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
1805 responseptr
= newptr
;
1806 rr
->RequireGoodbye
= active
;
1807 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) numDereg
++;
1808 else if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++; else numAnswer
++;
1811 if (rr
->NewRData
&& active
)
1812 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
1814 // The first time through (pktcount==0), if this record is verified unique
1815 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
1816 if (!pktcount
&& active
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
1817 rr
->SendNSECNow
= mDNSInterfaceMark
;
1819 if (newptr
) // If succeeded in sending, advance to next interface
1821 // If sending on all interfaces, go to next interface; else we're finished now
1822 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
1823 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
1825 rr
->SendRNow
= mDNSNULL
;
1830 // Second Pass. Add additional records, if there's space.
1831 newptr
= responseptr
;
1832 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1833 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
1834 if (ResourceRecordIsValidAnswer(rr
))
1836 // If we have at least one answer already in the packet, then plan to add additionals too
1837 mDNSBool SendAdditional
= (m
->omsg
.h
.numAnswers
> 0);
1839 // If we're not planning to send any additionals, but this record is a unique one, then
1840 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
1841 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
1842 if (!SendAdditional
&& (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
1844 const AuthRecord
*a
;
1845 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
1846 if (a
->LastMCTime
== m
->timenow
&&
1847 a
->LastMCInterface
== intf
->InterfaceID
&&
1848 SameResourceRecordSignature(a
, rr
)) { SendAdditional
= mDNStrue
; break; }
1850 if (!SendAdditional
) // If we don't want to send this after all,
1851 rr
->ImmedAdditional
= mDNSNULL
; // then cancel its ImmedAdditional field
1852 else if (newptr
) // Else, try to add it if we can
1854 // The first time through (pktcount==0), if this record is verified unique
1855 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
1856 if (!pktcount
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
1857 rr
->SendNSECNow
= mDNSInterfaceMark
;
1859 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1860 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
1861 newptr
= PutRR_OS(newptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
1862 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
1865 responseptr
= newptr
;
1866 rr
->ImmedAdditional
= mDNSNULL
;
1867 rr
->RequireGoodbye
= mDNStrue
;
1868 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
1869 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
1870 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
1871 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
1872 rr
->LastMCTime
= m
->timenow
;
1873 rr
->LastMCInterface
= intf
->InterfaceID
;
1878 // Third Pass. Add NSEC records, if there's space.
1879 // When we're generating an NSEC record in response to a specify query for that type
1880 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
1881 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
1882 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1883 if (rr
->SendNSECNow
== mDNSInterfaceMark
|| rr
->SendNSECNow
== intf
->InterfaceID
)
1886 mDNS_SetupResourceRecord(&nsec
, mDNSNULL
, mDNSInterface_Any
, kDNSType_NSEC
, rr
->resrec
.rroriginalttl
, kDNSRecordTypeUnique
, mDNSNULL
, mDNSNULL
);
1887 nsec
.resrec
.rrclass
|= kDNSClass_UniqueRRSet
;
1888 AssignDomainName(&nsec
.namestorage
, rr
->resrec
.name
);
1889 mDNSPlatformMemZero(nsec
.rdatastorage
.u
.nsec
.bitmap
, sizeof(nsec
.rdatastorage
.u
.nsec
.bitmap
));
1890 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
1891 if (ResourceRecordIsValidAnswer(r2
) && SameResourceRecordNameClassInterface(r2
, rr
))
1893 if (r2
->resrec
.rrtype
>= kDNSQType_ANY
) { LogMsg("Can't create NSEC for record %s", ARDisplayString(m
, r2
)); break; }
1894 else nsec
.rdatastorage
.u
.nsec
.bitmap
[r2
->resrec
.rrtype
>> 3] |= 128 >> (r2
->resrec
.rrtype
& 7);
1896 newptr
= responseptr
;
1897 if (!r2
) // If we successfully built our NSEC record, add it to the packet now
1899 newptr
= PutRR_OS(responseptr
, &m
->omsg
.h
.numAdditionals
, &nsec
.resrec
);
1900 if (newptr
) responseptr
= newptr
;
1903 // If we successfully put the NSEC record, clear the SendNSECNow flag
1904 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
1905 if (newptr
|| rr
->SendNSECNow
== mDNSInterfaceMark
)
1907 rr
->SendNSECNow
= mDNSNULL
;
1908 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
1909 for (r2
= rr
->next
; r2
; r2
=r2
->next
)
1910 if (SameResourceRecordNameClassInterface(r2
, rr
))
1911 if (r2
->SendNSECNow
== mDNSInterfaceMark
|| r2
->SendNSECNow
== intf
->InterfaceID
)
1912 r2
->SendNSECNow
= mDNSNULL
;
1916 if (m
->omsg
.h
.numAnswers
|| m
->omsg
.h
.numAdditionals
)
1918 // If we have data to send, add OWNER option if necessary, then send packet
1920 if (OwnerRecordSpace
)
1923 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
1924 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
1925 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
1926 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
1927 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
1928 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
);
1929 if (newptr
) { responseptr
= newptr
; LogSPS("SendResponses put %s", ARDisplayString(m
, &opt
)); }
1930 else if (m
->omsg
.h
.numAnswers
+ m
->omsg
.h
.numAuthorities
+ m
->omsg
.h
.numAdditionals
== 1)
1931 LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
1932 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
1934 LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
1935 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
1938 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
1939 numDereg
, numDereg
== 1 ? "" : "s",
1940 numAnnounce
, numAnnounce
== 1 ? "" : "s",
1941 numAnswer
, numAnswer
== 1 ? "" : "s",
1942 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
1943 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
);
1944 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
);
1945 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
1946 if (++pktcount
>= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
1947 // There might be more things to send on this interface, so go around one more time and try again.
1949 else // Nothing more to send on this interface; go to next
1951 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
1952 #if MDNS_DEBUGMSGS && 0
1953 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
1954 debugf(msg
, intf
, next
);
1957 pktcount
= 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
1962 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
1965 if (m
->CurrentRecord
)
1966 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
1967 m
->CurrentRecord
= m
->ResourceRecords
;
1968 while (m
->CurrentRecord
)
1970 rr
= m
->CurrentRecord
;
1971 m
->CurrentRecord
= rr
->next
;
1975 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
&& rr
->resrec
.InterfaceID
!= mDNSInterface_P2P
)
1976 LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr
->SendRNow
, rr
->resrec
.InterfaceID
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
1977 rr
->SendRNow
= mDNSNULL
;
1980 if (rr
->ImmedAnswer
|| rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1982 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
1984 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->AnnounceCount
== 0)
1986 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
1987 if (!AuthRecord_uDNS(rr
)) CompleteDeregistration(m
, rr
); // Don't touch rr after this
1991 rr
->ImmedAnswer
= mDNSNULL
;
1992 rr
->ImmedUnicast
= mDNSfalse
;
1993 rr
->v4Requester
= zerov4Addr
;
1994 rr
->v6Requester
= zerov6Addr
;
1998 verbosedebugf("SendResponses: Next in %ld ticks", m
->NextScheduledResponse
- m
->timenow
);
2001 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2002 // so we want to be lazy about how frequently we do it.
2003 // 1. If a cache record is currently referenced by *no* active questions,
2004 // then we don't mind expiring it up to a minute late (who will know?)
2005 // 2. Else, if a cache record is due for some of its final expiration queries,
2006 // we'll allow them to be late by up to 2% of the TTL
2007 // 3. Else, if a cache record has completed all its final expiration queries without success,
2008 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2009 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2010 // so allow at most 1/10 second lateness
2011 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2012 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2013 #define CacheCheckGracePeriod(RR) ( \
2014 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
2015 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
2016 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
2017 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
2019 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2021 mDNSexport
void ScheduleNextCacheCheckTime(mDNS
*const m
, const mDNSu32 slot
, const mDNSs32 event
)
2023 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
2024 m
->rrcache_nextcheck
[slot
] = event
;
2025 if (m
->NextCacheCheck
- event
> 0)
2026 m
->NextCacheCheck
= event
;
2029 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2031 // rr->resrec.rroriginalttl
2032 // rr->UnansweredQueries
2033 // rr->CRActiveQuestion
2034 mDNSlocal
void SetNextCacheCheckTimeForRecord(mDNS
*const m
, CacheRecord
*const rr
)
2036 rr
->NextRequiredQuery
= RRExpireTime(rr
);
2038 // If we have an active question, then see if we want to schedule a refresher query for this record.
2039 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2040 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
2042 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
2043 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
2044 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2045 (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
,rr
));
2048 ScheduleNextCacheCheckTime(m
, HashSlot(rr
->resrec
.name
), NextCacheCheckEvent(rr
));
2051 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
2052 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
2053 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
2054 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2056 mDNSlocal mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
2058 if (interval
< kMinimumReconfirmTime
)
2059 interval
= kMinimumReconfirmTime
;
2060 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
2061 interval
= 0x10000000;
2063 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2064 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
2066 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2067 // For all the reconfirmations in a given batch, we want to use the same random value
2068 // so that the reconfirmation questions can be grouped into a single query packet
2069 if (!m
->RandomReconfirmDelay
) m
->RandomReconfirmDelay
= 1 + mDNSRandom(0x3FFFFFFF);
2070 interval
+= m
->RandomReconfirmDelay
% ((interval
/3) + 1);
2071 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
2072 rr
->resrec
.rroriginalttl
= (interval
* 4 + mDNSPlatformOneSecond
- 1) / mDNSPlatformOneSecond
;
2073 SetNextCacheCheckTimeForRecord(m
, rr
);
2075 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2076 RRExpireTime(rr
) - m
->timenow
, CRDisplayString(m
, rr
), rr
->CRActiveQuestion
);
2077 return(mStatus_NoError
);
2080 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
2082 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2083 // It also appends to the list of known answer records that need to be included,
2084 // and updates the forcast for the size of the known answer section.
2085 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, DNSMessage
*query
, mDNSu8
**queryptr
, DNSQuestion
*q
,
2086 CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
2088 mDNSBool ucast
= (q
->LargeAnswers
|| q
->RequestUnicast
) && m
->CanReceiveUnicastOn5353
;
2089 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
2090 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
2091 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
- *answerforecast
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
2094 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
2099 mDNSu32 forecast
= *answerforecast
;
2100 const mDNSu32 slot
= HashSlot(&q
->qname
);
2101 const CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
2103 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
2105 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
2106 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
2107 !(rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && // which is a shared (i.e. not unique) record type
2108 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not already in the known answer list
2109 rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
2110 SameNameRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
2111 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
> // and its half-way-to-expiry time is at least 1 second away
2112 mDNSPlatformOneSecond
) // (also ensures we never include goodbye records with TTL=1)
2114 // We don't want to include unique records in the Known Answer section. The Known Answer section
2115 // is intended to suppress floods of shared-record replies from many other devices on the network.
2116 // That concept really does not apply to unique records, and indeed if we do send a query for
2117 // which we have a unique record already in our cache, then including that unique record as a
2118 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2120 *ka
= rr
; // Link this record into our known answer chain
2121 ka
= &rr
->NextInKAList
;
2122 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2123 forecast
+= 12 + rr
->resrec
.rdestimate
;
2124 // If we're trying to put more than one question in this packet, and it doesn't fit
2125 // then undo that last question and try again next time
2126 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
2128 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2129 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
);
2130 query
->h
.numQuestions
--;
2131 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
2132 while (*ka
) { CacheRecord
*c
= *ka
; *ka
= mDNSNULL
; ka
= &c
->NextInKAList
; }
2133 return(mDNSfalse
); // Return false, so we'll try again in the next packet
2137 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2138 *queryptr
= newptr
; // Update the packet pointer
2139 *answerforecast
= forecast
; // Update the forecast
2140 *kalistptrptr
= ka
; // Update the known answer list pointer
2141 if (ucast
) q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
2143 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // For every resource record in our cache,
2144 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
2145 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not in the known answer list
2146 SameNameRecordAnswersQuestion(&rr
->resrec
, q
)) // which answers our question
2148 rr
->UnansweredQueries
++; // indicate that we're expecting a response
2149 rr
->LastUnansweredTime
= m
->timenow
;
2150 SetNextCacheCheckTimeForRecord(m
, rr
);
2157 // When we have a query looking for a specified name, but there appear to be no answers with
2158 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2159 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
2160 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2161 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2162 // A typical reconfirmation scenario might go like this:
2163 // Depth 0: Name "myhost.local" has no address records
2164 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2165 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2166 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2167 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2168 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2169 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const int depth
)
2174 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth
, name
->c
);
2175 FORALL_CACHERECORDS(slot
, cg
, cr
)
2177 domainname
*crtarget
= GetRRDomainNameTarget(&cr
->resrec
);
2178 if (crtarget
&& cr
->resrec
.rdatahash
== namehash
&& SameDomainName(crtarget
, name
))
2180 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth
, CRDisplayString(m
, cr
));
2181 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
2182 if (depth
< 5) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, depth
+1);
2187 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2188 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
2189 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2190 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2191 mDNSlocal
const CacheRecord
*CacheHasAddressTypeForName(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
2193 CacheGroup
*const cg
= CacheGroupForName(m
, HashSlot(name
), namehash
, name
);
2194 const CacheRecord
*cr
= cg
? cg
->members
: mDNSNULL
;
2195 while (cr
&& !RRTypeIsAddressType(cr
->resrec
.rrtype
)) cr
=cr
->next
;
2199 mDNSlocal
const CacheRecord
*FindSPSInCache1(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*const c0
, const CacheRecord
*const c1
)
2201 CacheGroup
*const cg
= CacheGroupForName(m
, HashSlot(&q
->qname
), q
->qnamehash
, &q
->qname
);
2202 const CacheRecord
*cr
, *bestcr
= mDNSNULL
;
2203 mDNSu32 bestmetric
= 1000000;
2204 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
2205 if (cr
->resrec
.rrtype
== kDNSType_PTR
&& cr
->resrec
.rdlength
>= 6) // If record is PTR type, with long enough name,
2206 if (cr
!= c0
&& cr
!= c1
) // that's not one we've seen before,
2207 if (SameNameRecordAnswersQuestion(&cr
->resrec
, q
)) // and answers our browse query,
2208 if (!IdenticalSameNameRecord(&cr
->resrec
, &m
->SPSRecords
.RR_PTR
.resrec
)) // and is not our own advertised service...
2210 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
2211 if (bestmetric
> metric
) { bestmetric
= metric
; bestcr
= cr
; }
2216 // Finds the three best Sleep Proxies we currently have in our cache
2217 mDNSexport
void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3])
2219 sps
[0] = FindSPSInCache1(m
, q
, mDNSNULL
, mDNSNULL
);
2220 sps
[1] = !sps
[0] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], mDNSNULL
);
2221 sps
[2] = !sps
[1] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], sps
[1]);
2224 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2225 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
2228 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
2231 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
2234 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
2237 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
2240 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2241 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2242 for (i
=0; i
<DupSuppressInfoSize
; i
++)
2243 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
2245 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
2246 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
2247 if (v4
&& v6
) return(mDNStrue
);
2252 mDNSlocal
int RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
2256 // See if we have this one in our list somewhere already
2257 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
2259 // If not, find a slot we can re-use
2260 if (i
>= DupSuppressInfoSize
)
2263 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
2264 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
2268 // Record the info about this query we saw
2270 ds
[i
].InterfaceID
= InterfaceID
;
2276 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
2278 // If more than 90% of the way to the query time, we should unconditionally accelerate it
2279 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
2282 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2283 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
2285 // We forecast: qname (n) type (2) class (2)
2286 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
2287 const mDNSu32 slot
= HashSlot(&q
->qname
);
2288 const CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
2289 const CacheRecord
*rr
;
2290 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
2291 if (rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
2292 SameNameRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
2293 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
2294 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0)// and we'll ask at least once again before NextRequiredQuery
2296 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2297 forecast
+= 12 + rr
->resrec
.rdestimate
;
2298 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
2306 // How Standard Queries are generated:
2307 // 1. The Question Section contains the question
2308 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
2310 // How Probe Queries are generated:
2311 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2312 // if some other host is already using *any* records with this name, we want to know about it.
2313 // 2. The Authority Section contains the proposed values we intend to use for one or more
2314 // of our records with that name (analogous to the Update section of DNS Update packets)
2315 // because if some other host is probing at the same time, we each want to know what the other is
2316 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2318 mDNSlocal
void SendQueries(mDNS
*const m
)
2326 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2327 mDNSs32 maxExistingQuestionInterval
= 0;
2328 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2329 CacheRecord
*KnownAnswerList
= mDNSNULL
;
2331 // 1. If time for a query, work out what we need to do
2333 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
2334 // to their NextRequiredQuery to be worth batching them together with this one
2335 FORALL_CACHERECORDS(slot
, cg
, cr
)
2336 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
2337 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
2339 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
2340 q
= cr
->CRActiveQuestion
;
2341 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(cr
)/20, cr
->resrec
.InterfaceID
);
2342 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2343 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2344 if (q
->Target
.type
) q
->SendQNow
= mDNSInterfaceMark
; // If targeted query, mark it
2345 else if (!mDNSOpaque16IsZero(q
->TargetQID
)) { q
->LastQTime
= m
->timenow
- q
->ThisQInterval
; cr
->UnansweredQueries
++; }
2346 else if (q
->SendQNow
== mDNSNULL
) q
->SendQNow
= cr
->resrec
.InterfaceID
;
2347 else if (q
->SendQNow
!= cr
->resrec
.InterfaceID
) q
->SendQNow
= mDNSInterfaceMark
;
2350 // Scan our list of questions to see which:
2351 // *WideArea* queries need to be sent
2352 // *unicast* queries need to be sent
2353 // *multicast* queries we're definitely going to send
2354 if (m
->CurrentQuestion
)
2355 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2356 m
->CurrentQuestion
= m
->Questions
;
2357 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
2359 q
= m
->CurrentQuestion
;
2360 if (q
->Target
.type
&& (q
->SendQNow
|| TimeToSendThisQuestion(q
, m
->timenow
)))
2362 mDNSu8
*qptr
= m
->omsg
.data
;
2363 const mDNSu8
*const limit
= m
->omsg
.data
+ sizeof(m
->omsg
.data
);
2365 // 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
2366 if (!q
->LocalSocket
) q
->LocalSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
2369 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, QueryFlags
);
2370 qptr
= putQuestion(&m
->omsg
, qptr
, limit
, &q
->qname
, q
->qtype
, q
->qclass
);
2371 mDNSSendDNSMessage(m
, &m
->omsg
, qptr
, mDNSInterface_Any
, q
->LocalSocket
, &q
->Target
, q
->TargetPort
, mDNSNULL
, mDNSNULL
);
2372 q
->ThisQInterval
*= QuestionIntervalStep
;
2374 if (q
->ThisQInterval
> MaxQuestionInterval
)
2375 q
->ThisQInterval
= MaxQuestionInterval
;
2376 q
->LastQTime
= m
->timenow
;
2377 q
->LastQTxTime
= m
->timenow
;
2378 q
->RecentAnswerPkts
= 0;
2379 q
->SendQNow
= mDNSNULL
;
2380 q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
2382 else if (mDNSOpaque16IsZero(q
->TargetQID
) && !q
->Target
.type
&& TimeToSendThisQuestion(q
, m
->timenow
))
2384 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2385 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
2386 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
2387 maxExistingQuestionInterval
= q
->ThisQInterval
;
2389 // If m->CurrentQuestion wasn't modified out from under us, advance it now
2390 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
2391 // m->CurrentQuestion point to the right question
2392 if (q
== m
->CurrentQuestion
) m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
2394 while (m
->CurrentQuestion
)
2396 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2397 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
2399 m
->CurrentQuestion
= mDNSNULL
;
2401 // Scan our list of questions
2402 // (a) to see if there are any more that are worth accelerating, and
2403 // (b) to update the state variables for *all* the questions we're going to send
2404 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
2405 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
2406 // 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.
2407 m
->NextScheduledQuery
= m
->timenow
+ 0x78000000;
2408 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
2410 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
||
2411 (!q
->Target
.type
&& ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
))))
2413 // If at least halfway to next query time, advance to next interval
2414 // If less than halfway to next query time, then
2415 // treat this as logically a repeat of the last transmission, without advancing the interval
2416 if (m
->timenow
- (q
->LastQTime
+ (q
->ThisQInterval
/2)) >= 0)
2418 //LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
2419 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
2420 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
2421 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
/ InitialQuestionInterval
, q
->RequestUnicast
);
2422 q
->ThisQInterval
*= QuestionIntervalStep
;
2423 if (q
->ThisQInterval
> MaxQuestionInterval
)
2424 q
->ThisQInterval
= MaxQuestionInterval
;
2425 else if (q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* QuestionIntervalStep3
&& !q
->RequestUnicast
&&
2426 !(RRTypeIsAddressType(q
->qtype
) && CacheHasAddressTypeForName(m
, &q
->qname
, q
->qnamehash
)))
2428 // Generally don't need to log this.
2429 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
2430 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
2431 // and when there simply happen to be no instances of the service the client is looking
2432 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
2433 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
2434 q
->qname
.c
, DNSTypeName(q
->qtype
));
2435 // Sending third query, and no answers yet; time to begin doubting the source
2436 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
2440 // Mark for sending. (If no active interfaces, then don't even try.)
2441 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
2444 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
2445 q
->LastQTime
= m
->timenow
;
2448 // If we recorded a duplicate suppression for this question less than half an interval ago,
2449 // then we consider it recent enough that we don't need to do an identical query ourselves.
2450 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
2452 q
->LastQTxTime
= m
->timenow
;
2453 q
->RecentAnswerPkts
= 0;
2454 if (q
->RequestUnicast
) q
->RequestUnicast
--;
2456 // For all questions (not just the ones we're sending) check what the next scheduled event will be
2457 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
2458 SetNextQueryTime(m
,q
);
2461 // 2. Scan our authoritative RR list to see what probes we might need to send
2463 m
->NextScheduledProbe
= m
->timenow
+ 0x78000000;
2465 if (m
->CurrentRecord
)
2466 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2467 m
->CurrentRecord
= m
->ResourceRecords
;
2468 while (m
->CurrentRecord
)
2470 ar
= m
->CurrentRecord
;
2471 m
->CurrentRecord
= ar
->next
;
2472 if (!AuthRecord_uDNS(ar
) && ar
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
2474 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
2475 if (m
->timenow
- (ar
->LastAPTime
+ ar
->ThisAPInterval
) < 0)
2477 SetNextAnnounceProbeTime(m
, ar
);
2479 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
2480 else if (ar
->ProbeCount
)
2482 if (ar
->AddressProxy
.type
== mDNSAddrType_IPv4
)
2484 LogSPS("SendQueries ARP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
2485 SendARP(m
, 1, ar
, &zerov4Addr
, &zeroEthAddr
, &ar
->AddressProxy
.ip
.v4
, &ar
->WakeUp
.IMAC
);
2487 else if (ar
->AddressProxy
.type
== mDNSAddrType_IPv6
)
2489 LogSPS("SendQueries NDP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
2490 // IPv6 source = zero
2491 // No target hardware address
2492 // IPv6 target address is address we're probing
2493 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
2494 SendNDP(m
, NDP_Sol
, 0, ar
, &zerov6Addr
, mDNSNULL
, &ar
->AddressProxy
.ip
.v6
, &ar
->WakeUp
.IMAC
);
2496 // Mark for sending. (If no active interfaces, then don't even try.)
2497 ar
->SendRNow
= (!intf
|| ar
->WakeUp
.HMAC
.l
[0]) ? mDNSNULL
: ar
->resrec
.InterfaceID
? ar
->resrec
.InterfaceID
: intf
->InterfaceID
;
2498 ar
->LastAPTime
= m
->timenow
;
2499 // When we have a late conflict that resets a record to probing state we use a special marker value greater
2500 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
2501 if (ar
->ProbeCount
> DefaultProbeCountForTypeUnique
)
2502 ar
->ProbeCount
= DefaultProbeCountForTypeUnique
;
2504 SetNextAnnounceProbeTime(m
, ar
);
2505 if (ar
->ProbeCount
== 0)
2507 // If this is the last probe for this record, then see if we have any matching records
2508 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
2510 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
2511 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, ar
))
2513 // ... then acknowledge this record to the client.
2514 // We do this optimistically, just as we're about to send the third probe.
2515 // This helps clients that both advertise and browse, and want to filter themselves
2516 // from the browse results list, because it helps ensure that the registration
2517 // confirmation will be delivered 1/4 second *before* the browse "add" event.
2518 // A potential downside is that we could deliver a registration confirmation and then find out
2519 // moments later that there's a name conflict, but applications have to be prepared to handle
2520 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
2521 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
);
2524 // else, if it has now finished probing, move it to state Verified,
2525 // and update m->NextScheduledResponse so it will be announced
2528 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
); // Defensive, just in case it got missed somehow
2529 ar
->resrec
.RecordType
= kDNSRecordTypeVerified
;
2530 ar
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
2531 ar
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
2532 SetNextAnnounceProbeTime(m
, ar
);
2536 m
->CurrentRecord
= m
->DuplicateRecords
;
2537 while (m
->CurrentRecord
)
2539 ar
= m
->CurrentRecord
;
2540 m
->CurrentRecord
= ar
->next
;
2541 if (ar
->resrec
.RecordType
== kDNSRecordTypeUnique
&& ar
->ProbeCount
== 0 && !ar
->Acknowledged
)
2542 AcknowledgeRecord(m
, ar
);
2545 // 3. Now we know which queries and probes we're sending,
2546 // go through our interface list sending the appropriate queries on each interface
2549 const int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
2550 mDNSu8
*queryptr
= m
->omsg
.data
;
2551 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, QueryFlags
);
2552 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
2553 if (!KnownAnswerList
)
2555 // Start a new known-answer list
2556 CacheRecord
**kalistptr
= &KnownAnswerList
;
2557 mDNSu32 answerforecast
= OwnerRecordSpace
; // We start by assuming we'll need at least enough space to put the Owner Option
2559 // Put query questions in this packet
2560 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
2562 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
== intf
->InterfaceID
))
2564 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
2565 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
2566 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- m
->omsg
.data
, queryptr
+ answerforecast
- m
->omsg
.data
);
2568 // If we're suppressing this question, or we successfully put it, update its SendQNow state
2569 if (SuppressOnThisInterface(q
->DupSuppress
, intf
) ||
2570 BuildQuestion(m
, &m
->omsg
, &queryptr
, q
, &kalistptr
, &answerforecast
))
2571 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
2575 // Put probe questions in this packet
2576 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
2577 if (ar
->SendRNow
== intf
->InterfaceID
)
2579 mDNSBool ucast
= (ar
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1) && m
->CanReceiveUnicastOn5353
;
2580 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
2581 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.numQuestions
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
2582 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2583 mDNSu32 forecast
= answerforecast
+ 12 + ar
->resrec
.rdestimate
;
2584 mDNSu8
*newptr
= putQuestion(&m
->omsg
, queryptr
, limit
- forecast
, ar
->resrec
.name
, kDNSQType_ANY
, (mDNSu16
)(ar
->resrec
.rrclass
| ucbit
));
2588 answerforecast
= forecast
;
2589 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
2590 ar
->IncludeInProbe
= mDNStrue
;
2591 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d",
2592 ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
), ar
->ProbeCount
);
2597 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
2598 while (KnownAnswerList
)
2600 CacheRecord
*ka
= KnownAnswerList
;
2601 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- ka
->TimeRcvd
)) / mDNSPlatformOneSecond
;
2602 mDNSu8
*newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAnswers
,
2603 &ka
->resrec
, ka
->resrec
.rroriginalttl
- SecsSinceRcvd
, m
->omsg
.data
+ NormalMaxDNSMessageData
- OwnerRecordSpace
);
2606 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
2607 ka
->resrec
.name
->c
, DNSTypeName(ka
->resrec
.rrtype
), queryptr
- m
->omsg
.data
, newptr
- m
->omsg
.data
);
2609 KnownAnswerList
= ka
->NextInKAList
;
2610 ka
->NextInKAList
= mDNSNULL
;
2614 // If we ran out of space and we have more than one question in the packet, that's an error --
2615 // we shouldn't have put more than one question if there was a risk of us running out of space.
2616 if (m
->omsg
.h
.numQuestions
> 1)
2617 LogMsg("SendQueries: Put %d answers; No more space for known answers", m
->omsg
.h
.numAnswers
);
2618 m
->omsg
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
2623 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
2624 if (ar
->IncludeInProbe
)
2626 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, &ar
->resrec
);
2627 ar
->IncludeInProbe
= mDNSfalse
;
2628 if (newptr
) queryptr
= newptr
;
2629 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m
,ar
));
2632 if (queryptr
> m
->omsg
.data
)
2634 if (OwnerRecordSpace
)
2637 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
2638 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
2639 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
2640 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
2641 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
2642 LogSPS("SendQueries putting %s", ARDisplayString(m
, &opt
));
2643 queryptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAdditionals
,
2644 &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
2646 LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
2647 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
2648 if (queryptr
> m
->omsg
.data
+ NormalMaxDNSMessageData
)
2649 if (m
->omsg
.h
.numQuestions
!= 1 || m
->omsg
.h
.numAnswers
!= 0 || m
->omsg
.h
.numAuthorities
!= 1 || m
->omsg
.h
.numAdditionals
!= 1)
2650 LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
2651 m
->omsg
.data
, m
->omsg
.data
+ NormalMaxDNSMessageData
, queryptr
,
2652 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
2655 if ((m
->omsg
.h
.flags
.b
[0] & kDNSFlag0_TC
) && m
->omsg
.h
.numQuestions
> 1)
2656 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m
->omsg
.h
.numQuestions
);
2657 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
2658 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
2659 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
2660 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAuthorities
== 1 ? "" : "s", intf
->InterfaceID
);
2661 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
);
2662 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
);
2663 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
2664 if (++pktcount
>= 1000)
2665 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
2666 // There might be more records left in the known answer list, or more questions to send
2667 // on this interface, so go around one more time and try again.
2669 else // Nothing more to send on this interface; go to next
2671 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
2672 #if MDNS_DEBUGMSGS && 0
2673 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
2674 debugf(msg
, intf
, next
);
2680 // 4. Final housekeeping
2682 // 4a. Debugging check: Make sure we announced all our records
2683 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
2686 if (ar
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
&& ar
->resrec
.InterfaceID
!= mDNSInterface_P2P
)
2687 LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar
->SendRNow
, ar
->resrec
.InterfaceID
, ARDisplayString(m
, ar
));
2688 ar
->SendRNow
= mDNSNULL
;
2691 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
2692 // that their interface which went away might come back again, the logic will want to send queries
2693 // for those records, but we can't because their interface isn't here any more, so to keep the
2694 // state machine ticking over we just pretend we did so.
2695 // If the interface does not come back in time, the cache record will expire naturally
2696 FORALL_CACHERECORDS(slot
, cg
, cr
)
2697 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
2698 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
2700 cr
->UnansweredQueries
++;
2701 cr
->CRActiveQuestion
->SendQNow
= mDNSNULL
;
2702 SetNextCacheCheckTimeForRecord(m
, cr
);
2705 // 4c. Debugging check: Make sure we sent all our planned questions
2706 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
2707 // we legitimately couldn't send because the interface is no longer available
2708 for (q
= m
->Questions
; q
; q
=q
->next
)
2712 for (x
= m
->NewQuestions
; x
; x
=x
->next
) if (x
== q
) break; // Check if this question is a NewQuestion
2713 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
));
2714 q
->SendQNow
= mDNSNULL
;
2718 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
)
2721 mDNSu8
*ptr
= m
->omsg
.data
;
2722 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
2723 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID
); return; }
2725 // 0x00 Destination address
2726 for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
2728 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2729 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
2731 // 0x0C Ethertype (0x0842)
2735 // 0x0E Wakeup sync sequence
2736 for (i
=0; i
<6; i
++) *ptr
++ = 0xFF;
2739 for (j
=0; j
<16; j
++) for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
2742 for (i
=0; i
<6; i
++) *ptr
++ = password
->b
[i
];
2744 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
2746 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
2747 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
2748 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
2749 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
2750 // So, we send one of each, unicast first, then broadcast second.
2751 for (i
=0; i
<6; i
++) m
->omsg
.data
[i
] = 0xFF;
2752 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
2755 // ***************************************************************************
2756 #if COMPILER_LIKES_PRAGMA_MARK
2758 #pragma mark - RR List Management & Task Management
2761 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
2762 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
2763 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
2764 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
2765 mDNSexport
void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
)
2767 DNSQuestion
*const q
= m
->CurrentQuestion
;
2768 mDNSBool followcname
= rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& AddRecord
&&
2769 rr
->resrec
.rrtype
== kDNSType_CNAME
&& q
->qtype
!= kDNSType_CNAME
;
2770 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
2771 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", rr
->resrec
.rroriginalttl
, CRDisplayString(m
, rr
));
2773 if (QuerySuppressed(q
)) return;
2775 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
2776 // may be called twice, once when the record is received, and again when it's time to notify local clients.
2777 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
2779 rr
->LastUsed
= m
->timenow
;
2780 if (AddRecord
== QC_add
&& !q
->DuplicateOf
&& rr
->CRActiveQuestion
!= q
)
2782 if (!rr
->CRActiveQuestion
) m
->rrcache_active
++; // If not previously active, increment rrcache_active count
2783 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
2784 rr
->CRActiveQuestion
, q
, CRDisplayString(m
,rr
), q
->CurrentAnswers
);
2785 rr
->CRActiveQuestion
= q
; // We know q is non-null
2786 SetNextCacheCheckTimeForRecord(m
, rr
);
2790 // (a) a no-cache add, where we've already done at least one 'QM' query, or
2791 // (b) a normal add, where we have at least one unique-type answer,
2792 // then there's no need to keep polling the network.
2793 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
2794 // We do this for mDNS questions and uDNS one-shot questions, but not for
2795 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
2796 if ((AddRecord
== QC_addnocache
&& !q
->RequestUnicast
) ||
2797 (AddRecord
== QC_add
&& (q
->ExpectUnique
|| (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))))
2798 if (ActiveQuestion(q
) && (mDNSOpaque16IsZero(q
->TargetQID
) || !q
->LongLived
))
2800 q
->LastQTime
= m
->timenow
;
2801 q
->LastQTxTime
= m
->timenow
;
2802 q
->RecentAnswerPkts
= 0;
2803 q
->ThisQInterval
= MaxQuestionInterval
;
2804 q
->RequestUnicast
= mDNSfalse
;
2805 debugf("AnswerCurrentQuestionWithResourceRecord: Set MaxQuestionInterval for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
2808 if (rr
->DelayDelivery
) return; // We'll come back later when CacheRecordDeferredAdd() calls us
2810 // Only deliver negative answers if client has explicitly requested them
2811 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
|| (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
)))
2812 if (!AddRecord
|| !q
->ReturnIntermed
) return;
2814 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
2815 if (q
->QuestionCallback
&& !q
->NoAnswer
&& (!followcname
|| q
->ReturnIntermed
))
2817 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
2818 if (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
))
2821 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->qDNSServer
);
2822 q
->QuestionCallback(m
, q
, &neg
.resrec
, AddRecord
);
2825 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
2826 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2828 // Note: Proceed with caution here because client callback function is allowed to do anything,
2829 // including starting/stopping queries, registering/deregistering records, etc.
2831 if (followcname
&& m
->CurrentQuestion
== q
)
2833 const mDNSBool selfref
= SameDomainName(&q
->qname
, &rr
->resrec
.rdata
->u
.name
);
2834 if (q
->CNAMEReferrals
>= 10 || selfref
)
2835 LogMsg("AnswerCurrentQuestionWithResourceRecord: %p %##s (%s) NOT following CNAME referral %d%s for %s",
2836 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CNAMEReferrals
, selfref
? " (Self-Referential)" : "", CRDisplayString(m
, rr
));
2839 const mDNSu32 c
= q
->CNAMEReferrals
+ 1; // Stash a copy of the new q->CNAMEReferrals value
2841 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
2842 // themselves. Without that check we can get into a case where we have two duplicate questions,
2843 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
2844 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
2845 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
2846 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
2847 // for either of them. This is not a problem for CNAME loops of two or more records because in
2848 // those cases the newly re-appended question A has a different target name and therefore cannot be
2849 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
2851 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
2852 // and track CNAMEs coming and going, we should really create a subordinate query here,
2853 // which we would subsequently cancel and retract if the CNAME referral record were removed.
2854 // In reality this is such a corner case we'll ignore it until someone actually needs it.
2855 LogInfo("AnswerCurrentQuestionWithResourceRecord: %p %##s (%s) following CNAME referral %d for %s",
2856 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CNAMEReferrals
, CRDisplayString(m
, rr
));
2858 mDNS_StopQuery_internal(m
, q
); // Stop old query
2859 AssignDomainName(&q
->qname
, &rr
->resrec
.rdata
->u
.name
); // Update qname
2860 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
2861 // If a unicast query results in a CNAME that points to a .local, we need to re-try
2862 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
2863 // to try this as unicast query even though it is a .local name
2864 if (!mDNSOpaque16IsZero(q
->TargetQID
) && IsLocalDomain(&q
->qname
))
2866 LogInfo("AnswerCurrentQuestionWithResourceRecord: Resolving a .local CNAME %p %##s (%s) CacheRecord %s",
2867 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), CRDisplayString(m
, rr
));
2868 q
->InterfaceID
= mDNSInterface_Unicast
;
2870 mDNS_StartQuery_internal(m
, q
); // start new query
2871 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
2872 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
2873 q
->CNAMEReferrals
= c
;
2878 // New Questions are answered through AnswerNewQuestion. But there may not have been any
2879 // matching cache records for the questions when it is called. There are two possibilities.
2881 // 1) There are no cache records
2882 // 2) There are cache records but the DNSServers between question and cache record don't match.
2884 // In the case of (1), where there are no cache records and later we add them when we get a response,
2885 // CacheRecordAdd/CacheRecordDeferredAdd will take care of adding the cache and delivering the ADD
2886 // events to the application. If we already have a cache entry, then no ADD events are delivered
2887 // unless the RDATA has changed
2889 // In the case of (2) where we had the cache records and did not answer because of the DNSServer mismatch,
2890 // we need to answer them whenever we change the DNSServer. But we can't do it at the instant the DNSServer
2891 // changes because when we do the callback, the question can get deleted and the calling function would not
2892 // know how to handle it. So, we run this function from mDNS_Execute to handle DNSServer changes on the
2895 mDNSlocal
void AnswerQuestionsForDNSServerChanges(mDNS
*const m
)
2903 if (m
->CurrentQuestion
)
2904 LogMsg("AnswerQuestionsForDNSServerChanges: ERROR m->CurrentQuestion already set: %##s (%s)",
2905 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2907 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
= qnext
)
2911 // multicast or DNSServers did not change.
2912 if (mDNSOpaque16IsZero(q
->TargetQID
)) continue;
2913 if (!q
->deliverAddEvents
) continue;
2915 // We are going to look through the cache for this question since it changed
2916 // its DNSserver last time. Reset it so that we don't call them again. Calling
2917 // them again will deliver duplicate events to the application
2918 q
->deliverAddEvents
= mDNSfalse
;
2919 if (QuerySuppressed(q
)) continue;
2920 m
->CurrentQuestion
= q
;
2921 slot
= HashSlot(&q
->qname
);
2922 cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
2923 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
2925 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
2927 LogInfo("AnswerQuestionsForDNSServerChanges: Calling AnswerCurrentQuestionWithResourceRecord for question %p %##s using resource record %s",
2928 q
, q
->qname
.c
, CRDisplayString(m
, rr
));
2929 // When this question penalizes a DNS server and has no more DNS servers to pick, we normally
2930 // deliver a negative cache response and suspend the question for 60 seconds (see uDNS_CheckCurrentQuestion).
2931 // But sometimes we may already find the negative cache entry and deliver that here as the process
2932 // of changing DNS servers. When the cache entry is about to expire, we will resend the question and
2933 // that time, we need to make sure that we have a valid DNS server. Otherwise, we will deliver
2934 // a negative cache response without trying the server.
2935 if (!q
->qDNSServer
&& !q
->DuplicateOf
&& rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
2938 SetValidDNSServers(m
, q
);
2939 q
->qDNSServer
= GetServerForQuestion(m
, q
);
2940 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
2941 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
2943 q
->CurrentAnswers
++;
2944 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
2945 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
2946 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
2947 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
2951 m
->CurrentQuestion
= mDNSNULL
;
2954 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*rr
)
2956 rr
->DelayDelivery
= 0;
2957 if (m
->CurrentQuestion
)
2958 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
2959 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2960 m
->CurrentQuestion
= m
->Questions
;
2961 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
2963 DNSQuestion
*q
= m
->CurrentQuestion
;
2964 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
2965 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
2966 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
2967 m
->CurrentQuestion
= q
->next
;
2969 m
->CurrentQuestion
= mDNSNULL
;
2972 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSu32 slot
)
2974 const mDNSs32 threshhold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
2975 const mDNSs32 start
= m
->timenow
- 0x10000000;
2976 mDNSs32 delay
= start
;
2977 CacheGroup
*cg
= CacheGroupForName(m
, slot
, namehash
, name
);
2978 const CacheRecord
*rr
;
2979 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
2980 if (threshhold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
2981 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
2982 delay
= RRExpireTime(rr
);
2983 if (delay
- start
> 0) return(NonZeroTime(delay
));
2987 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
2988 // If new questions are created as a result of invoking client callbacks, they will be added to
2989 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
2990 // rr is a new CacheRecord just received into our cache
2991 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
2992 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
2993 // which may change the record list and/or question list.
2994 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2995 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
2999 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3000 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3001 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3003 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3005 // If this question is one that's actively sending queries, and it's received ten answers within one
3006 // second of sending the last query packet, then that indicates some radical network topology change,
3007 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3008 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3009 // because we will anyway send another query within a few seconds. The first reset query is sent out
3010 // randomized over the next four seconds to reduce possible synchronization between machines.
3011 if (q
->LastAnswerPktNum
!= m
->PktNum
)
3013 q
->LastAnswerPktNum
= m
->PktNum
;
3014 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
3015 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
3017 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3018 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
3019 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
3020 q
->ThisQInterval
= InitialQuestionInterval
;
3021 SetNextQueryTime(m
,q
);
3024 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr
, rr
->resrec
.name
->c
,
3025 DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
, rr
->resrec
.rDNSServer
?
3026 &rr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(rr
->resrec
.rDNSServer
?
3027 rr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
3028 q
->CurrentAnswers
++;
3029 q
->unansweredQueries
= 0;
3030 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
3031 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
3032 if (q
->CurrentAnswers
> 4000)
3034 static int msgcount
= 0;
3035 if (msgcount
++ < 10)
3036 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3037 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
3038 rr
->resrec
.rroriginalttl
= 0;
3039 rr
->UnansweredQueries
= MaxUnansweredQueries
;
3044 if (!rr
->DelayDelivery
)
3046 if (m
->CurrentQuestion
)
3047 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3048 m
->CurrentQuestion
= m
->Questions
;
3049 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3051 q
= m
->CurrentQuestion
;
3052 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3053 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
3054 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3055 m
->CurrentQuestion
= q
->next
;
3057 m
->CurrentQuestion
= mDNSNULL
;
3060 SetNextCacheCheckTimeForRecord(m
, rr
);
3063 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3064 // If new questions are created as a result of invoking client callbacks, they will be added to
3065 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3066 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3067 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3068 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3069 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3070 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3071 // which may change the record list and/or question list.
3072 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3073 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*rr
)
3075 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
3076 if (m
->CurrentQuestion
)
3077 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3078 m
->CurrentQuestion
= m
->Questions
;
3079 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
3080 // since we're not caching the record and we'll get no opportunity to do this later
3081 while (m
->CurrentQuestion
)
3083 DNSQuestion
*q
= m
->CurrentQuestion
;
3084 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3085 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
3086 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3087 m
->CurrentQuestion
= q
->next
;
3089 m
->CurrentQuestion
= mDNSNULL
;
3092 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3093 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3094 // If new questions are created as a result of invoking client callbacks, they will be added to
3095 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3096 // rr is an existing cache CacheRecord that just expired and is being deleted
3097 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3098 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3099 // which may change the record list and/or question list.
3100 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3101 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
3103 if (m
->CurrentQuestion
)
3104 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3105 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3106 m
->CurrentQuestion
= m
->Questions
;
3108 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3109 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3110 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3112 DNSQuestion
*q
= m
->CurrentQuestion
;
3113 // When a question enters suppressed state, we generate RMV events and generate a negative
3114 // response. A cache may be present that answers this question e.g., cache entry generated
3115 // before the question became suppressed. We need to skip the suppressed questions here as
3116 // the RMV event has already been generated.
3117 if (!QuerySuppressed(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3119 verbosedebugf("CacheRecordRmv %p %s", rr
, CRDisplayString(m
, rr
));
3120 q
->FlappingInterface1
= mDNSNULL
;
3121 q
->FlappingInterface2
= mDNSNULL
;
3123 // When a question changes DNS server, it is marked with deliverAddEvents if we find any
3124 // cache entry corresponding to the new DNS server. Before we deliver the ADD event, the
3125 // cache entry may be removed in which case CurrentAnswers can be zero.
3126 if (q
->deliverAddEvents
&& !q
->CurrentAnswers
)
3128 LogInfo("CacheRecordRmv: Question %p %##s (%s) deliverAddEvents set, DNSServer %#a:%d",
3129 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
3130 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
3131 m
->CurrentQuestion
= q
->next
;
3134 if (q
->CurrentAnswers
== 0)
3135 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3136 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
3137 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
3140 q
->CurrentAnswers
--;
3141 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
3142 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
3144 if (rr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
3146 if (q
->CurrentAnswers
== 0)
3148 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3149 q
->qname
.c
, DNSTypeName(q
->qtype
));
3150 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
3152 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
3155 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3156 m
->CurrentQuestion
= q
->next
;
3158 m
->CurrentQuestion
= mDNSNULL
;
3161 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
3163 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3165 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
3167 e
->next
= m
->rrcache_free
;
3168 m
->rrcache_free
= e
;
3169 m
->rrcache_totalused
--;
3172 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
3174 CacheEntity
*e
= (CacheEntity
*)(*cp
);
3175 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3176 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
3177 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3178 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
3179 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3180 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
3181 (*cp
)->name
= mDNSNULL
;
3182 *cp
= (*cp
)->next
; // Cut record from list
3183 ReleaseCacheEntity(m
, e
);
3186 mDNSlocal
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
3188 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3189 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
3190 r
->resrec
.rdata
= mDNSNULL
;
3191 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
3194 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3195 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3196 // callbacks for old records are delivered before callbacks for newer records.
3197 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
3199 CacheRecord
**rp
= &cg
->members
;
3201 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3202 m
->lock_rrcache
= 1;
3206 CacheRecord
*const rr
= *rp
;
3207 mDNSs32 event
= RRExpireTime(rr
);
3208 if (m
->timenow
- event
>= 0) // If expired, delete it
3210 *rp
= rr
->next
; // Cut it from the list
3211 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3212 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
3213 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
3215 DNSQuestion
*q
= rr
->CRActiveQuestion
;
3216 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3217 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3218 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3219 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3220 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3221 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3222 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
3223 if (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
&& ActiveQuestion(q
))
3225 q
->ThisQInterval
= InitialQuestionInterval
;
3226 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3227 SetNextQueryTime(m
, q
);
3229 CacheRecordRmv(m
, rr
);
3230 m
->rrcache_active
--;
3232 ReleaseCacheRecord(m
, rr
);
3234 else // else, not expired; see if we need to query
3236 // If waiting to delay delivery, do nothing until then
3237 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
3238 event
= rr
->DelayDelivery
;
3241 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
3242 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3244 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
3245 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
3246 else // else trigger our question to go out now
3248 // Set NextScheduledQuery to timenow so that SendQueries() will run.
3249 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
3250 m
->NextScheduledQuery
= m
->timenow
;
3251 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3252 // which will correctly update m->NextCacheCheck for us.
3253 event
= m
->timenow
+ 0x3FFFFFFF;
3257 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3258 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
3259 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3260 m
->rrcache_nextcheck
[slot
] = event
;
3264 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
3265 cg
->rrcache_tail
= rp
;
3266 m
->lock_rrcache
= 0;
3269 // Caller should hold the lock
3270 mDNSlocal
void AnswerSuppressUnusableQuestion(mDNS
*const m
, DNSQuestion
*q
)
3272 LogInfo("AnswerSuppressUnusableQuestion: Generating negative response for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3273 if (!m
->CurrentQuestion
) LogMsg("AnswerSuppressUnusableQuestion: ERROR!! CurrentQuestion not set");
3275 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, mDNSNULL
);
3276 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
3277 if (m
->CurrentQuestion
== q
) q
->ThisQInterval
= 0; // Deactivate this question
3278 // Don't touch the question after this
3279 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
3282 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
3284 mDNSBool ShouldQueryImmediately
= mDNStrue
;
3285 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
3286 const mDNSu32 slot
= HashSlot(&q
->qname
);
3287 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
3289 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3291 if (cg
) CheckCacheExpiration(m
, slot
, cg
);
3292 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
3293 m
->NewQuestions
= q
->next
;
3294 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3295 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3297 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3298 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
3299 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3300 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3301 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3302 // advanced it), that means the question was deleted, so we no longer need to worry about answering
3303 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3304 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
3306 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
3307 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3308 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3309 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3311 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3312 // This should be safe, because calling the client's question callback may cause the
3313 // question list to be modified, but should not ever cause the rrcache list to be modified.
3314 // If the client's question callback deletes the question, then m->CurrentQuestion will
3315 // be advanced, and we'll exit out of the loop
3316 m
->lock_rrcache
= 1;
3317 if (m
->CurrentQuestion
)
3318 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3319 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3320 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
3322 if (q
->NoAnswer
== NoAnswer_Fail
)
3324 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3325 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
3326 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
3327 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
3328 q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
3329 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
3331 if (m
->CurrentQuestion
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit
; }
3333 // If 'mDNSInterface_Any' question, see if we want to tell it about LocalOnly records
3334 if (q
->InterfaceID
== mDNSInterface_Any
)
3336 if (m
->CurrentRecord
)
3337 LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3338 m
->CurrentRecord
= m
->ResourceRecords
;
3339 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
3341 AuthRecord
*rr
= m
->CurrentRecord
;
3342 m
->CurrentRecord
= rr
->next
;
3343 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
3344 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3346 AnswerLocalQuestionWithLocalAuthRecord(m
, q
, rr
, mDNStrue
);
3347 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3350 m
->CurrentRecord
= mDNSNULL
;
3352 if (m
->CurrentQuestion
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit
; }
3354 // If we are not supposed to answer this question, generate a negative response.
3355 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
3356 if (QuerySuppressed(q
)) { q
->SuppressQuery
= mDNSfalse
; AnswerSuppressUnusableQuestion(m
, q
); q
->SuppressQuery
= mDNStrue
; }
3360 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
3361 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
3363 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
3364 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3365 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
3367 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
3368 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, CRDisplayString(m
, rr
), m
->timenow
, rr
->TimeRcvd
);
3369 continue; // Go to next one in loop
3372 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
3373 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
3374 if ((rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
3375 ShouldQueryImmediately
= mDNSfalse
;
3376 q
->CurrentAnswers
++;
3377 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
3378 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
3379 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
3380 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3382 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
3383 ShouldQueryImmediately
= mDNSfalse
;
3385 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
3386 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
3387 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
3389 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
3391 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3392 q
->ThisQInterval
= InitialQuestionInterval
;
3393 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3394 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
3396 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
3397 if (!m
->RandomQueryDelay
)
3398 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
3399 q
->LastQTime
+= m
->RandomQueryDelay
;
3403 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
3404 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
3405 // answers for this question until *after* its scheduled transmission time, in which case
3406 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
3407 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
3408 SetNextQueryTime(m
,q
);
3411 m
->CurrentQuestion
= mDNSNULL
;
3412 m
->lock_rrcache
= 0;
3415 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
3416 // appropriate answers, stopping if it reaches a NewLocalRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
3417 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
3419 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
3420 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
3422 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3424 if (m
->CurrentQuestion
)
3425 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3426 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3427 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
3429 if (m
->CurrentRecord
)
3430 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3431 m
->CurrentRecord
= m
->ResourceRecords
;
3433 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
3435 AuthRecord
*rr
= m
->CurrentRecord
;
3436 m
->CurrentRecord
= rr
->next
;
3437 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3439 AnswerLocalQuestionWithLocalAuthRecord(m
, q
, rr
, mDNStrue
);
3440 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3444 m
->CurrentQuestion
= mDNSNULL
;
3445 m
->CurrentRecord
= mDNSNULL
;
3448 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
3450 CacheEntity
*e
= mDNSNULL
;
3452 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
3453 m
->lock_rrcache
= 1;
3455 // If we have no free records, ask the client layer to give us some more memory
3456 if (!m
->rrcache_free
&& m
->MainCallback
)
3458 if (m
->rrcache_totalused
!= m
->rrcache_size
)
3459 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
3460 m
->rrcache_totalused
, m
->rrcache_size
);
3462 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
3463 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
3464 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
3465 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
3466 // and recycle them, instead of allocating more memory.
3467 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
3468 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
3469 m
->rrcache_size
, m
->rrcache_active
);
3472 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
3473 m
->MainCallback(m
, mStatus_GrowCache
);
3474 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3478 // If we still have no free records, recycle all the records we can.
3479 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
3480 if (!m
->rrcache_free
)
3482 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
3484 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3486 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
3489 CacheRecord
**rp
= &(*cp
)->members
;
3492 // Records that answer still-active questions are not candidates for recycling
3493 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
3494 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
3498 CacheRecord
*rr
= *rp
;
3499 *rp
= (*rp
)->next
; // Cut record from list
3500 ReleaseCacheRecord(m
, rr
);
3503 if ((*cp
)->rrcache_tail
!= rp
)
3504 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
3505 (*cp
)->rrcache_tail
= rp
;
3506 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
3507 else ReleaseCacheGroup(m
, cp
);
3510 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
3511 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
3514 if (m
->rrcache_free
) // If there are records in the free list, take one
3516 e
= m
->rrcache_free
;
3517 m
->rrcache_free
= e
->next
;
3518 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
3520 LogInfo("RR Cache now using %ld objects", m
->rrcache_totalused
);
3521 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
3522 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
3523 else m
->rrcache_report
+= 1000;
3525 mDNSPlatformMemZero(e
, sizeof(*e
));
3528 m
->lock_rrcache
= 0;
3533 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
3535 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
3538 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
3539 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
3541 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
3542 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
3543 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
3549 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
3551 mDNSu16 namelen
= DomainNameLength(rr
->name
);
3552 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
3553 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
3554 cg
->next
= m
->rrcache_hash
[slot
];
3555 cg
->namehash
= rr
->namehash
;
3556 cg
->members
= mDNSNULL
;
3557 cg
->rrcache_tail
= &cg
->members
;
3558 cg
->name
= (domainname
*)cg
->namestorage
;
3559 //LogMsg("GetCacheGroup: %-10s %d-byte cache name %##s",
3560 // (namelen > InlineCacheGroupNameSize) ? "Allocating" : "Inline", namelen, rr->name->c);
3561 if (namelen
> InlineCacheGroupNameSize
) cg
->name
= mDNSPlatformMemAllocate(namelen
);
3564 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
3565 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
3568 AssignDomainName(cg
->name
, rr
->name
);
3570 if (CacheGroupForRecord(m
, slot
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
3571 m
->rrcache_hash
[slot
] = cg
;
3572 if (CacheGroupForRecord(m
, slot
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
3577 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
3579 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
3580 LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
3581 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
3582 // a positive answer using an expired record (e.g. from an interface that has gone away).
3583 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
3584 // summary deletion without giving the proper callback to any questions that are monitoring it.
3585 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
3586 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
3587 rr
->UnansweredQueries
= MaxUnansweredQueries
;
3588 rr
->resrec
.rroriginalttl
= 0;
3589 SetNextCacheCheckTimeForRecord(m
, rr
);
3592 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
3595 mDNSPlatformLock(m
);
3598 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
3599 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
3602 if (m
->timenow
) time
= m
->timenow
;
3603 else time
= mDNS_TimeNow_NoLock(m
);
3604 mDNSPlatformUnlock(m
);
3608 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
3609 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
3610 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
3611 #define SetSPSProxyListChanged(X) do { \
3612 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
3613 m->SPSProxyListChanged = (X); } while(0)
3615 // Called from mDNS_Execute() to expire stale proxy records
3616 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
3618 m
->CurrentRecord
= list
;
3619 while (m
->CurrentRecord
)
3621 AuthRecord
*rr
= m
->CurrentRecord
;
3622 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
3624 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
3625 // so we need to cease proxying for *all* records we may have, expired or not.
3626 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
3628 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
3629 m
->NextScheduledSPS
= rr
->TimeExpire
;
3631 else // else proxy record expired, so remove it
3633 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
3634 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
3635 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
3636 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
3637 // Don't touch rr after this -- memory may have been free'd
3640 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
3641 // new records could have been added to the end of the list as a result of that call.
3642 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
3643 m
->CurrentRecord
= rr
->next
;
3647 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
3649 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
3651 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
3654 AuthRecord
*head
, *tail
;
3656 verbosedebugf("mDNS_Execute");
3658 if (m
->CurrentQuestion
)
3659 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
3660 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3662 if (m
->CurrentRecord
)
3663 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
3665 // 1. If we're past the probe suppression time, we can clear it
3666 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
3668 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
3669 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
3671 // 3. Purge our cache of stale old records
3672 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
3674 mDNSu32 slot
, numchecked
= 0;
3675 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
3676 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3678 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
3680 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
3681 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ 0x3FFFFFFF;
3684 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
3686 CheckCacheExpiration(m
, slot
, *cp
);
3687 if ((*cp
)->members
) cp
=&(*cp
)->next
;
3688 else ReleaseCacheGroup(m
, cp
);
3691 // Even if we didn't need to actually check this slot yet, still need to
3692 // factor its nextcheck time into our overall NextCacheCheck value
3693 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
3694 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
3696 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
3699 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
3701 m
->NextScheduledSPS
= m
->timenow
+ 0x3FFFFFFF;
3702 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
3703 CheckProxyRecords(m
, m
->ResourceRecords
);
3706 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
3708 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
3709 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0) m
->AnnounceOwner
= 0;
3711 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
3714 if (m
->SleepState
== SleepState_Transferring
)
3716 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
3717 BeginSleepProcessing(m
);
3721 // 4. See if we can answer any of our new local questions from the cache
3722 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
3724 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
3725 AnswerNewQuestion(m
);
3727 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
3729 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
3730 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
3731 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
3733 m
->LocalRemoveEvents
= mDNSfalse
;
3734 m
->CurrentRecord
= m
->ResourceRecords
;
3735 while (m
->CurrentRecord
)
3737 AuthRecord
*rr
= m
->CurrentRecord
;
3738 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3740 debugf("mDNS_Execute: Generating local RMV events for %s", ARDisplayString(m
, rr
));
3741 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
3742 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
);
3743 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
3745 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
3746 rr
->AnsweredLocalQ
= mDNSfalse
;
3749 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
3750 m
->CurrentRecord
= rr
->next
;
3753 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
3755 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
3756 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
3758 head
= tail
= mDNSNULL
;
3759 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
3761 AuthRecord
*rr
= m
->NewLocalRecords
;
3762 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
3763 if (LocalRecordReady(rr
))
3765 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
3766 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNStrue
);
3770 // If we have just one record that is not ready, we don't have to unlink and
3771 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
3772 // terminate and set the NewLocalRecords to rr.
3773 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
3774 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
3775 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
3781 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
3782 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
3783 // if this is the first record we are skipping, move to the end of the list.
3784 // if we have already skipped records before, append it at the end.
3785 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
3786 if (*p
) *p
= rr
->next
; // Cut this record from the list
3787 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
3790 while (*p
) p
=&(*p
)->next
;
3799 rr
->next
= mDNSNULL
;
3802 m
->NewLocalRecords
= head
;
3803 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
3805 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
3807 // 5. Some questions may have picked a new DNS server and the cache may answer these questions now.
3808 AnswerQuestionsForDNSServerChanges(m
);
3810 // 6. See what packets we need to send
3811 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
3812 DiscardDeregistrations(m
);
3813 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
3815 // If the platform code is ready, and we're not suppressing packet generation right now
3816 // then send our responses, probes, and questions.
3817 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
3818 // We send queries next, because there might be final-stage probes that complete their probing here, causing
3819 // them to advance to announcing state, and we want those to be included in any announcements we send out.
3820 // Finally, we send responses, including the previously mentioned records that just completed probing.
3821 m
->SuppressSending
= 0;
3823 // 7. Send Query packets. This may cause some probing records to advance to announcing state
3824 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
3825 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
3828 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
3829 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
3830 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
3831 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3832 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
3833 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3835 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
3837 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
3838 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
3839 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
3842 // 8. Send Response packets, including probing records just advanced to announcing state
3843 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
3844 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
3846 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
3847 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
3851 // Clear RandomDelay values, ready to pick a new different value next time
3852 m
->RandomQueryDelay
= 0;
3853 m
->RandomReconfirmDelay
= 0;
3855 #ifndef UNICAST_DISABLED
3856 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
3857 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
3858 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
3862 // Note about multi-threaded systems:
3863 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
3864 // performing mDNS API operations that change our next scheduled event time.
3866 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
3867 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
3868 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
3869 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
3870 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
3871 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
3872 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
3873 // without blocking. This avoids the race condition between the signal from the other thread arriving
3874 // just *before* or just *after* the main thread enters the blocking primitive.
3876 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
3877 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
3878 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
3879 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
3880 // by the time it gets to the timer callback function).
3882 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
3883 return(m
->NextScheduledEvent
);
3886 mDNSlocal
void SuspendLLQs(mDNS
*m
)
3889 for (q
= m
->Questions
; q
; q
= q
->next
)
3890 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
3891 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
3894 // ActivateUnicastQuery() is called from three places:
3895 // 1. When a new question is created
3896 // 2. On wake from sleep
3897 // 3. When the DNS configuration changes
3898 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
3899 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
3900 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
3902 // For now this AutoTunnel stuff is specific to Mac OS X.
3903 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
3904 #if APPLE_OSX_mDNSResponder
3905 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
3906 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
3907 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
3908 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
3909 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
3910 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
3912 if (RRTypeIsAddressType(question
->qtype
) && PrivateQuery(question
) &&
3913 !SameDomainLabel(question
->qname
.c
, (const mDNSu8
*)"\x0c_autotunnel6")&& question
->QuestionCallback
!= AutoTunnelCallback
)
3915 question
->NoAnswer
= NoAnswer_Suspended
;
3916 AddNewClientTunnel(m
, question
);
3919 #endif // APPLE_OSX_mDNSResponder
3921 if (!question
->DuplicateOf
)
3923 debugf("ActivateUnicastQuery: %##s %s%s%s",
3924 question
->qname
.c
, DNSTypeName(question
->qtype
), PrivateQuery(question
) ? " (Private)" : "", ScheduleImmediately
? " ScheduleImmediately" : "");
3925 question
->CNAMEReferrals
= 0;
3926 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
3927 if (question
->LongLived
)
3929 question
->state
= LLQ_InitialRequest
;
3930 question
->id
= zeroOpaque64
;
3931 question
->servPort
= zeroIPPort
;
3932 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
3934 if (ScheduleImmediately
)
3936 question
->ThisQInterval
= InitialQuestionInterval
;
3937 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
3938 SetNextQueryTime(m
, question
);
3943 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
3947 #ifndef UNICAST_DISABLED
3948 // Retrigger all our uDNS questions
3949 if (m
->CurrentQuestion
)
3950 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
3951 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3952 m
->CurrentQuestion
= m
->Questions
;
3953 while (m
->CurrentQuestion
)
3955 q
= m
->CurrentQuestion
;
3956 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3957 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
)) ActivateUnicastQuery(m
, q
, mDNStrue
);
3961 // Retrigger all our mDNS questions
3962 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
3963 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
3965 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
3966 q
->RequestUnicast
= 2; // Set to 2 because is decremented once *before* we check it
3967 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3968 q
->RecentAnswerPkts
= 0;
3969 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
3970 m
->NextScheduledQuery
= m
->timenow
;
3974 // ***************************************************************************
3975 #if COMPILER_LIKES_PRAGMA_MARK
3977 #pragma mark - Power Management (Sleep/Wake)
3980 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
3982 #ifndef IDLESLEEPCONTROL_DISABLED
3983 mDNSBool allowSleep
= mDNStrue
;
3985 if (m
->SystemSleepOnlyIfWakeOnLAN
)
3987 // Don't sleep if we are a proxy for any services
3988 if (m
->ProxyRecords
)
3990 allowSleep
= mDNSfalse
;
3991 LogInfo("Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
3994 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
3996 // Scan the list of active interfaces
3997 NetworkInterfaceInfo
*intf
;
3998 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4000 if (intf
->McastTxRx
)
4002 // Disallow sleep if this interface doesn't support NetWake
4005 allowSleep
= mDNSfalse
;
4006 LogInfo("Sleep disabled because %s does not support NetWake", intf
->ifname
);
4010 // Disallow sleep if there is no sleep proxy server
4011 if (FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
) == mDNSNULL
)
4013 allowSleep
= mDNSfalse
;
4014 LogInfo("Sleep disabled because %s has no sleep proxy", intf
->ifname
);
4020 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
4023 // Call the platform code to enable/disable sleep
4024 mDNSPlatformSetAllowSleep(m
, allowSleep
);
4027 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*intf
, const mDNSOpaque16 id
)
4029 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
4030 const int sps
= intf
->NextSPSAttempt
/ 3;
4033 if (!intf
->SPSAddr
[sps
].type
)
4035 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
4036 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
4037 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
4038 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
4042 // Mark our mDNS records (not unicast records) for transfer to SPS
4043 if (mDNSOpaque16IsZero(id
))
4044 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4045 if (rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
4046 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
4047 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
4051 mDNSu8
*p
= m
->omsg
.data
;
4052 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
4053 // For now we follow that same logic for SPS registrations too.
4054 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
4055 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
4056 InitializeDNSMessage(&m
->omsg
.h
, mDNSOpaque16IsZero(id
) ? mDNS_NewMessageID(m
) : id
, UpdateReqFlags
);
4058 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4059 if (rr
->SendRNow
|| (!mDNSOpaque16IsZero(id
) && !AuthRecord_uDNS(rr
) && mDNSSameOpaque16(rr
->updateid
, id
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0))
4062 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
4063 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
4064 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
4065 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
4066 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
4068 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
4071 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, rr
));
4072 rr
->SendRNow
= mDNSNULL
;
4073 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
4074 rr
->LastAPTime
= m
->timenow
;
4075 rr
->updateid
= m
->omsg
.h
.id
;
4076 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
4077 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
4082 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
4086 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
4087 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
4088 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
4089 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
4090 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
4091 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
4092 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
4093 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]);
4094 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
4095 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
4097 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
4101 // Once we've attempted to register, we need to include our OWNER option in our packets when we re-awaken
4102 m
->SentSleepProxyRegistration
= mDNStrue
;
4104 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
4105 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
4106 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
4107 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSNULL
);
4108 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
4109 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv6
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
4111 LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
4112 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_A
;
4113 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
4120 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
4123 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
4126 // RetrySPSRegistrations is called from SendResponses, with the lock held
4127 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
4130 NetworkInterfaceInfo
*intf
;
4132 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
4133 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4134 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
4135 intf
->NextSPSAttemptTime
++;
4137 // Retry any record registrations that are due
4138 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4139 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
4140 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4141 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
)
4143 LogSPS("RetrySPSRegistrations: %s", ARDisplayString(m
, rr
));
4144 SendSPSRegistration(m
, intf
, rr
->updateid
);
4147 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
4148 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4149 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
4150 intf
->NextSPSAttempt
++;
4153 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
4155 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
4156 int sps
= (int)(question
- intf
->NetWakeResolve
);
4158 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
4160 if (!AddRecord
) return; // Don't care about REMOVE events
4161 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
4163 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
4165 if (answer
->rrtype
== kDNSType_SRV
)
4167 // 1. Got the SRV record; now look up the target host's IPv6 link-local address
4168 mDNS_StopQuery(m
, question
);
4169 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
4170 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
4171 question
->qtype
= kDNSType_AAAA
;
4172 mDNS_StartQuery(m
, question
);
4174 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
4176 // 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
4177 mDNS_StopQuery(m
, question
);
4178 question
->ThisQInterval
= -1;
4179 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
4180 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
4182 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
4185 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== 0)
4187 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
4188 mDNS_StopQuery(m
, question
);
4189 LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps
, question
->qname
.c
);
4190 question
->qtype
= kDNSType_A
;
4191 mDNS_StartQuery(m
, question
);
4193 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
4195 // 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
4196 mDNS_StopQuery(m
, question
);
4197 question
->ThisQInterval
= -1;
4198 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
4199 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
4201 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
4206 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
4209 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4210 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
))
4215 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
)
4218 m
->SleepState
= SleepState_Sleeping
;
4220 #ifndef UNICAST_DISABLED
4221 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
4222 #endif /* UNICAST_DISABLED */
4224 // Mark all the records we need to deregister and send them
4225 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4226 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
4227 rr
->ImmedAnswer
= mDNSInterfaceMark
;
4231 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
4232 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
4234 mDNSBool SendGoodbyes
= mDNStrue
;
4235 const CacheRecord
*sps
[3] = { mDNSNULL
};
4237 m
->NextScheduledSPRetry
= m
->timenow
;
4239 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
4240 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
4241 else // If we have at least one advertised service
4243 NetworkInterfaceInfo
*intf
;
4244 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4246 if (!intf
->NetWake
) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
4247 #if APPLE_OSX_mDNSResponder
4248 else if (ActivateLocalProxy(m
, intf
->ifname
) == mStatus_NoError
)
4250 SendGoodbyes
= mDNSfalse
;
4251 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
4252 // This will leave m->SleepState set to SleepState_Transferring,
4253 // which is okay because with no outstanding resolves, or updates in flight,
4254 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
4256 #endif // APPLE_OSX_mDNSResponder
4259 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
4260 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
4261 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
4265 SendGoodbyes
= mDNSfalse
;
4266 intf
->NextSPSAttempt
= 0;
4267 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
4268 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
4272 if (intf
->SPSAddr
[i
].type
)
4273 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
); *(long*)0 = 0; }
4274 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
4275 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
); *(long*)0 = 0; }
4277 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
4278 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
4279 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
4282 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
4283 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
4284 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
4285 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
4293 if (SendGoodbyes
) // If we didn't find even one Sleep Proxy
4295 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
4296 SendSleepGoodbyes(m
);
4300 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4301 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4302 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4303 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
4307 LogSPS("%s (old state %d) at %ld", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
4309 if (sleep
&& !m
->SleepState
) // Going to sleep
4312 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
4315 mDNSu8 oldstate
= m
->SPSState
;
4316 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
4318 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
4319 mDNS_ReclaimLockAfterCallback();
4322 m
->SleepState
= SleepState_Transferring
;
4323 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
4325 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
4326 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
4327 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
4332 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
4333 BeginSleepProcessing(m
);
4336 #ifndef UNICAST_DISABLED
4340 // RemoveAutoTunnel6Record needs to be called outside the lock, as it grabs the lock also.
4341 #if APPLE_OSX_mDNSResponder
4342 RemoveAutoTunnel6Record(m
);
4344 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m
->SleepState
,
4345 m
->SleepState
== SleepState_Transferring
? "Transferring" :
4346 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
4348 else if (!sleep
) // Waking up
4353 NetworkInterfaceInfo
*intf
;
4356 // Reset SleepLimit back to 0 now that we're awake again.
4359 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
4360 if (m
->SleepState
!= SleepState_Awake
)
4362 m
->SleepState
= SleepState_Awake
;
4364 if (m
->SentSleepProxyRegistration
) // Include OWNER option in packets for 60 seconds after waking
4366 m
->SentSleepProxyRegistration
= mDNSfalse
;
4367 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
4369 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
4370 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
4371 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
4372 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
4373 m
->DelaySleep
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 16);
4376 if (m
->SPSState
== 3)
4379 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
);
4382 // In case we gave up waiting and went to sleep before we got an ack from the Sleep Proxy,
4383 // on wake we go through our record list and clear updateid back to zero
4384 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) rr
->updateid
= zeroID
;
4386 // ... and the same for NextSPSAttempt
4387 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
4389 // Restart unicast and multicast queries
4390 mDNSCoreRestartQueries(m
);
4392 // and reactivtate service registrations
4393 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
4394 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
4396 // 2. Re-validate our cache records
4397 FORALL_CACHERECORDS(slot
, cg
, cr
)
4398 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
4400 // 3. Retrigger probing and announcing for all our authoritative records
4401 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4402 if (AuthRecord_uDNS(rr
))
4404 ActivateUnicastRegistration(m
, rr
);
4408 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
4409 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
4410 rr
->AnnounceCount
= InitialAnnounceCount
;
4411 rr
->SendNSECNow
= mDNSNULL
;
4412 InitializeLastAPTime(m
, rr
);
4415 // 4. Refresh NAT mappings
4416 // We don't want to have to assume that all hardware can necessarily keep accurate
4417 // track of passage of time while asleep, so on wake we refresh our NAT mappings
4418 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
4419 // When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
4420 // mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
4421 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
4422 m
->retryGetAddr
= m
->timenow
+ mDNSPlatformOneSecond
* 5;
4423 LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m
->retryGetAddr
- m
->timenow
, m
->timenow
);
4424 RecreateNATMappings(m
);
4429 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
4433 NetworkInterfaceInfo
*intf
;
4437 if (m
->DelaySleep
) goto notready
;
4439 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
4440 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
4442 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
4444 // See if we might need to retransmit any lost Sleep Proxy Registrations
4445 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4446 if (intf
->NextSPSAttempt
>= 0)
4448 if (now
- intf
->NextSPSAttemptTime
>= 0)
4450 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
4451 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
4452 SendSPSRegistration(m
, intf
, zeroID
);
4453 // Don't need to "goto notready" here, because if we do still have record registrations
4454 // that have not been acknowledged yet, we'll catch that in the record list scan below.
4457 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
4458 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
4461 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
4462 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4464 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
4465 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
4467 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
4468 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
4473 // Scan list of registered records
4474 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4475 if (!AuthRecord_uDNS(rr
))
4476 if (!mDNSOpaque16IsZero(rr
->updateid
))
4477 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS Update ID %d %s", mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto spsnotready
; }
4479 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
4480 for (q
= m
->Questions
; q
; q
= q
->next
)
4481 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
4483 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4487 // Scan list of registered records
4488 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4489 if (AuthRecord_uDNS(rr
))
4491 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
4492 { LogSPS("mDNSCoreReadyForSleep: waiting for Record Update ID %d %s", mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto notready
; }
4493 #if APPLE_OSX_mDNSResponder
4494 if (!RecordReadyForSleep(m
, rr
)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m
, rr
)); goto notready
; }
4503 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
4504 // and allow up to ten seconds more to complete wide-area deregistration instead
4505 if (now
- m
->SleepLimit
>= 0)
4507 LogMsg("Failed to register with SPS, now sending goodbyes");
4509 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4510 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
4512 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
4513 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
4514 mDNS_DeactivateNetWake_internal(m
, intf
);
4517 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4518 if (!AuthRecord_uDNS(rr
))
4519 if (!mDNSOpaque16IsZero(rr
->updateid
))
4521 LogSPS("ReadyForSleep clearing updateid for %s", ARDisplayString(m
, rr
));
4522 rr
->updateid
= zeroID
;
4525 // We'd really like to allow up to ten seconds more here,
4526 // but if we don't respond to the sleep notification within 30 seconds
4527 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
4528 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
4529 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
4530 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
4531 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
4533 SendSleepGoodbyes(m
);
4541 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
)
4545 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
4546 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
4547 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
4548 // and if that happens we don't want to just give up and go back to sleep and never try again.
4549 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
4551 NATTraversalInfo
*nat
;
4552 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
4553 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
4555 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
4556 if (e
- t
> 0) e
= t
;
4557 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
4558 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
4559 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
4560 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
4561 nat
->retryInterval
/ mDNSPlatformOneSecond
,
4562 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
4563 (t
- now
) / mDNSPlatformOneSecond
);
4566 // This loop checks both the time we need to renew wide-area registrations,
4567 // and the time we need to renew Sleep Proxy registrations
4568 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
4569 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
4571 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
4572 if (e
- t
> 0) e
= t
;
4573 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
4574 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4575 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4576 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
4577 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
4583 // ***************************************************************************
4584 #if COMPILER_LIKES_PRAGMA_MARK
4586 #pragma mark - Packet Reception Functions
4589 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4591 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
4592 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
4594 mDNSu8
*responseptr
= response
->data
;
4595 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
4596 const mDNSu8
*ptr
= query
->data
;
4598 mDNSu32 maxttl
= 0x70000000;
4601 // Initialize the response fields so we can answer the questions
4602 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
4605 // *** 1. Write out the list of questions we are actually going to answer with this packet
4609 maxttl
= kStaticCacheTTL
;
4610 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4613 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
4614 if (!ptr
) return(mDNSNULL
);
4616 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
4618 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
4619 { // then put the question in the question section
4620 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
4621 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
4622 break; // break out of the ResponseRecords loop, and go on to the next question
4627 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
4631 // *** 2. Write Answers
4633 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4634 if (rr
->NR_AnswerTo
)
4636 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
4637 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
4638 if (p
) responseptr
= p
;
4639 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
4643 // *** 3. Write Additionals
4645 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4646 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
4648 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
4649 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
4650 if (p
) responseptr
= p
;
4651 else debugf("GenerateUnicastResponse: No more space for additionals");
4654 return(responseptr
);
4657 // AuthRecord *our is our Resource Record
4658 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4659 // Returns 0 if there is no conflict
4660 // Returns +1 if there was a conflict and we won
4661 // Returns -1 if there was a conflict and we lost and have to rename
4662 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
4664 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
4665 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
4666 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4667 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4669 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
4670 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
4671 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
4672 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
4674 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
4675 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
4676 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
4677 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
4679 LogMsg("CompareRData ERROR: Invalid state");
4683 // See if we have an authoritative record that's identical to this packet record,
4684 // whose canonical DependentOn record is the specified master record.
4685 // The DependentOn pointer is typically used for the TXT record of service registrations
4686 // It indicates that there is no inherent conflict detection for the TXT record
4687 // -- it depends on the SRV record to resolve name conflicts
4688 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4689 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4690 // If the record has no DependentOn, then just return that record's pointer
4691 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4692 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
4694 const AuthRecord
*r1
;
4695 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
4697 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4699 const AuthRecord
*r2
= r1
;
4700 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4701 if (r2
== master
) return(mDNStrue
);
4704 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
4706 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4708 const AuthRecord
*r2
= r1
;
4709 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4710 if (r2
== master
) return(mDNStrue
);
4716 // Find the canonical RRSet pointer for this RR received in a packet.
4717 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4718 // pointers (if any) to make sure we return the canonical member of this name/type/class
4719 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4720 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
4722 const AuthRecord
*rr
;
4723 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4725 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
4727 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
4734 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4735 // as one of our records (our) but different rdata.
4736 // 1. If our record is not a type that's supposed to be unique, we don't care.
4737 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4738 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4739 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4740 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4741 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4742 // are members of the same RRSet, then this is not a conflict.
4743 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
4745 // If not supposed to be unique, not a conflict
4746 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
4748 // If a dependent record, not a conflict
4749 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
4752 // If the pktrr matches a member of ourset, not a conflict
4753 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
4754 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
4755 if (pktset
== ourset
) return(mDNSfalse
);
4757 // For records we're proxying, where we don't know the full
4758 // relationship between the records, having any matching record
4759 // in our AuthRecords list is sufficient evidence of non-conflict
4760 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
4763 // Okay, this is a conflict
4767 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4768 // the record list and/or question list.
4769 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4770 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4771 DNSQuestion
*q
, AuthRecord
*our
)
4774 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
4775 mDNSBool FoundUpdate
= mDNSfalse
;
4777 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
4779 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
4781 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
4783 FoundUpdate
= mDNStrue
;
4784 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
4786 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
4787 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
4788 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
4791 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
4792 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
4793 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
4795 // 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.
4796 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
4797 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
4800 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
4801 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
4802 our
->AnnounceCount
= InitialAnnounceCount
;
4803 InitializeLastAPTime(m
, our
);
4810 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
4811 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
4815 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4818 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
4820 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4823 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
4825 mDNSu32 slot
= HashSlot(pktrr
->name
);
4826 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, pktrr
);
4829 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4831 match
= !pktrr
->InterfaceID
? pktrr
->rDNSServer
== rr
->resrec
.rDNSServer
: pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
;
4832 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
4837 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
4838 // to check our lists and discard any stale duplicates of this record we already have
4839 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
4841 if (m
->CurrentRecord
)
4842 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4843 m
->CurrentRecord
= thelist
;
4844 while (m
->CurrentRecord
)
4846 AuthRecord
*const rr
= m
->CurrentRecord
;
4847 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
4848 if (IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
4850 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
4851 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
4852 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
4853 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
4854 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
4855 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
4857 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4858 // new records could have been added to the end of the list as a result of that call.
4859 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
4860 m
->CurrentRecord
= rr
->next
;
4864 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
4865 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
4867 if (m
->CurrentRecord
)
4868 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4869 m
->CurrentRecord
= thelist
;
4870 while (m
->CurrentRecord
)
4872 AuthRecord
*const rr
= m
->CurrentRecord
;
4873 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
4874 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
4876 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
4878 // We don't do this here because we know that the host is waking up at this point, so we don't send
4879 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
4880 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
4881 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
4882 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
4883 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
4884 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
4887 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
4888 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
4889 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
4890 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
4891 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
4892 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
4893 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
4894 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
4896 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4897 // new records could have been added to the end of the list as a result of that call.
4898 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
4899 m
->CurrentRecord
= rr
->next
;
4903 // ProcessQuery examines a received query to see if we have any answers to give
4904 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4905 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
4906 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
4908 mDNSBool FromLocalSubnet
= srcaddr
&& mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
4909 AuthRecord
*ResponseRecords
= mDNSNULL
;
4910 AuthRecord
**nrp
= &ResponseRecords
;
4911 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
4912 CacheRecord
**eap
= &ExpectedAnswers
;
4913 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
4914 DNSQuestion
**dqp
= &DupQuestions
;
4915 mDNSs32 delayresponse
= 0;
4916 mDNSBool SendLegacyResponse
= mDNSfalse
;
4918 mDNSu8
*responseptr
= mDNSNULL
;
4923 // *** 1. Look in Additional Section for an OPT record
4925 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
4928 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
4929 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
4931 const rdataOPT
*opt
;
4932 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
4933 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
4934 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
4935 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
4936 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
4938 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
4939 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
4942 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4946 // *** 2. Parse Question Section and mark potential answers
4949 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4951 mDNSBool QuestionNeedsMulticastResponse
;
4952 int NumAnswersForThisQuestion
= 0;
4953 AuthRecord
*NSECAnswer
= mDNSNULL
;
4954 DNSQuestion pktq
, *q
;
4955 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
4956 if (!ptr
) goto exit
;
4958 // The only queries that *need* a multicast response are:
4959 // * Queries sent via multicast
4961 // * that don't have the kDNSQClass_UnicastResponse bit set
4962 // These queries need multicast responses because other clients will:
4963 // * suppress their own identical questions when they see these questions, and
4964 // * expire their cache records if they don't see the expected responses
4965 // For other queries, we may still choose to send the occasional multicast response anyway,
4966 // to keep our neighbours caches warm, and for ongoing conflict detection.
4967 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
4968 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
4969 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
4971 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
4972 // can result in user callbacks which may change the record list and/or question list.
4973 // Also note: we just mark potential answer records here, without trying to build the
4974 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
4975 // from that list while we're in the middle of trying to build it.
4976 if (m
->CurrentRecord
)
4977 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4978 m
->CurrentRecord
= m
->ResourceRecords
;
4979 while (m
->CurrentRecord
)
4981 rr
= m
->CurrentRecord
;
4982 m
->CurrentRecord
= rr
->next
;
4983 if (AnyTypeRecordAnswersQuestion(&rr
->resrec
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
4985 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
4987 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
4988 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
4989 else if (ResourceRecordIsValidAnswer(rr
))
4991 NumAnswersForThisQuestion
++;
4992 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
4993 // unicast answer back to the source, because timeliness in answering probes is important.
4996 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
4997 // NR_AnswerTo == (mDNSu8*)~1 means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
4998 // NR_AnswerTo == (mDNSu8*)~0 means "definitely answer via multicast" (can't downgrade to unicast later)
4999 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
5000 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
5001 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
5002 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
5004 // We only mark this question for sending if it is at least one second since the last time we multicast it
5005 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
5006 // This is to guard against the case where someone blasts us with queries as fast as they can.
5007 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
5008 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
5009 rr
->NR_AnswerTo
= (mDNSu8
*)~0;
5011 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: (mDNSu8
*)~1;
5014 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
5016 // If we don't have any answers for this question, but we do own another record with the same name,
5017 // then we'll want to mark it to generate an NSEC record on this interface
5018 if (!NSECAnswer
) NSECAnswer
= rr
;
5023 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
5025 NumAnswersForThisQuestion
++;
5026 NSECAnswer
->SendNSECNow
= InterfaceID
;
5027 m
->NextScheduledResponse
= m
->timenow
;
5030 // If we couldn't answer this question, someone else might be able to,
5031 // so use random delay on response to reduce collisions
5032 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
5034 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5035 if (QuestionNeedsMulticastResponse
)
5037 // We only do the following accelerated cache expiration and duplicate question suppression processing
5038 // for non-truncated multicast queries with multicast responses.
5039 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
5040 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
5041 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
5042 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5045 const mDNSu32 slot
= HashSlot(&pktq
.qname
);
5046 CacheGroup
*cg
= CacheGroupForName(m
, slot
, pktq
.qnamehash
, &pktq
.qname
);
5049 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5050 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5051 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5052 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5054 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
5055 if (SameNameRecordAnswersQuestion(&cr
->resrec
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
5056 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
5059 eap
= &cr
->NextInKAList
;
5060 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5061 if (cr
->MPUnansweredQ
== 0 || m
->timenow
- cr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
5063 // Although MPUnansweredQ is only really used for multi-packet query processing,
5064 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5065 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5066 cr
->MPUnansweredQ
++;
5067 cr
->MPLastUnansweredQT
= m
->timenow
;
5068 cr
->MPExpectingKA
= mDNStrue
;
5073 // Check if this question is the same as any of mine.
5074 // We only do this for non-truncated queries. Right now it would be too complicated to try
5075 // to keep track of duplicate suppression state between multiple packets, especially when we
5076 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5077 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5078 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5080 for (q
= m
->Questions
; q
; q
=q
->next
)
5081 if (!q
->Target
.type
&& ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
5082 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
5083 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
5084 if (q
->qtype
== pktq
.qtype
&&
5085 q
->qclass
== pktq
.qclass
&&
5086 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
5087 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
5092 // *** 3. Now we can safely build the list of marked answers
5094 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
5095 if (rr
->NR_AnswerTo
) // If we marked the record...
5096 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
5099 // *** 4. Add additional records
5101 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
5104 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
5106 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
5108 // Get the record...
5109 CacheRecord
*ourcacherr
;
5110 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
5111 if (!ptr
) goto exit
;
5112 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
5114 // See if this Known-Answer suppresses any of our currently planned answers
5115 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5116 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
5117 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5119 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5120 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
5122 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5123 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
5125 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5127 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
5129 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5131 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
5133 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
5135 rr
->ImmedAnswer
= mDNSNULL
;
5136 rr
->ImmedUnicast
= mDNSfalse
;
5137 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5138 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
5144 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
5146 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5147 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5148 // 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).
5149 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
5151 ourcacherr
->MPUnansweredKA
++;
5152 ourcacherr
->MPExpectingKA
= mDNSfalse
;
5156 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
5157 // any records that are suppressed by the Known Answer list in this packet.
5158 eap
= &ExpectedAnswers
;
5161 CacheRecord
*cr
= *eap
;
5162 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
5163 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
5164 else eap
= &cr
->NextInKAList
;
5167 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5170 dqp
= &DupQuestions
;
5173 DNSQuestion
*q
= *dqp
;
5174 if (ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
5175 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
5176 else dqp
= &q
->NextInDQList
;
5180 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
5184 // *** 6. Cancel any additionals that were added because of now-deleted records
5186 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5187 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
5188 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5191 // *** 7. Mark the send flags on the records we plan to send
5193 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5195 if (rr
->NR_AnswerTo
)
5197 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
5198 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
5200 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5201 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0)
5203 SendMulticastResponse
= mDNStrue
;
5204 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
5205 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
5206 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
5207 if (rr
->NR_AnswerTo
== (mDNSu8
*)~1) rr
->NR_AnswerTo
= (mDNSu8
*)~0;
5210 // If the client insists on a multicast response, then we'd better send one
5211 if (rr
->NR_AnswerTo
== (mDNSu8
*)~0) SendMulticastResponse
= mDNStrue
;
5212 else if (rr
->NR_AnswerTo
== (mDNSu8
*)~1) SendUnicastResponse
= mDNStrue
;
5213 else if (rr
->NR_AnswerTo
) SendLegacyResponse
= mDNStrue
;
5215 if (SendMulticastResponse
|| SendUnicastResponse
)
5217 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5218 rr
->ImmedAnswerMarkTime
= m
->timenow
;
5220 m
->NextScheduledResponse
= m
->timenow
;
5221 // If we're already planning to send this on another interface, just send it on all interfaces
5222 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
5223 rr
->ImmedAnswer
= mDNSInterfaceMark
;
5226 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
5227 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
5228 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5230 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
5231 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
5233 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5235 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
5236 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
5240 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
5241 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
5242 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
5243 // else, for a simple unique record reply, we can reply immediately; no need for delay
5244 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
5245 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
5247 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== (mDNSu8
*)~0)
5249 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5250 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5251 // then the earlier client is out of luck
5252 rr
->ImmedAdditional
= InterfaceID
;
5253 // No need to set m->NextScheduledResponse here
5254 // We'll send these additional records when we send them, or not, as the case may be
5259 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
5261 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
5263 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5264 mDNSs32 oldss
= m
->SuppressSending
;
5265 if (oldss
&& delayresponse
)
5266 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
5268 // Pick a random delay:
5269 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
5270 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
5271 // This is an integer value, with resolution determined by the platform clock rate.
5272 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
5273 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
5274 // The +49 before dividing is to ensure we round up, not down, to ensure that even
5275 // on platforms where the native clock rate is less than fifty ticks per second,
5276 // we still guarantee that the final calculated delay is at least one platform tick.
5277 // We want to make sure we don't ever allow the delay to be zero ticks,
5278 // because if that happens we'll fail the Bonjour Conformance Test.
5279 // Our final computed delay is 20-120ms for normal delayed replies,
5280 // or 400-500ms in the case of multi-packet known-answer lists.
5281 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
5282 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
5283 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5284 if (oldss
&& delayresponse
)
5285 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
5290 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
5292 if (SendLegacyResponse
)
5293 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
5296 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
5299 // *** 10. Finally, clear our link chains ready for use next time
5301 while (ResponseRecords
)
5303 rr
= ResponseRecords
;
5304 ResponseRecords
= rr
->NextResponse
;
5305 rr
->NextResponse
= mDNSNULL
;
5306 rr
->NR_AnswerTo
= mDNSNULL
;
5307 rr
->NR_AdditionalTo
= mDNSNULL
;
5310 while (ExpectedAnswers
)
5312 CacheRecord
*cr
= ExpectedAnswers
;
5313 ExpectedAnswers
= cr
->NextInKAList
;
5314 cr
->NextInKAList
= mDNSNULL
;
5316 // For non-truncated queries, we can definitively say that we should expect
5317 // to be seeing a response for any records still left in the ExpectedAnswers list
5318 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5319 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
)
5321 cr
->UnansweredQueries
++;
5322 cr
->LastUnansweredTime
= m
->timenow
;
5323 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5324 if (cr
->UnansweredQueries
> 1)
5325 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5326 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
5328 SetNextCacheCheckTimeForRecord(m
, cr
);
5331 // If we've seen multiple unanswered queries for this record,
5332 // then mark it to expire in five seconds if we don't get a response by then.
5333 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
5335 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5336 // Only show debugging message if this record was not about to expire anyway
5337 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5338 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5339 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
5341 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
5343 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5344 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5345 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5346 // possible packet loss of up to 20% of the additional KA packets.)
5347 else if (cr
->MPUnansweredQ
* 4 > cr
->MPUnansweredKA
* 5 + 8)
5349 // We want to do this conservatively.
5350 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5351 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5352 // By setting the record to expire in four minutes, we achieve two things:
5353 // (a) the 90-95% final expiration queries will be less bunched together
5354 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5355 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(cr
) - m
->timenow
) / 4;
5356 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
5357 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
5359 // Only show debugging message if this record was not about to expire anyway
5360 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5361 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5362 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
5364 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
5365 cr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
5366 cr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
5367 cr
->MPUnansweredKA
= 0;
5368 cr
->MPExpectingKA
= mDNSfalse
;
5370 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
5371 remain
= kDefaultReconfirmTimeForNoAnswer
;
5372 mDNS_Reconfirm_internal(m
, cr
, remain
);
5377 while (DupQuestions
)
5379 DNSQuestion
*q
= DupQuestions
;
5380 DupQuestions
= q
->NextInDQList
;
5381 q
->NextInDQList
= mDNSNULL
;
5382 i
= RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
5383 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
5384 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6", i
);
5387 return(responseptr
);
5390 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
5391 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5392 const mDNSInterfaceID InterfaceID
)
5394 mDNSu8
*responseend
= mDNSNULL
;
5395 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
5396 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
5398 if (!InterfaceID
&& dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
))
5400 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
5401 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
5402 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
5403 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5404 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5405 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5406 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
5410 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
5411 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
5412 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
5413 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5414 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5415 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5416 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
5418 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
5419 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
5421 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
5423 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5424 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
5425 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
5426 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
5427 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
5428 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
);
5433 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
5437 (void)srcaddr
; // Unused
5438 for (s
= m
->DNSServers
; s
; s
= s
->next
)
5439 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
5444 struct UDPSocket_struct
5446 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
5449 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
, const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
)
5452 for (q
= m
->Questions
; q
; q
=q
->next
)
5454 if (!tcp
&& !q
->LocalSocket
) continue;
5455 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
5456 mDNSSameOpaque16(q
->TargetQID
, id
) &&
5457 q
->qtype
== question
->qtype
&&
5458 q
->qclass
== question
->qclass
&&
5459 q
->qnamehash
== question
->qnamehash
&&
5460 SameDomainName(&q
->qname
, &question
->qname
))
5466 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
5467 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
5473 // Unicast records have zero as InterfaceID
5474 if (rr
->resrec
.InterfaceID
) return mDNSNULL
;
5476 for (q
= m
->Questions
; q
; q
=q
->next
)
5478 if (!q
->DuplicateOf
&& UnicastResourceRecordAnswersQuestion(&rr
->resrec
, q
))
5480 if (!mDNSOpaque16IsZero(q
->TargetQID
))
5482 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
5484 if (mDNSSameOpaque16(q
->TargetQID
, id
))
5489 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
5493 srcp
= q
->tcpSrcPort
;
5495 if (mDNSSameIPPort(srcp
, port
)) return(q
);
5497 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
5498 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
5499 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
5500 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
5501 q
->qname
.c
, DNSTypeName(q
->qtype
), &q
->Target
, mDNSVal16(srcp
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
5507 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
5515 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
5516 // Currently this applies only to rdata types containing more than one domainname,
5517 // or types where the domainname is not the last item in the structure.
5518 // In addition, NSEC currently requires less space for in-memory storage than its in-packet representation.
5519 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
5523 case kDNSType_SOA
: return sizeof(rdataSOA
);
5524 case kDNSType_RP
: return sizeof(rdataRP
);
5525 case kDNSType_PX
: return sizeof(rdataPX
);
5526 case kDNSType_NSEC
:return sizeof(rdataNSEC
);
5527 default: return rr
->rdlength
;
5531 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
)
5533 CacheRecord
*rr
= mDNSNULL
;
5534 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
5536 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
5538 //if (RDLength > InlineCacheRDSize)
5539 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
5541 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
5542 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
5543 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
5546 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
5547 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
5548 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
5549 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
5550 rr
->DelayDelivery
= delay
;
5552 // If this is an oversized record with external storage allocated, copy rdata to external storage
5553 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
5554 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
5555 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
5556 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
5557 if (RDLength
> InlineCacheRDSize
)
5558 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
5560 rr
->next
= mDNSNULL
; // Clear 'next' pointer
5561 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
5562 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
5564 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
5569 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
5571 rr
->TimeRcvd
= m
->timenow
;
5572 rr
->resrec
.rroriginalttl
= ttl
;
5573 rr
->UnansweredQueries
= 0;
5574 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5575 rr
->MPUnansweredQ
= 0;
5576 rr
->MPUnansweredKA
= 0;
5577 rr
->MPExpectingKA
= mDNSfalse
;
5579 SetNextCacheCheckTimeForRecord(m
, rr
);
5582 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
5585 const mDNSu32 slot
= HashSlot(&q
->qname
);
5586 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
5587 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5588 if (rr
->CRActiveQuestion
== q
)
5590 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
5591 RefreshCacheRecord(m
, rr
, lease
);
5595 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
5597 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
5598 else if (LLQType
== uDNS_LLQ_Events
)
5600 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
5601 if (ttl
== 0xFFFFFFFF) ttl
= 0;
5602 else ttl
= kLLQ_DefLease
;
5604 else // else not LLQ (standard uDNS response)
5606 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
5607 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
5608 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
5610 // Adjustment factor to avoid race condition:
5611 // 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.
5612 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
5613 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
5614 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
5615 // We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
5616 // the cached copy at our local caching server will already have expired, so the server will be forced
5617 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
5620 // For mDNS, TTL zero means "delete this record"
5621 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
5622 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
5623 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
5624 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
5625 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
5626 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
5627 // (with the current code) result in the server having even less than three seconds to respond
5628 // before we deleted the record and reported a "remove" event to any active questions.
5629 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
5630 // then things really break (e.g. we end up making a negative cache entry).
5631 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
5632 if (ttl
< 15) ttl
= 15;
5638 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5639 // the record list and/or question list.
5640 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5641 // InterfaceID non-NULL tells us the interface this multicast response was received on
5642 // InterfaceID NULL tells us this was a unicast response
5643 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
5644 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
5645 const DNSMessage
*const response
, const mDNSu8
*end
,
5646 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5647 const mDNSInterfaceID InterfaceID
)
5650 mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
5651 mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
5652 DNSQuestion
*llqMatch
= mDNSNULL
;
5653 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
5655 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
5656 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
5657 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
5658 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
5659 CacheRecord
**cfp
= &CacheFlushRecords
;
5661 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5662 // to guard against spoof responses, then the only credible protection against that is cryptographic
5663 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5664 int firstauthority
= response
->h
.numAnswers
;
5665 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
5666 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
5667 const mDNSu8
*ptr
= response
->data
;
5668 DNSServer
*uDNSServer
= mDNSNULL
;
5670 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
5671 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
5672 srcaddr
, dstaddr
, InterfaceID
,
5673 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5674 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5675 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5676 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
5678 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
5679 // When a DNS client receives a reply with TC
5680 // set, it should ignore that response, and query again, using a
5681 // mechanism, such as a TCP connection, that will permit larger replies.
5682 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
5683 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
5684 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
5685 // <rdar://problem/6690034> Can't bind to Active Directory
5686 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
5687 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
5688 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
5689 // and not even do the TCP query.
5690 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
5691 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
)) return;
5693 if (LLQType
== uDNS_LLQ_Ignore
) return;
5695 // 1. We ignore questions (if any) in mDNS response packets
5696 // 2. If this is an LLQ response, we handle it much the same
5697 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
5698 // answer as being the authoritative complete RRSet, and respond by deleting all other
5699 // matching cache records that don't appear in this packet.
5700 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
5701 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
|| (response
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5702 ptr
= LocateAnswers(response
, end
);
5703 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
5704 // in this response packet are immediately deemed to be invalid.
5707 mDNSu8 rcode
= (mDNSu8
)(response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
5708 mDNSBool failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
5709 mDNSBool returnEarly
= mDNSfalse
;
5710 // We could possibly combine this with the similar loop at the end of this function --
5711 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
5712 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
5713 // which it was received (or refreshed), and then at the end if we find any cache records which
5714 // answer questions in this packet's question section, but which aren't tagged with this packet's
5715 // packet number, then we deduce they are old and delete them
5716 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
5718 DNSQuestion q
, *qptr
= mDNSNULL
;
5719 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
5720 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
5725 const mDNSu32 slot
= HashSlot(&q
.qname
);
5726 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
5727 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5728 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
5730 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
5731 rr
->resrec
.InterfaceID
, CRDisplayString(m
, rr
));
5732 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
5733 rr
->TimeRcvd
= m
->timenow
- TicksTTL(rr
) - 1;
5734 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5741 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr
->qDNSServer
, rcode
, q
.qname
.c
, DNSTypeName(q
.qtype
));
5742 PenalizeDNSServer(m
, qptr
);
5744 returnEarly
= mDNStrue
;
5750 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
5751 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5752 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5753 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5754 // not goto exit because we won't have any CacheFlushRecords and we do not want to
5755 // generate negative cache entries (we want to query the next server)
5760 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
5762 // All responses sent via LL multicast are acceptable for caching
5763 // All responses received over our outbound TCP connections are acceptable for caching
5764 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
;
5765 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
5766 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
5768 const mDNSu8 RecordType
=
5769 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
5770 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
5771 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
5772 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5773 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
) { m
->rec
.r
.resrec
.RecordType
= 0; continue; }
5775 // Don't want to cache OPT or TSIG pseudo-RRs
5776 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
) { m
->rec
.r
.resrec
.RecordType
= 0; continue; }
5777 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
5779 const rdataOPT
*opt
;
5780 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
5781 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5782 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5783 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
5784 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
5786 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
5787 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
5789 m
->rec
.r
.resrec
.RecordType
= 0;
5793 // if a CNAME record points to itself, then don't add it to the cache
5794 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
5796 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
5797 m
->rec
.r
.resrec
.RecordType
= 0;
5801 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
5802 // In the case of active LLQs, we'll get remove events when the records actually do go away
5803 // In the case of polling LLQs, we assume the record remains valid until the next poll
5804 if (!mDNSOpaque16IsZero(response
->h
.id
))
5805 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
5807 // If response was not sent via LL multicast,
5808 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
5813 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
5814 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
5815 // queries to get ADD/RMV events. To lookup the question, we can't use
5816 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
5817 // has already matched the question using the 64 bit Id in the packet and we use that here.
5819 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
5821 else if (!AcceptableResponse
|| !dstaddr
)
5823 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
5824 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
5825 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
5828 DNSQuestion
*q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
5830 // Intialize the DNS server on the resource record which will now filter what questions we answer with
5833 // We could potentially lookup the DNS server based on the source address, but that may not work always
5834 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
5835 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
5836 // on the "id" and "source port", then this response answers the question and assume the response
5837 // came from the same DNS server that we sent the query to.
5841 AcceptableResponse
= mDNStrue
;
5844 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5845 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
5850 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
5851 // the question. The code below does that. So, make this record unacceptable for now
5854 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
5855 AcceptableResponse
= mDNSfalse
;
5861 // 1. Check that this packet resource record does not conflict with any of ours
5862 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
5864 if (m
->CurrentRecord
)
5865 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
5866 m
->CurrentRecord
= m
->ResourceRecords
;
5867 while (m
->CurrentRecord
)
5869 AuthRecord
*rr
= m
->CurrentRecord
;
5870 m
->CurrentRecord
= rr
->next
;
5871 // We accept all multicast responses, and unicast responses resulting from queries we issued
5872 // For other unicast responses, this code accepts them only for responses with an
5873 // (apparently) local source address that pertain to a record of our own that's in probing state
5874 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
5876 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
5878 // ... check to see if type and rdata are identical
5879 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
5881 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5882 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
5884 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5885 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
5889 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
5890 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5893 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
5894 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
5896 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
5897 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
-> resrec
.rdatahash
, ARDisplayString(m
, rr
));
5899 // If this record is marked DependentOn another record for conflict detection purposes,
5900 // then *that* record has to be bumped back to probing state to resolve the conflict
5901 if (rr
->DependentOn
)
5903 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
5904 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
-> resrec
.rdatahash
, ARDisplayString(m
, rr
));
5907 // If we've just whacked this record's ProbeCount, don't need to do it again
5908 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
5909 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
5910 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
5911 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
5914 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
5915 // If we'd previously verified this record, put it back to probing state and try again
5916 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
5918 LogMsg("mDNSCoreReceiveResponse: Reseting to Probing: %s", ARDisplayString(m
, rr
));
5919 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5920 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
5921 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
5922 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
5923 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
5924 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
5925 rr
->AnnounceCount
= InitialAnnounceCount
;
5926 InitializeLastAPTime(m
, rr
);
5927 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
5929 // If we're probing for this record, we just failed
5930 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
5932 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will rename %s", rr
->ProbeCount
, ARDisplayString(m
, rr
));
5933 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5935 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the same machine giving
5936 // different answers for the reverse mapping record.) This is simply a misconfiguration, and we don't try to recover from it.
5937 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
5939 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
5940 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5943 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
5946 // Else, matching signature, different type or rdata, but not a considered a conflict.
5947 // If the packet record has the cache-flush bit set, then we check to see if we
5948 // have any record(s) of the same type that we should re-assert to rescue them
5949 // (see note about "multi-homing and bridged networks" at the end of this function).
5950 else if (m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
)
5951 if ((m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
5952 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5957 if (!AcceptableResponse
)
5959 const CacheRecord
*cr
;
5960 for (cr
= CacheFlushRecords
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
5962 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
5963 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
5964 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
5965 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
5966 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
5967 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
5969 if (target
&& cr
->resrec
.rdatahash
== m
->rec
.r
.resrec
.namehash
&& SameDomainName(target
, m
->rec
.r
.resrec
.name
))
5971 debugf("mDNSCoreReceiveResponse: Found a matching entry for %##s in the CacheFlushRecords", m
->rec
.r
.resrec
.name
->c
);
5972 AcceptableResponse
= mDNStrue
;
5973 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
5979 // 2. See if we want to add this packet resource record to our cache
5980 // We only try to cache answers if we have a cache to put them in
5981 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
5982 if (!AcceptableResponse
) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m
, &m
->rec
.r
));
5983 if (m
->rrcache_size
&& AcceptableResponse
)
5985 const mDNSu32 slot
= HashSlot(m
->rec
.r
.resrec
.name
);
5986 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &m
->rec
.r
.resrec
);
5989 // 2a. Check if this packet resource record is already in our cache
5990 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5992 mDNSBool match
= !InterfaceID
? m
->rec
.r
.resrec
.rDNSServer
== rr
->resrec
.rDNSServer
: rr
->resrec
.InterfaceID
== InterfaceID
;
5993 // If we found this exact resource record, refresh its TTL
5994 if (match
&& IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
5996 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5997 verbosedebugf("Found record size %5d interface %p already in cache: %s",
5998 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
6000 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
6002 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
6003 if (rr
->NextInCFList
== mDNSNULL
&& cfp
!= &rr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
6004 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; *cfp
= (CacheRecord
*)1; }
6006 // If this packet record is marked unique, and our previous cached copy was not, then fix it
6007 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
6010 for (q
= m
->Questions
; q
; q
=q
->next
) if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) q
->UniqueAnswers
++;
6011 rr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
6015 if (!SameRDataBody(&m
->rec
.r
.resrec
, &rr
->resrec
.rdata
->u
, SameDomainNameCS
))
6017 // If the rdata of the packet record differs in name capitalization from the record in our cache
6018 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
6019 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
6020 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
6021 rr
->resrec
.rroriginalttl
= 0;
6022 rr
->TimeRcvd
= m
->timenow
;
6023 rr
->UnansweredQueries
= MaxUnansweredQueries
;
6024 SetNextCacheCheckTimeForRecord(m
, rr
);
6025 LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m
,rr
));
6026 LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m
,&m
->rec
.r
));
6027 LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
6028 NextCacheCheckEvent(rr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
6029 // DO NOT break out here -- we want to continue as if we never found it
6031 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
6034 //if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
6035 RefreshCacheRecord(m
, rr
, m
->rec
.r
.resrec
.rroriginalttl
);
6037 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
6038 // polling the network once we get a valid response back. For the first time when a new
6039 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
6040 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
6041 // configuration changed, without flushing the cache, we reset the question interval here.
6042 // Currently, we do this for for both multicast and unicast questions as long as the record
6043 // type is unique. For unicast, resource record is always unique and for multicast it is
6044 // true for records like A etc. but not for PTR.
6045 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
6047 for (q
= m
->Questions
; q
; q
=q
->next
)
6049 if (!q
->DuplicateOf
&& !q
->LongLived
&&
6050 ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
6052 q
->LastQTime
= m
->timenow
;
6053 q
->LastQTxTime
= m
->timenow
;
6054 q
->RecentAnswerPkts
= 0;
6055 q
->ThisQInterval
= MaxQuestionInterval
;
6056 q
->RequestUnicast
= mDNSfalse
;
6057 q
->unansweredQueries
= 0;
6058 debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
6059 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
6067 // If the packet TTL is zero, that means we're deleting this record.
6068 // To give other hosts on the network a chance to protest, we push the deletion
6069 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
6070 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
6071 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
6072 // If record's current expiry time is more than a second from now, we set it to expire in one second.
6073 // If the record is already going to expire in less than one second anyway, we leave it alone --
6074 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
6075 debugf("DE for %s", CRDisplayString(m
, rr
));
6076 if (RRExpireTime(rr
) - m
->timenow
> mDNSPlatformOneSecond
)
6078 rr
->resrec
.rroriginalttl
= 1;
6079 rr
->TimeRcvd
= m
->timenow
;
6080 rr
->UnansweredQueries
= MaxUnansweredQueries
;
6081 SetNextCacheCheckTimeForRecord(m
, rr
);
6088 // If packet resource record not in our cache, add it now
6089 // (unless it is just a deletion of a record we never had, in which case we don't care)
6090 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
6092 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
6093 const mDNSs32 delay
= AddToCFList
? NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
) :
6094 CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
, slot
);
6095 // If unique, assume we may have to delay delivery of this 'add' event.
6096 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
6097 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
6098 // to schedule an mDNS_Execute task at the appropriate time.
6099 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
);
6102 if (AddToCFList
) { *cfp
= rr
; cfp
= &rr
->NextInCFList
; *cfp
= (CacheRecord
*)1; }
6103 else if (rr
->DelayDelivery
) ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
6107 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6111 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6113 // If we've just received one or more records with their cache flush bits set,
6114 // then scan that cache slot to see if there are any old stale records we need to flush
6115 while (CacheFlushRecords
!= (CacheRecord
*)1)
6117 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
6118 const mDNSu32 slot
= HashSlot(r1
->resrec
.name
);
6119 const CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &r1
->resrec
);
6120 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
6121 r1
->NextInCFList
= mDNSNULL
;
6123 // Look for records in the cache with the same signature as this new one with the cache flush
6124 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
6125 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
6126 // We make these TTL adjustments *only* for records that still have *more* than one second
6127 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
6128 // (and now has half a second remaining) could inadvertently get its life extended, by either
6129 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
6130 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
6131 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
6132 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
6133 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
6134 // To avoid this, we need to ensure that the cache flushing operation will only act to
6135 // *decrease* a record's remaining lifetime, never *increase* it.
6136 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
6137 // For Unicast (null InterfaceID) the DNSservers should also match
6138 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
6139 (r1
->resrec
.InterfaceID
|| (r1
->resrec
.rDNSServer
== r2
->resrec
.rDNSServer
)) &&
6140 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
6141 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
)
6143 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
6144 // else, if record is old, mark it to be flushed
6145 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
6147 // If we find mismatched TTLs in an RRSet, correct them.
6148 // We only do this for records with a TTL of 2 or higher. It's possible to have a
6149 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
6150 // which we treat as a goodbye followed by an addition) and in that case it would be
6151 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
6152 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
6153 // because certain early Bonjour devices are known to have this specific mismatch, and
6154 // there's no point filling syslog with messages about something we already know about.
6155 // We also don't log this for uDNS responses, since a caching name server is obliged
6156 // to give us an aged TTL to correct for how long it has held the record,
6157 // so our received TTLs are expected to vary in that case
6158 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
6160 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
6161 mDNSOpaque16IsZero(response
->h
.id
))
6162 LogInfo("Correcting TTL from %4d to %4d for %s",
6163 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
6164 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
6166 r2
->TimeRcvd
= m
->timenow
;
6168 else // else, if record is old, mark it to be flushed
6170 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
6171 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
6172 // We set stale records to expire in one second.
6173 // This gives the owner a chance to rescue it if necessary.
6174 // This is important in the case of multi-homing and bridged networks:
6175 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
6176 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
6177 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
6178 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
6179 // By delaying the deletion by one second, we give X a change to notice that this bridging has
6180 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
6182 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
6183 // final expiration queries for this record.
6185 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
6186 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
6187 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
6188 // <rdar://problem/5636422> Updating TXT records is too slow
6189 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
6190 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
6191 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
6193 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
6194 r2
->resrec
.rroriginalttl
= 0;
6196 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
6198 // We only set a record to expire in one second if it currently has *more* than a second to live
6199 // If it's already due to expire in a second or less, we just leave it alone
6200 r2
->resrec
.rroriginalttl
= 1;
6201 r2
->UnansweredQueries
= MaxUnansweredQueries
;
6202 r2
->TimeRcvd
= m
->timenow
- 1;
6203 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
6204 // that we marked for deletion via an explicit DE record
6207 SetNextCacheCheckTimeForRecord(m
, r2
);
6210 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
6212 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
, slot
);
6213 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
6214 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
6215 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
6219 // See if we need to generate negative cache entries for unanswered unicast questions
6220 ptr
= response
->data
;
6221 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
6224 DNSQuestion
*qptr
= mDNSNULL
;
6225 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
6226 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
6228 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
6229 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
6230 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
6231 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
6232 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
6233 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
6234 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
6235 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
6236 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
6237 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
6238 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
6239 LogInfo("Skipping check to see if we need to generate a negative cache entry for %##s (%s)", q
.qname
.c
, DNSTypeName(q
.qtype
));
6242 CacheRecord
*rr
, *neg
= mDNSNULL
;
6243 mDNSu32 slot
= HashSlot(&q
.qname
);
6244 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
6245 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
6246 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
6248 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
6249 if (RRExpireTime(rr
) - m
->timenow
> 0) break;
6250 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
6251 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= rr
;
6256 // We start off assuming a negative caching TTL of 60 seconds
6257 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
6258 mDNSu32 negttl
= 60;
6260 const domainname
*name
= &q
.qname
;
6261 mDNSu32 hash
= q
.qnamehash
;
6263 // Special case for our special Microsoft Active Directory "local SOA" check.
6264 // Some cheap home gateways don't include an SOA record in the authority section when
6265 // they send negative responses, so we don't know how long to cache the negative result.
6266 // Because we don't want to keep hitting the root name servers with our query to find
6267 // if we're on a network using Microsoft Active Directory using "local" as a private
6268 // internal top-level domain, we make sure to cache the negative result for at least one day.
6269 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
6271 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
6272 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
6274 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
6275 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
6277 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
6278 mDNSu32 ttl_s
= soa
->min
;
6279 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
6280 // for the SOA record for ".", where the record is reported as non-cacheable
6281 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
6282 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
6283 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
6284 if (negttl
< ttl_s
) negttl
= ttl_s
;
6286 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
6287 // with an Authority Section SOA record for d.com, then this is a hint that the authority
6288 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
6289 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
6290 if (q
.qtype
== kDNSType_SOA
)
6292 int qcount
= CountLabels(&q
.qname
);
6293 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
6294 if (qcount
- 1 > scount
)
6295 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
6296 repeat
= qcount
- 1 - scount
;
6299 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6302 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
6303 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
6304 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
6305 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
6306 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
6307 // so that we back off our polling rate and don't keep hitting the server continually.
6310 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
6311 negttl
= neg
->resrec
.rroriginalttl
* 2;
6316 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
6318 // If we already had a negative cache entry just update it, else make one or more new negative cache entries
6321 debugf("Renewing negative TTL from %d to %d %s", neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
6322 RefreshCacheRecord(m
, neg
, negttl
);
6326 debugf("mDNSCoreReceiveResponse making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
6327 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
6328 CreateNewCacheEntry(m
, slot
, cg
, 0); // We never need any delivery delay for these generated negative cache records
6329 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6332 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
6333 hash
= DomainNameHashValue(name
);
6334 slot
= HashSlot(name
);
6335 cg
= CacheGroupForName(m
, slot
, hash
, name
);
6343 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
6346 for (rr
= thelist
; rr
; rr
=rr
->next
)
6347 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
6348 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6351 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
6353 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
6354 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
6357 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
6359 if (result
&& result
!= mStatus_MemFree
)
6360 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
6362 if (result
== mStatus_NameConflict
)
6364 LogMsg("Received Conflicting mDNS -- waking %s %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
6365 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
);
6366 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
);
6368 else if (result
== mStatus_MemFree
)
6371 mDNSPlatformMemFree(ar
);
6372 mDNS_UpdateAllowSleep(m
);
6376 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
6377 const DNSMessage
*const msg
, const mDNSu8
*end
,
6378 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
6379 const mDNSInterfaceID InterfaceID
)
6383 mDNSu8
*p
= m
->omsg
.data
;
6384 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
6385 mDNSu32 updatelease
= 0;
6388 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6389 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6390 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
6391 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
6392 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
6393 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
6394 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
6396 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
6398 if (mDNS_PacketLoggingEnabled
)
6399 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
6401 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
6404 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
6405 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
6408 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
6409 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
6411 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
6412 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
6415 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6418 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
6420 if (!updatelease
|| !owner
.HMAC
.l
[0])
6422 static int msgs
= 0;
6426 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
6427 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
6429 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
6431 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
6433 static int msgs
= 0;
6437 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
6438 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
6440 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
6444 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
6446 if (updatelease
> 24 * 60 * 60)
6447 updatelease
= 24 * 60 * 60;
6449 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
6450 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
6452 ptr
= LocateAuthorities(msg
, end
);
6453 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
6455 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
6456 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
6458 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
6459 AuthRecord
*ar
= mDNSPlatformMemAllocate(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
6460 if (!ar
) { m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
; break; }
6463 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
6464 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
6465 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
6466 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
6467 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, SPSRecordCallback
, ar
);
6468 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
6469 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
6470 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
6471 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
6472 ar
->ForceMCast
= mDNStrue
;
6474 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
6476 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
6477 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
6478 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
6479 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
6480 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
6482 ar
->TimeRcvd
= m
->timenow
;
6483 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
6484 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
6485 m
->NextScheduledSPS
= ar
->TimeExpire
;
6486 mDNS_Register_internal(m
, ar
);
6487 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
6488 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
6489 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
6490 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
6491 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
6492 if (m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
6493 if (ar
->resrec
.rrtype
== kDNSType_AAAA
) ar
->resrec
.rroriginalttl
= 0;
6495 mDNS_UpdateAllowSleep(m
);
6496 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
6499 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6502 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
6504 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
6505 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
6506 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
6510 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
6511 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
6512 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
6513 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
6514 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
6515 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
6516 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
6520 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
);
6523 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSInterfaceID InterfaceID
)
6528 mDNSu32 updatelease
= 60 * 60; // If SPS fails to indicate lease time, assume one hour
6529 const mDNSu8
*ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
);
6532 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
6533 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
6536 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
6537 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
6538 if (o
->opt
== kDNSOpt_Lease
)
6540 updatelease
= o
->u
.updatelease
;
6541 LogSPS("Sleep Proxy granted lease time %4d seconds", updatelease
);
6544 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6547 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6548 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
6549 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
6551 rr
->updateid
= zeroID
;
6552 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
6553 LogSPS("Sleep Proxy registered record %5d %s", updatelease
, ARDisplayString(m
,rr
));
6557 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
6558 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
6559 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
6562 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
6563 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
, DNSServer
*dnsserver
)
6565 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
6567 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
6573 // Create empty resource record
6574 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
6575 cr
->resrec
.InterfaceID
= InterfaceID
;
6576 cr
->resrec
.rDNSServer
= dnsserver
;
6577 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
6578 cr
->resrec
.rrtype
= rrtype
;
6579 cr
->resrec
.rrclass
= rrclass
;
6580 cr
->resrec
.rroriginalttl
= ttl_seconds
;
6581 cr
->resrec
.rdlength
= 0;
6582 cr
->resrec
.rdestimate
= 0;
6583 cr
->resrec
.namehash
= namehash
;
6584 cr
->resrec
.rdatahash
= 0;
6585 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
6586 cr
->resrec
.rdata
->MaxRDLength
= 0;
6588 cr
->NextInKAList
= mDNSNULL
;
6589 cr
->TimeRcvd
= m
->timenow
;
6590 cr
->DelayDelivery
= 0;
6591 cr
->NextRequiredQuery
= m
->timenow
;
6592 cr
->LastUsed
= m
->timenow
;
6593 cr
->CRActiveQuestion
= mDNSNULL
;
6594 cr
->UnansweredQueries
= 0;
6595 cr
->LastUnansweredTime
= 0;
6596 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6597 cr
->MPUnansweredQ
= 0;
6598 cr
->MPLastUnansweredQT
= 0;
6599 cr
->MPUnansweredKA
= 0;
6600 cr
->MPExpectingKA
= mDNSfalse
;
6602 cr
->NextInCFList
= mDNSNULL
;
6605 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, void *const pkt
, const mDNSu8
*const end
,
6606 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
6607 const mDNSInterfaceID InterfaceID
)
6609 mDNSInterfaceID ifid
= InterfaceID
;
6610 DNSMessage
*msg
= (DNSMessage
*)pkt
;
6611 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
6612 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
6613 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
6614 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
6616 mDNSu8
*ptr
= mDNSNULL
;
6617 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
6618 if (TLS
) dstaddr
= mDNSNULL
;
6620 #ifndef UNICAST_DISABLED
6621 if (mDNSSameAddress(srcaddr
, &m
->Router
))
6623 #ifdef _LEGACY_NAT_TRAVERSAL_
6624 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
6627 LNT_ConfigureRouterInfo(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
6632 if (mDNSSameIPPort(srcport
, NATPMPPort
))
6635 uDNS_ReceiveNATPMPPacket(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
6640 #ifdef _LEGACY_NAT_TRAVERSAL_
6641 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
6645 if ((unsigned)(end
- (mDNSu8
*)pkt
) < sizeof(DNSMessageHeader
))
6647 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
);
6650 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
6651 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
6652 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
6653 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
6654 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
6655 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
6656 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
6658 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
6660 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
6661 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
6662 if (srcaddr
&& !mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
6666 #ifndef UNICAST_DISABLED
6667 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
6668 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
6670 ifid
= mDNSInterface_Any
;
6671 if (mDNS_PacketLoggingEnabled
)
6672 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
6673 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
6674 // Note: mDNSCore also needs to get access to received unicast responses
6677 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
6678 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
6679 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
6680 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, InterfaceID
);
6683 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
6684 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
, InterfaceID
);
6685 if (mDNS_LoggingEnabled
)
6688 while (i
<end
- (mDNSu8
*)pkt
)
6691 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
6692 do if (i
<end
- (mDNSu8
*)pkt
) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", ((mDNSu8
*)pkt
)[i
]); while (++i
& 15);
6693 LogInfo("%s", buffer
);
6697 // Packet reception often causes a change to the task list:
6698 // 1. Inbound queries can cause us to need to send responses
6699 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
6700 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
6701 // 4. Response packets that answer questions may cause our client to issue new questions
6705 // ***************************************************************************
6706 #if COMPILER_LIKES_PRAGMA_MARK
6708 #pragma mark - Searcher Functions
6711 // Targets are considered the same if both queries are untargeted, or
6712 // if both are targeted to the same address+port
6713 // (If Target address is zero, TargetPort is undefined)
6714 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
6715 (mDNSSameAddress(&(A)->Target, &(B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
6717 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
6718 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
6719 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
6720 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
6721 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
6723 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
6724 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
6725 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
6726 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
6727 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
6728 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
6729 // breaks this design principle.
6731 // If IsLLQ(Q) is true, it means the question is both:
6732 // (a) long-lived and
6733 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
6734 // for multicast questions, we don't want to treat LongLived as anything special
6735 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
6737 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
6740 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
6741 // This prevents circular references, where two questions are each marked as a duplicate of the other.
6742 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
6743 // further in the list.
6744 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list for another question
6745 if (q
->InterfaceID
== question
->InterfaceID
&& // with the same InterfaceID,
6746 SameQTarget(q
, question
) && // and same unicast/multicast target settings
6747 q
->qtype
== question
->qtype
&& // type,
6748 q
->qclass
== question
->qclass
&& // class,
6749 IsLLQ(q
) == IsLLQ(question
) && // and long-lived status matches
6750 (!q
->AuthInfo
|| question
->AuthInfo
) && // to avoid deadlock, don't make public query dup of a private one
6751 (q
->SuppressQuery
== question
->SuppressQuery
) && // Questions that are suppressed/not suppressed
6752 q
->qnamehash
== question
->qnamehash
&&
6753 SameDomainName(&q
->qname
, &question
->qname
)) // and name
6758 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
6759 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
6762 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
6763 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
6764 if ((q
->DuplicateOf
= FindDuplicateQuestion(m
, q
)) == mDNSNULL
)
6766 // If q used to be a duplicate, but now is not,
6767 // then inherit the state from the question that's going away
6768 q
->LastQTime
= question
->LastQTime
;
6769 q
->ThisQInterval
= question
->ThisQInterval
;
6770 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
6771 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
6772 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
6773 q
->RequestUnicast
= question
->RequestUnicast
;
6774 q
->LastQTxTime
= question
->LastQTxTime
;
6775 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
6776 q
->nta
= question
->nta
;
6777 q
->servAddr
= question
->servAddr
;
6778 q
->servPort
= question
->servPort
;
6779 q
->qDNSServer
= question
->qDNSServer
;
6780 q
->validDNSServers
= question
->validDNSServers
;
6781 q
->unansweredQueries
= question
->unansweredQueries
;
6782 q
->noServerResponse
= question
->noServerResponse
;
6783 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
6785 q
->TargetQID
= question
->TargetQID
;
6786 q
->LocalSocket
= question
->LocalSocket
;
6788 q
->state
= question
->state
;
6789 // q->tcp = question->tcp;
6790 q
->ReqLease
= question
->ReqLease
;
6791 q
->expire
= question
->expire
;
6792 q
->ntries
= question
->ntries
;
6793 q
->id
= question
->id
;
6795 question
->LocalSocket
= mDNSNULL
;
6796 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
6797 // question->tcp = mDNSNULL;
6800 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6804 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6805 q
->nta
->ZoneDataContext
= q
;
6808 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
6809 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
6811 if (question
->state
== LLQ_Established
)
6813 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6814 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
6817 SetNextQueryTime(m
,q
);
6821 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
6824 if (server
->penaltyTime
!= 0)
6826 ptime
= server
->penaltyTime
- m
->timenow
;
6829 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
6830 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
6832 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
6833 ptime
, server
->penaltyTime
, m
->timenow
);
6834 server
->penaltyTime
= 0;
6841 //Checks to see whether the newname is a better match for the name, given the best one we have
6842 //seen so far (given in bestcount).
6843 //Returns -1 if the newname is not a better match
6844 //Returns 0 if the newname is the same as the old match
6845 //Returns 1 if the newname is a better match
6846 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
6849 // If the name contains fewer labels than the new server's domain or the new name
6850 // contains fewer labels than the current best, then it can't possibly be a better match
6851 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
6853 // If there is no match, return -1 and the caller will skip this newname for
6856 // If we find a match and the number of labels is the same as bestcount, then
6857 // we return 0 so that the caller can do additional logic to pick one of
6858 // the best based on some other factors e.g., penaltyTime
6860 // If we find a match and the number of labels is more than bestcount, then we
6861 // return 1 so that the caller can pick this over the old one.
6863 // Note: newcount can either be equal or greater than bestcount beause of the
6866 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
6867 return bestcount
== newcount
? 0 : 1;
6872 // Sets all the Valid DNS servers for a question
6873 mDNSexport
void SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
6875 DNSServer
*curmatch
= mDNSNULL
;
6876 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
6878 int bettermatch
, currcount
;
6881 question
->validDNSServers
= zeroOpaque64
;
6882 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
6884 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scoped
);
6885 // skip servers that will soon be deleted
6886 if (curr
->flags
& DNSServer_FlagDelete
)
6887 { debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
); continue; }
6889 currcount
= CountLabels(&curr
->domain
);
6890 if ((!curr
->scoped
&& (!question
->InterfaceID
|| (question
->InterfaceID
== mDNSInterface_Unicast
))) || (curr
->interface
== question
->InterfaceID
))
6892 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
6894 // If we found a better match (bettermatch == 1) then clear all the bits
6895 // corresponding to the old DNSServers that we have may set before and start fresh.
6896 // If we find an equal match, then include that DNSServer also by setting the corresponding
6898 if ((bettermatch
== 1) || (bettermatch
== 0))
6901 bestmatchlen
= currcount
;
6902 if (bettermatch
) { debugf("SetValidDNSServers: Resetting all the bits"); question
->validDNSServers
= zeroOpaque64
; }
6903 debugf("SetValidDNSServers: Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d", &curr
->addr
, curr
->domain
.c
, curr
->scoped
, index
);
6904 bit_set_opaque64(question
->validDNSServers
, index
);
6909 question
->noServerResponse
= 0;
6910 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
6911 question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
6914 // Get the Best server that matches a name. If you find penalized servers, look for the one
6915 // that will come out of the penalty box soon
6916 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSOpaque64 validBits
, int *selected
, mDNSBool nameMatch
)
6918 DNSServer
*curmatch
= mDNSNULL
;
6919 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
6921 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
6922 int bettermatch
, currcount
;
6926 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
6927 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
6928 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
6930 // skip servers that will soon be deleted
6931 if (curr
->flags
& DNSServer_FlagDelete
)
6932 { debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
); continue; }
6934 // Check if this is a valid DNSServer
6935 if (!bit_get_opaque64(validBits
, index
)) { debugf("GetBestServer: continuing for index %d", index
); index
++; continue; }
6937 currcount
= CountLabels(&curr
->domain
);
6938 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
6940 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
6941 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
6943 // If there are multiple best servers for a given question, we will pick the first one
6944 // if none of them are penalized. If some of them are penalized in that list, we pick
6945 // the least penalized one. BetterMatchForName walks through all best matches and
6946 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
6947 // in the list when there are no penalized servers and least one among them
6948 // when there are some penalized servers
6950 // Notes on InterfaceID matching:
6952 // 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
6953 // is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
6954 // entries by "scoped" being false. These are like any other unscoped entries except that
6955 // if it is picked e.g., domain match, when the packet is sent out later, the packet will
6956 // be sent out on that interface. Theese entries can be matched by either specifying a
6957 // zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
6958 // the question will cause an extra check on matching the InterfaceID on the question
6959 // against the DNSServer.
6961 // 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
6962 // is the new way of specifying an InterfaceID option for DNSServer. These will be considered
6963 // only when the question has non-zero interfaceID.
6965 if ((!curr
->scoped
&& !InterfaceID
) || (curr
->interface
== InterfaceID
))
6968 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
6969 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
6970 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
6971 // part and still do some redundant steps e.g., InterfaceID match
6973 if (nameMatch
) bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
6974 else bettermatch
= 0;
6976 // If we found a better match (bettermatch == 1) then we don't need to
6977 // compare penalty times. But if we found an equal match, then we compare
6978 // the penalty times to pick a better match
6980 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
6981 { currindex
= index
; curmatch
= curr
; bestmatchlen
= currcount
; bestPenaltyTime
= currPenaltyTime
; }
6985 if (selected
) *selected
= currindex
;
6989 // Look up a DNS Server, matching by name and InterfaceID
6990 mDNSexport DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
)
6992 DNSServer
*curmatch
= mDNSNULL
;
6993 char *ifname
= mDNSNULL
; // for logging purposes only
6994 mDNSOpaque64 allValid
;
6996 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
6997 InterfaceID
= mDNSNULL
;
6999 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
7001 // By passing in all ones, we make sure that every DNS server is considered
7002 allValid
.l
[0] = allValid
.l
[1] = 0xFFFFFFFF;
7004 curmatch
= GetBestServer(m
, name
, InterfaceID
, allValid
, mDNSNULL
, mDNStrue
);
7006 if (curmatch
!= mDNSNULL
)
7007 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch
->addr
,
7008 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
7011 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname
? ifname
: "None", InterfaceID
, name
);
7016 // Look up a DNS Server for a question within its valid DNSServer bits
7017 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
7019 DNSServer
*curmatch
= mDNSNULL
;
7020 char *ifname
= mDNSNULL
; // for logging purposes only
7021 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
7022 const domainname
*name
= &question
->qname
;
7025 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
7026 InterfaceID
= mDNSNULL
;
7028 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
7030 if (!mDNSOpaque64IsZero(&question
->validDNSServers
))
7032 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
7033 if (currindex
!= -1) bit_clr_opaque64(question
->validDNSServers
, currindex
);
7036 if (curmatch
!= mDNSNULL
)
7037 LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question
, &curmatch
->addr
,
7038 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
7039 InterfaceID
, name
, DNSTypeName(question
->qtype
));
7041 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question
, ifname
? ifname
: "None", InterfaceID
, name
, DNSTypeName(question
->qtype
));
7047 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
7048 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
7050 // Called in normal client context (lock not held)
7051 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
7056 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
7057 for (q
= m
->Questions
; q
; q
=q
->next
)
7058 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
7059 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
7060 #if APPLE_OSX_mDNSResponder
7061 UpdateAutoTunnelDomainStatuses(m
);
7066 mDNSlocal mDNSBool
ShouldSuppressQuery(mDNS
*const m
, domainname
*qname
, mDNSu16 qtype
, mDNSInterfaceID InterfaceID
)
7068 NetworkInterfaceInfo
*i
;
7070 DomainAuthInfo
*AuthInfo
;
7072 if (qtype
== kDNSType_A
) iptype
= mDNSAddrType_IPv4
;
7073 else if (qtype
== kDNSType_AAAA
) iptype
= mDNSAddrType_IPv6
;
7074 else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
7076 // We still want the ability to be able to listen to the local services and hence
7077 // don't fail .local requests. We always have a loopback interface which we don't
7079 if (InterfaceID
!= mDNSInterface_Unicast
&& IsLocalDomain(qname
)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
7081 // Skip Private domains as we have special addresses to get the hosts in the Private domain
7082 AuthInfo
= GetAuthInfoForName_internal(m
, qname
);
7083 if (AuthInfo
&& !AuthInfo
->deltime
&& AuthInfo
->AutoTunnel
)
7084 { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
7086 // Match on Type, Address and InterfaceID
7088 // Check whether we are looking for a name that ends in .local, then presence of a link-local
7089 // address on the interface is sufficient.
7090 for (i
= m
->HostInterfaces
; i
; i
= i
->next
)
7092 if (i
->ip
.type
!= iptype
) continue;
7094 if (!InterfaceID
|| (InterfaceID
== mDNSInterface_LocalOnly
) || (InterfaceID
== mDNSInterface_P2P
) ||
7095 (InterfaceID
== mDNSInterface_Unicast
) || (i
->InterfaceID
== InterfaceID
))
7097 if (iptype
== mDNSAddrType_IPv4
&& !mDNSv4AddressIsLoopback(&i
->ip
.ip
.v4
) && !mDNSv4AddressIsLinkLocal(&i
->ip
.ip
.v4
))
7099 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname
, DNSTypeName(qtype
),
7103 else if (iptype
== mDNSAddrType_IPv6
&&
7104 !mDNSv6AddressIsLoopback(&i
->ip
.ip
.v6
) &&
7105 !mDNSv6AddressIsLinkLocal(&i
->ip
.ip
.v6
) &&
7106 !mDNSSameIPv6Address(i
->ip
.ip
.v6
, m
->AutoTunnelHostAddr
) &&
7107 !mDNSSameIPv6Address(i
->ip
.ip
.v6
, m
->AutoTunnelRelayAddrOut
))
7109 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname
, DNSTypeName(qtype
),
7115 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname
, DNSTypeName(qtype
));
7119 mDNSlocal
void CheckSuppressedCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
7125 // Temporarily turn off suppression so that AnswerCurrentQuestionWithResourceRecord
7126 // can answer the question
7127 q
->SuppressQuery
= mDNSfalse
;
7128 slot
= HashSlot(&q
->qname
);
7129 cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
7130 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7132 // Don't deliver RMV events for negative records
7133 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
7135 LogInfo("CheckSuppressedCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
7136 CRDisplayString(m
, rr
), q
, q
->qname
.c
, DNSTypeName(q
->qtype
), rr
->CRActiveQuestion
, q
->CurrentAnswers
);
7140 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
7142 LogInfo("CheckSuppressedCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s",
7143 q
->qname
.c
, CRDisplayString(m
, rr
));
7145 q
->CurrentAnswers
--;
7146 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
7147 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
7149 if (rr
->CRActiveQuestion
== q
)
7152 // If this was the active question for this cache entry, it was the one that was
7153 // responsible for keeping the cache entry fresh when the cache entry was reaching
7154 // its expiry. We need to handover the responsibility to someone else. Otherwise,
7155 // when the cache entry is about to expire, we won't find an active question
7156 // (pointed by CRActiveQuestion) to refresh the cache.
7157 for (qptr
= m
->Questions
; qptr
; qptr
=qptr
->next
)
7158 if (ActiveQuestion(qptr
) && ResourceRecordAnswersQuestion(&rr
->resrec
, qptr
))
7162 LogInfo("CheckSuppressedCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
7163 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
7164 qptr
, CRDisplayString(m
,rr
), q
->CurrentAnswers
, qptr
->CurrentAnswers
, qptr
->SuppressUnusable
, qptr
->SuppressQuery
);
7166 rr
->CRActiveQuestion
= qptr
; // Question used to be active; new value may or may not be null
7167 if (!qptr
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
7169 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
7170 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
7173 if (m
->CurrentQuestion
== q
) q
->SuppressQuery
= mDNStrue
;
7176 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
7179 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
7180 if (q
== question
) return mDNStrue
;
7184 // The caller should hold the lock
7185 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
7187 DNSQuestion
*q
, *qnext
;
7188 DNSQuestion
*restart
= mDNSNULL
;
7190 // We look through all questions including new questions. During network change events,
7191 // we potentially restart questions here in this function that ends up as new questions,
7192 // which may be suppressed at this instance. Before it is handled we get another network
7193 // event that changes the status e.g., address becomes available. If we did not process
7194 // new questions, we would never change its SuppressQuery status.
7195 for (q
= m
->Questions
; q
; q
= qnext
)
7198 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->SuppressUnusable
)
7200 mDNSBool old
= q
->SuppressQuery
;
7201 q
->SuppressQuery
= ShouldSuppressQuery(m
, &q
->qname
, q
->qtype
, q
->InterfaceID
);
7202 if (q
->SuppressQuery
!= old
)
7204 if (q
->SuppressQuery
)
7206 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
7207 // followed by a negative cache response
7208 if (m
->CurrentQuestion
)
7209 LogMsg("CheckSuppressUnusableQuestions: ERROR m->CurrentQuestion already set: %##s (%s)",
7210 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
7212 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
7213 if (!IsQuestionNew(m
, q
))
7215 m
->CurrentQuestion
= q
;
7216 CheckSuppressedCurrentQuestion(m
, q
);
7217 if (m
->CurrentQuestion
!= q
)
7219 m
->CurrentQuestion
= mDNSNULL
;
7220 LogInfo("CheckSuppressUnusableQuestions: Question deleted while giving RMV events");
7223 m
->CurrentQuestion
= mDNSNULL
;
7225 else { debugf("CheckSuppressUnusableQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
7228 // There are two cases here.
7230 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
7231 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
7232 // because when we get the response, if we had entries in the cache already, it will not answer
7233 // this question if the cache entry did not change. Hence, we need to restart
7234 // the query so that it can be answered from the cache.
7236 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
7237 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
7238 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
7239 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
7240 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
7241 // immediate response and not want to be blocked behind a question that is querying DNS servers.
7242 // When the question is not suppressed, we don't want two active questions sending packets on the wire.
7243 // This affects both efficiency and also the current design where there is only one active question
7244 // pointed to from a cache entry.
7246 // We restart queries in a two step process by first calling stop and build a temporary list which we
7247 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
7248 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
7249 // will soon become the real question) including q->ThisQInterval which might be zero if it was
7250 // suppressed before. At the end when we have restarted all questions, none of them is active as each
7251 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
7253 // It is much cleaner and less error prone to build a list of questions and restart at the end.
7255 LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
7256 mDNS_StopQuery_internal(m
, q
);
7265 restart
= restart
->next
;
7267 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
7268 mDNS_StartQuery_internal(m
, q
);
7272 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
7274 if (question
->Target
.type
&& !ValidQuestionTarget(question
))
7276 LogMsg("Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery?)",
7277 question
->Target
.type
, mDNSVal16(question
->TargetPort
));
7278 question
->Target
.type
= mDNSAddrType_None
;
7281 if (!question
->Target
.type
) question
->TargetPort
= zeroIPPort
; // If no question->Target specified clear TargetPort
7283 question
->TargetQID
=
7284 #ifndef UNICAST_DISABLED
7285 (question
->Target
.type
|| Question_uDNS(question
)) ? mDNS_NewMessageID(m
) :
7286 #endif // UNICAST_DISABLED
7289 debugf("mDNS_StartQuery: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
7291 if (m
->rrcache_size
== 0) // Can't do queries if we have no cache space allocated
7292 return(mStatus_NoCache
);
7298 if (!ValidateDomainName(&question
->qname
))
7300 LogMsg("Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
7301 return(mStatus_Invalid
);
7304 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
7306 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
) q
= &m
->LocalOnlyQuestions
;
7307 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
7311 LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
7312 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
7313 return(mStatus_AlreadyRegistered
);
7318 // If this question is referencing a specific interface, verify it exists
7319 if (question
->InterfaceID
&& question
->InterfaceID
!= mDNSInterface_LocalOnly
&& question
->InterfaceID
!= mDNSInterface_Unicast
&& question
->InterfaceID
!= mDNSInterface_P2P
)
7321 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
7323 LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
7324 question
->InterfaceID
, question
->qname
.c
, DNSTypeName(question
->qtype
));
7327 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
7328 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
7329 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
7330 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
7331 // that to go out immediately.
7332 question
->next
= mDNSNULL
;
7333 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // MUST do this before FindDuplicateQuestion()
7334 question
->DelayAnswering
= CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
, HashSlot(&question
->qname
));
7335 question
->LastQTime
= m
->timenow
;
7336 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
7337 question
->ExpectUnicastResp
= 0;
7338 question
->LastAnswerPktNum
= m
->PktNum
;
7339 question
->RecentAnswerPkts
= 0;
7340 question
->CurrentAnswers
= 0;
7341 question
->LargeAnswers
= 0;
7342 question
->UniqueAnswers
= 0;
7343 question
->FlappingInterface1
= mDNSNULL
;
7344 question
->FlappingInterface2
= mDNSNULL
;
7345 // Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
7346 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
7347 if (question
->SuppressUnusable
)
7348 question
->SuppressQuery
= ShouldSuppressQuery(m
, &question
->qname
, question
->qtype
, question
->InterfaceID
);
7350 question
->SuppressQuery
= 0;
7351 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
7352 question
->NextInDQList
= mDNSNULL
;
7353 question
->SendQNow
= mDNSNULL
;
7354 question
->SendOnAll
= mDNSfalse
;
7355 question
->RequestUnicast
= 0;
7356 question
->LastQTxTime
= m
->timenow
;
7357 question
->CNAMEReferrals
= 0;
7359 // We'll create our question->LocalSocket on demand, if needed.
7360 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
7361 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
7362 // NAT mapping for receiving inbound add/remove events.
7363 question
->LocalSocket
= mDNSNULL
;
7364 question
->deliverAddEvents
= mDNSfalse
;
7365 question
->qDNSServer
= mDNSNULL
;
7366 question
->unansweredQueries
= 0;
7367 question
->nta
= mDNSNULL
;
7368 question
->servAddr
= zeroAddr
;
7369 question
->servPort
= zeroIPPort
;
7370 question
->tcp
= mDNSNULL
;
7371 question
->NoAnswer
= NoAnswer_Normal
;
7373 question
->state
= LLQ_InitialRequest
;
7374 question
->ReqLease
= 0;
7375 question
->expire
= 0;
7376 question
->ntries
= 0;
7377 question
->id
= zeroOpaque64
;
7378 question
->validDNSServers
= zeroOpaque64
;
7379 question
->triedAllServersOnce
= 0;
7380 question
->noServerResponse
= 0;
7382 if (question
->DuplicateOf
) question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
7384 for (i
=0; i
<DupSuppressInfoSize
; i
++)
7385 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
7387 debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
7388 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
7389 NextQSendTime(question
) - m
->timenow
,
7390 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
7391 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
7393 if (question
->DelayAnswering
)
7394 LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
7395 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
7397 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
)
7399 if (!m
->NewLocalOnlyQuestions
) m
->NewLocalOnlyQuestions
= question
;
7403 if (!m
->NewQuestions
) m
->NewQuestions
= question
;
7405 // If the question's id is non-zero, then it's Wide Area
7406 // MUST NOT do this Wide Area setup until near the end of
7407 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
7408 // NS, etc.) and if we haven't finished setting up our own question and setting
7409 // m->NewQuestions if necessary then we could end up recursively re-entering
7410 // this routine with the question list data structures in an inconsistent state.
7411 if (!mDNSOpaque16IsZero(question
->TargetQID
))
7413 // Duplicate questions should have the same DNSServers so that when we find
7414 // a matching resource record, all of them get the answers. Calling GetServerForQuestion
7415 // for the duplicate question may get a different DNS server from the original question
7416 if (question
->DuplicateOf
)
7418 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
7419 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
7420 LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
7421 question
, question
->DuplicateOf
, question
->qname
.c
, DNSTypeName(question
->qtype
),
7422 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
7423 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
7427 SetValidDNSServers(m
, question
);
7428 question
->qDNSServer
= GetServerForQuestion(m
, question
);
7429 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s), DNS Server %#a:%d",
7430 question
, question
->qname
.c
, DNSTypeName(question
->qtype
),
7431 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
7432 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
7434 ActivateUnicastQuery(m
, question
, mDNSfalse
);
7436 // If long-lived query, and we don't have our NAT mapping active, start it now
7437 if (question
->LongLived
&& !m
->LLQNAT
.clientContext
)
7439 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
7440 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
7441 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
7442 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
7443 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal is active
7444 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
7447 #if APPLE_OSX_mDNSResponder
7448 if (question
->LongLived
)
7449 UpdateAutoTunnelDomainStatuses(m
);
7453 SetNextQueryTime(m
,question
);
7456 return(mStatus_NoError
);
7460 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
7461 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
7463 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
7464 // This function may be called anytime to free the zone information.The question may or may not have stopped.
7465 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
7467 if (nta
->question
.ThisQInterval
!= -1)
7469 mDNS_StopQuery_internal(m
, &nta
->question
);
7470 if (nta
->question
.ThisQInterval
!= -1)
7471 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
7473 mDNSPlatformMemFree(nta
);
7476 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
7478 const mDNSu32 slot
= HashSlot(&question
->qname
);
7479 CacheGroup
*cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
7481 DNSQuestion
**qp
= &m
->Questions
;
7483 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
7485 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
) qp
= &m
->LocalOnlyQuestions
;
7486 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
7487 if (*qp
) *qp
= (*qp
)->next
;
7491 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
7493 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
7494 question
->qname
.c
, DNSTypeName(question
->qtype
));
7498 return(mStatus_BadReferenceErr
);
7501 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
7502 UpdateQuestionDuplicates(m
, question
);
7503 // But don't trash ThisQInterval until afterwards.
7504 question
->ThisQInterval
= -1;
7506 // If there are any cache records referencing this as their active question, then see if there is any
7507 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
7508 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7510 if (rr
->CRActiveQuestion
== question
)
7513 // Checking for ActiveQuestion filters questions that are suppressed also
7514 // as suppressed questions are not active
7515 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
7516 if (ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
7519 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
7520 "CurrentAnswers %d, SuppressQuery %d", q
, CRDisplayString(m
,rr
), question
->CurrentAnswers
, q
->CurrentAnswers
, q
->SuppressQuery
);
7521 rr
->CRActiveQuestion
= q
; // Question used to be active; new value may or may not be null
7522 if (!q
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
7526 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
7527 // bump its pointer forward one question.
7528 if (m
->CurrentQuestion
== question
)
7530 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
7531 question
->qname
.c
, DNSTypeName(question
->qtype
));
7532 m
->CurrentQuestion
= question
->next
;
7535 if (m
->NewQuestions
== question
)
7537 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
7538 question
->qname
.c
, DNSTypeName(question
->qtype
));
7539 m
->NewQuestions
= question
->next
;
7542 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
7544 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
7545 question
->next
= mDNSNULL
;
7547 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
7549 // And finally, cancel any associated GetZoneData operation that's still running.
7550 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
7551 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
7552 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
7553 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
7554 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
7555 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
7556 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
7558 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
7560 for (q
= m
->Questions
; q
; q
=q
->next
)
7561 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
7564 if (!m
->LLQNAT
.clientContext
) // Should never happen, but just in case...
7565 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
7568 LogInfo("Stopping LLQNAT");
7569 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
7570 m
->LLQNAT
.clientContext
= mDNSNULL
; // Means LLQ NAT Traversal not running
7574 // If necessary, tell server it can delete this LLQ state
7575 if (question
->state
== LLQ_Established
)
7577 question
->ReqLease
= 0;
7578 sendLLQRefresh(m
, question
);
7579 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
7580 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
7581 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
7582 // we let that run out its natural course and complete asynchronously.
7585 question
->tcp
->question
= mDNSNULL
;
7586 question
->tcp
= mDNSNULL
;
7589 #if APPLE_OSX_mDNSResponder
7590 UpdateAutoTunnelDomainStatuses(m
);
7593 // wait until we send the refresh above which needs the nta
7594 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
7596 return(mStatus_NoError
);
7599 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
7603 status
= mDNS_StartQuery_internal(m
, question
);
7608 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
7612 status
= mDNS_StopQuery_internal(m
, question
);
7617 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
7618 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
7619 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
7620 // specifically to catch and report if the client callback does try to make API calls
7621 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
7627 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
7628 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
7630 status
= mDNS_StopQuery_internal(m
, question
);
7631 if (status
== mStatus_NoError
&& !qq
)
7633 const CacheRecord
*rr
;
7634 const mDNSu32 slot
= HashSlot(&question
->qname
);
7635 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
7636 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
7637 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7638 if (rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameRecordAnswersQuestion(&rr
->resrec
, question
))
7640 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
7641 if (question
->QuestionCallback
)
7642 question
->QuestionCallback(m
, question
, &rr
->resrec
, mDNSfalse
);
7649 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
7653 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
7654 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
7659 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
7661 mStatus status
= mStatus_BadReferenceErr
;
7664 cr
= FindIdenticalRecordInCache(m
, rr
);
7665 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
7666 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
7667 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
7672 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
7673 const domainname
*const srv
, const domainname
*const domain
,
7674 const mDNSInterfaceID InterfaceID
, mDNSBool ForceMCast
, mDNSQuestionCallback
*Callback
, void *Context
)
7676 question
->InterfaceID
= InterfaceID
;
7677 question
->Target
= zeroAddr
;
7678 question
->qtype
= kDNSType_PTR
;
7679 question
->qclass
= kDNSClass_IN
;
7680 question
->LongLived
= mDNStrue
;
7681 question
->ExpectUnique
= mDNSfalse
;
7682 question
->ForceMCast
= ForceMCast
;
7683 question
->ReturnIntermed
= mDNSfalse
;
7684 question
->SuppressUnusable
= mDNSfalse
;
7685 question
->QuestionCallback
= Callback
;
7686 question
->QuestionContext
= Context
;
7687 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
)) return(mStatus_BadParamErr
);
7689 return(mDNS_StartQuery_internal(m
, question
));
7692 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
7693 const domainname
*const srv
, const domainname
*const domain
,
7694 const mDNSInterfaceID InterfaceID
, mDNSBool ForceMCast
, mDNSQuestionCallback
*Callback
, void *Context
)
7698 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, InterfaceID
, ForceMCast
, Callback
, Context
);
7703 mDNSlocal mDNSBool
MachineHasActiveIPv6(mDNS
*const m
)
7705 NetworkInterfaceInfo
*intf
;
7706 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
7707 if (intf
->ip
.type
== mDNSAddrType_IPv6
) return(mDNStrue
);
7711 mDNSlocal
void FoundServiceInfoSRV(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
7713 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
7714 mDNSBool PortChanged
= !mDNSSameIPPort(query
->info
->port
, answer
->rdata
->u
.srv
.port
);
7715 if (!AddRecord
) return;
7716 if (answer
->rrtype
!= kDNSType_SRV
) return;
7718 query
->info
->port
= answer
->rdata
->u
.srv
.port
;
7720 // If this is our first answer, then set the GotSRV flag and start the address query
7723 query
->GotSRV
= mDNStrue
;
7724 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
7725 AssignDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
);
7726 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
7727 AssignDomainName(&query
->qAv6
.qname
, &answer
->rdata
->u
.srv
.target
);
7728 mDNS_StartQuery(m
, &query
->qAv4
);
7729 // Only do the AAAA query if this machine actually has IPv6 active
7730 if (MachineHasActiveIPv6(m
)) mDNS_StartQuery(m
, &query
->qAv6
);
7732 // If this is not our first answer, only re-issue the address query if the target host name has changed
7733 else if ((query
->qAv4
.InterfaceID
!= query
->qSRV
.InterfaceID
&& query
->qAv4
.InterfaceID
!= answer
->InterfaceID
) ||
7734 !SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
))
7736 mDNS_StopQuery(m
, &query
->qAv4
);
7737 if (query
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery(m
, &query
->qAv6
);
7738 if (SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
) && !PortChanged
)
7740 // If we get here, it means:
7741 // 1. This is not our first SRV answer
7742 // 2. The interface ID is different, but the target host and port are the same
7743 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
7744 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
7745 query
->qAv4
.InterfaceID
= query
->qSRV
.InterfaceID
; // Will be mDNSInterface_Any, or a specific interface
7746 query
->qAv6
.InterfaceID
= query
->qSRV
.InterfaceID
;
7750 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
7751 AssignDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
);
7752 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
7753 AssignDomainName(&query
->qAv6
.qname
, &answer
->rdata
->u
.srv
.target
);
7755 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query
->qAv4
.qname
.c
, DNSTypeName(query
->qAv4
.qtype
));
7756 mDNS_StartQuery(m
, &query
->qAv4
);
7757 // Only do the AAAA query if this machine actually has IPv6 active
7758 if (MachineHasActiveIPv6(m
)) mDNS_StartQuery(m
, &query
->qAv6
);
7760 else if (query
->ServiceInfoQueryCallback
&& query
->GotADD
&& query
->GotTXT
&& PortChanged
)
7762 if (++query
->Answers
>= 100)
7763 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
7764 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.srv
.target
.c
,
7765 mDNSVal16(answer
->rdata
->u
.srv
.port
));
7766 query
->ServiceInfoQueryCallback(m
, query
);
7768 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7769 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7772 mDNSlocal
void FoundServiceInfoTXT(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
7774 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
7775 if (!AddRecord
) return;
7776 if (answer
->rrtype
!= kDNSType_TXT
) return;
7777 if (answer
->rdlength
> sizeof(query
->info
->TXTinfo
)) return;
7779 query
->GotTXT
= mDNStrue
;
7780 query
->info
->TXTlen
= answer
->rdlength
;
7781 query
->info
->TXTinfo
[0] = 0; // In case answer->rdlength is zero
7782 mDNSPlatformMemCopy(query
->info
->TXTinfo
, answer
->rdata
->u
.txt
.c
, answer
->rdlength
);
7784 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query
->info
->name
.c
, query
->GotADD
);
7786 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7787 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7788 if (query
->ServiceInfoQueryCallback
&& query
->GotADD
)
7790 if (++query
->Answers
>= 100)
7791 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
7792 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.txt
.c
);
7793 query
->ServiceInfoQueryCallback(m
, query
);
7797 mDNSlocal
void FoundServiceInfo(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
7799 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
7800 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
7801 if (!AddRecord
) return;
7803 if (answer
->rrtype
== kDNSType_A
)
7805 query
->info
->ip
.type
= mDNSAddrType_IPv4
;
7806 query
->info
->ip
.ip
.v4
= answer
->rdata
->u
.ipv4
;
7808 else if (answer
->rrtype
== kDNSType_AAAA
)
7810 query
->info
->ip
.type
= mDNSAddrType_IPv6
;
7811 query
->info
->ip
.ip
.v6
= answer
->rdata
->u
.ipv6
;
7815 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer
->name
->c
, answer
->rrtype
, DNSTypeName(answer
->rrtype
));
7819 query
->GotADD
= mDNStrue
;
7820 query
->info
->InterfaceID
= answer
->InterfaceID
;
7822 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query
->info
->ip
.type
, query
->info
->name
.c
, query
->GotTXT
);
7824 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7825 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7826 if (query
->ServiceInfoQueryCallback
&& query
->GotTXT
)
7828 if (++query
->Answers
>= 100)
7829 debugf(answer
->rrtype
== kDNSType_A
?
7830 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
7831 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
7832 query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.data
);
7833 query
->ServiceInfoQueryCallback(m
, query
);
7837 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
7838 // If the query is not interface-specific, then InterfaceID may be zero
7839 // Each time the Callback is invoked, the remainder of the fields will have been filled in
7840 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
7841 mDNSexport mStatus
mDNS_StartResolveService(mDNS
*const m
,
7842 ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
)
7847 query
->qSRV
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7848 query
->qSRV
.InterfaceID
= info
->InterfaceID
;
7849 query
->qSRV
.Target
= zeroAddr
;
7850 AssignDomainName(&query
->qSRV
.qname
, &info
->name
);
7851 query
->qSRV
.qtype
= kDNSType_SRV
;
7852 query
->qSRV
.qclass
= kDNSClass_IN
;
7853 query
->qSRV
.LongLived
= mDNSfalse
;
7854 query
->qSRV
.ExpectUnique
= mDNStrue
;
7855 query
->qSRV
.ForceMCast
= mDNSfalse
;
7856 query
->qSRV
.ReturnIntermed
= mDNSfalse
;
7857 query
->qSRV
.SuppressUnusable
= mDNSfalse
;
7858 query
->qSRV
.QuestionCallback
= FoundServiceInfoSRV
;
7859 query
->qSRV
.QuestionContext
= query
;
7861 query
->qTXT
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7862 query
->qTXT
.InterfaceID
= info
->InterfaceID
;
7863 query
->qTXT
.Target
= zeroAddr
;
7864 AssignDomainName(&query
->qTXT
.qname
, &info
->name
);
7865 query
->qTXT
.qtype
= kDNSType_TXT
;
7866 query
->qTXT
.qclass
= kDNSClass_IN
;
7867 query
->qTXT
.LongLived
= mDNSfalse
;
7868 query
->qTXT
.ExpectUnique
= mDNStrue
;
7869 query
->qTXT
.ForceMCast
= mDNSfalse
;
7870 query
->qTXT
.ReturnIntermed
= mDNSfalse
;
7871 query
->qTXT
.SuppressUnusable
= mDNSfalse
;
7872 query
->qTXT
.QuestionCallback
= FoundServiceInfoTXT
;
7873 query
->qTXT
.QuestionContext
= query
;
7875 query
->qAv4
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7876 query
->qAv4
.InterfaceID
= info
->InterfaceID
;
7877 query
->qAv4
.Target
= zeroAddr
;
7878 query
->qAv4
.qname
.c
[0] = 0;
7879 query
->qAv4
.qtype
= kDNSType_A
;
7880 query
->qAv4
.qclass
= kDNSClass_IN
;
7881 query
->qAv4
.LongLived
= mDNSfalse
;
7882 query
->qAv4
.ExpectUnique
= mDNStrue
;
7883 query
->qAv4
.ForceMCast
= mDNSfalse
;
7884 query
->qAv4
.ReturnIntermed
= mDNSfalse
;
7885 query
->qAv4
.SuppressUnusable
= mDNSfalse
;
7886 query
->qAv4
.QuestionCallback
= FoundServiceInfo
;
7887 query
->qAv4
.QuestionContext
= query
;
7889 query
->qAv6
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7890 query
->qAv6
.InterfaceID
= info
->InterfaceID
;
7891 query
->qAv6
.Target
= zeroAddr
;
7892 query
->qAv6
.qname
.c
[0] = 0;
7893 query
->qAv6
.qtype
= kDNSType_AAAA
;
7894 query
->qAv6
.qclass
= kDNSClass_IN
;
7895 query
->qAv6
.LongLived
= mDNSfalse
;
7896 query
->qAv6
.ExpectUnique
= mDNStrue
;
7897 query
->qAv6
.ForceMCast
= mDNSfalse
;
7898 query
->qAv6
.ReturnIntermed
= mDNSfalse
;
7899 query
->qAv6
.SuppressUnusable
= mDNSfalse
;
7900 query
->qAv6
.QuestionCallback
= FoundServiceInfo
;
7901 query
->qAv6
.QuestionContext
= query
;
7903 query
->GotSRV
= mDNSfalse
;
7904 query
->GotTXT
= mDNSfalse
;
7905 query
->GotADD
= mDNSfalse
;
7909 query
->ServiceInfoQueryCallback
= Callback
;
7910 query
->ServiceInfoQueryContext
= Context
;
7912 // info->name = Must already be set up by client
7913 // info->interface = Must already be set up by client
7914 info
->ip
= zeroAddr
;
7915 info
->port
= zeroIPPort
;
7918 // We use mDNS_StartQuery_internal here because we're already holding the lock
7919 status
= mDNS_StartQuery_internal(m
, &query
->qSRV
);
7920 if (status
== mStatus_NoError
) status
= mDNS_StartQuery_internal(m
, &query
->qTXT
);
7921 if (status
!= mStatus_NoError
) mDNS_StopResolveService(m
, query
);
7927 mDNSexport
void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*q
)
7930 // We use mDNS_StopQuery_internal here because we're already holding the lock
7931 if (q
->qSRV
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qSRV
);
7932 if (q
->qTXT
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qTXT
);
7933 if (q
->qAv4
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qAv4
);
7934 if (q
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qAv6
);
7938 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
7939 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
7941 question
->InterfaceID
= InterfaceID
;
7942 question
->Target
= zeroAddr
;
7943 question
->qtype
= kDNSType_PTR
;
7944 question
->qclass
= kDNSClass_IN
;
7945 question
->LongLived
= mDNSfalse
;
7946 question
->ExpectUnique
= mDNSfalse
;
7947 question
->ForceMCast
= mDNSfalse
;
7948 question
->ReturnIntermed
= mDNSfalse
;
7949 question
->SuppressUnusable
= mDNSfalse
;
7950 question
->QuestionCallback
= Callback
;
7951 question
->QuestionContext
= Context
;
7952 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
7953 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
7954 if (!dom
) dom
= &localdomain
;
7955 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
7956 return(mDNS_StartQuery(m
, question
));
7959 // ***************************************************************************
7960 #if COMPILER_LIKES_PRAGMA_MARK
7962 #pragma mark - Responder Functions
7965 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
7969 status
= mDNS_Register_internal(m
, rr
);
7974 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
7975 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
7977 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
7979 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
7980 return(mStatus_Invalid
);
7985 // If TTL is unspecified, leave TTL unchanged
7986 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
7988 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
7991 RData
*n
= rr
->NewRData
;
7992 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
7993 if (rr
->UpdateCallback
)
7994 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
7997 rr
->NewRData
= newrdata
;
7998 rr
->newrdlength
= newrdlength
;
7999 rr
->UpdateCallback
= Callback
;
8001 #ifndef UNICAST_DISABLED
8002 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
&& rr
->resrec
.InterfaceID
!= mDNSInterface_P2P
&& !IsLocalDomain(rr
->resrec
.name
))
8004 mStatus status
= uDNS_UpdateRecord(m
, rr
);
8005 // The caller frees the memory on error, don't retain stale pointers
8006 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
8012 if (rr
->resrec
.rroriginalttl
== newttl
&&
8013 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
))
8014 CompleteRDataUpdate(m
, rr
);
8017 rr
->AnnounceCount
= InitialAnnounceCount
;
8018 InitializeLastAPTime(m
, rr
);
8019 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
8020 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
8021 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
8022 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
8023 if (rr
->UpdateCredits
<= 5)
8025 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
8026 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
8027 rr
->ThisAPInterval
*= 4;
8028 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
8029 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
8030 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
8032 rr
->resrec
.rroriginalttl
= newttl
;
8036 return(mStatus_NoError
);
8039 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
8040 // the record list and/or question list.
8041 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8042 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
8046 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
8051 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
8052 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
8054 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
8056 NetworkInterfaceInfo
*intf
;
8057 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8058 if (intf
->Advertise
) break;
8062 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8064 char buffer
[MAX_REVERSE_MAPPING_NAME
];
8065 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
8066 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
8068 // Send dynamic update for non-linklocal IPv4 Addresses
8069 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, kDNSRecordTypeUnique
, mDNS_HostNameCallback
, set
);
8070 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
8071 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kHostNameTTL
, kDNSRecordTypeUnique
, mDNSNULL
, mDNSNULL
);
8073 #if ANSWER_REMOTE_HOSTNAME_QUERIES
8074 set
->RR_A
.AllowRemoteQuery
= mDNStrue
;
8075 set
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
8076 set
->RR_HINFO
.AllowRemoteQuery
= mDNStrue
;
8078 // 1. Set up Address record to map from host name ("foo.local.") to IP address
8079 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
8080 AssignDomainName(&set
->RR_A
.namestorage
, &m
->MulticastHostname
);
8081 if (set
->ip
.type
== mDNSAddrType_IPv4
)
8083 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
8084 set
->RR_A
.resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
8085 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
8086 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
8087 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
8089 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
8092 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
8093 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
8094 for (i
= 0; i
< 16; i
++)
8096 static const char hexValues
[] = "0123456789ABCDEF";
8097 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
8098 buffer
[i
* 4 + 1] = '.';
8099 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
8100 buffer
[i
* 4 + 3] = '.';
8102 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
8105 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.namestorage
, buffer
);
8106 set
->RR_PTR
.AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
8107 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
8109 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
8111 mDNS_Register_internal(m
, &set
->RR_A
);
8112 mDNS_Register_internal(m
, &set
->RR_PTR
);
8114 if (!NO_HINFO
&& m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
8116 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
8117 AssignDomainName(&set
->RR_HINFO
.namestorage
, &m
->MulticastHostname
);
8118 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
8119 mDNSPlatformMemCopy(p
, &m
->HIHardware
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
8121 mDNSPlatformMemCopy(p
, &m
->HISoftware
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
8122 mDNS_Register_internal(m
, &set
->RR_HINFO
);
8126 debugf("Not creating HINFO record: platform support layer provided no information");
8127 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
8131 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8133 NetworkInterfaceInfo
*intf
;
8135 // If we still have address records referring to this one, update them
8136 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
8137 AuthRecord
*A
= primary
? &primary
->RR_A
: mDNSNULL
;
8138 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8139 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
8140 intf
->RR_A
.RRSet
= A
;
8142 // Unregister these records.
8143 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
8144 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
8145 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
8146 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
8147 if (set
->RR_A
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
8148 if (set
->RR_PTR
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
8149 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
8152 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
8154 domainname newmname
;
8155 NetworkInterfaceInfo
*intf
;
8159 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
8160 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
8164 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
8167 AssignDomainName(&m
->MulticastHostname
, &newmname
);
8169 // 1. Stop advertising our address records on all interfaces
8170 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8171 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
);
8173 // 2. Start advertising our address records using the new name
8174 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8175 if (intf
->Advertise
) AdvertiseInterface(m
, intf
);
8178 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
8179 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) SetTargetToHostName(m
, rr
);
8180 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) SetTargetToHostName(m
, rr
);
8185 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
8187 (void)rr
; // Unused parameter
8191 char *msg
= "Unknown result";
8192 if (result
== mStatus_NoError
) msg
= "Name registered";
8193 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
8194 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
8198 if (result
== mStatus_NoError
)
8200 // Notify the client that the host name is successfully registered
8201 if (m
->MainCallback
)
8202 m
->MainCallback(m
, mStatus_NoError
);
8204 else if (result
== mStatus_NameConflict
)
8206 domainlabel oldlabel
= m
->hostlabel
;
8208 // 1. First give the client callback a chance to pick a new name
8209 if (m
->MainCallback
)
8210 m
->MainCallback(m
, mStatus_NameConflict
);
8212 // 2. If the client callback didn't do it, add (or increment) an index ourselves
8213 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
8214 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
8215 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
8216 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
8218 // 3. Generate the FQDNs from the hostlabel,
8219 // and make sure all SRV records, etc., are updated to reference our new hostname
8221 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
8223 else if (result
== mStatus_MemFree
)
8225 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
8226 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
8227 debugf("mDNS_HostNameCallback: MemFree (ignored)");
8230 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
8233 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
8235 NetworkInterfaceInfo
*intf
;
8236 active
->IPv4Available
= mDNSfalse
;
8237 active
->IPv6Available
= mDNSfalse
;
8238 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8239 if (intf
->InterfaceID
== active
->InterfaceID
)
8241 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
8242 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
8246 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
8249 LogInfo("RestartRecordGetZoneData: ResourceRecords");
8250 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
8251 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
8253 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
8254 // Zero out the updateid so that if we have a pending response from the server, it won't
8255 // be accepted as a valid response. If we accept the response, we might free the new "nta"
8256 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
8257 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
8261 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8264 set
->NetWakeBrowse
.ThisQInterval
= -1;
8267 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
8268 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
8270 set
->NextSPSAttempt
= -1;
8271 set
->NextSPSAttemptTime
= m
->timenow
;
8274 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8276 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
8277 while (p
&& p
!= set
) p
=p
->next
;
8278 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
8280 if (set
->InterfaceActive
)
8282 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
8283 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, set
->InterfaceID
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
8287 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8289 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
8290 while (p
&& p
!= set
) p
=p
->next
;
8291 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
8293 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
8296 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
8298 // Stop our browse and resolve operations
8299 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
8300 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
8302 // Make special call to the browse callback to let it know it can to remove all records for this interface
8303 if (m
->SPSBrowseCallback
)
8305 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
8306 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
8307 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8310 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
8311 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
8312 InitializeNetWakeState(m
, set
);
8316 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
8319 mDNSBool FirstOfType
= mDNStrue
;
8320 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
8322 if (!set
->InterfaceID
)
8323 { LogMsg("Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set
->ip
); return(mStatus_Invalid
); }
8325 if (!mDNSAddressIsValidNonZero(&set
->mask
))
8326 { LogMsg("Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set
->ip
, &set
->mask
); return(mStatus_Invalid
); }
8330 // Assume this interface will be active now, unless we find a duplicate already in the list
8331 set
->InterfaceActive
= mDNStrue
;
8332 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
8333 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
8335 InitializeNetWakeState(m
, set
);
8337 // Scan list to see if this InterfaceID is already represented
8342 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
8344 return(mStatus_AlreadyRegistered
);
8347 if ((*p
)->InterfaceID
== set
->InterfaceID
)
8349 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
8350 set
->InterfaceActive
= mDNSfalse
;
8351 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
8352 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
8353 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
8359 set
->next
= mDNSNULL
;
8363 AdvertiseInterface(m
, set
);
8365 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set
->InterfaceID
, set
->ifname
, &set
->ip
,
8366 set
->InterfaceActive
?
8367 "not represented in list; marking active and retriggering queries" :
8368 "already represented in list; marking inactive for now");
8370 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
8372 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
8373 // giving the false impression that there's an active representative of this interface when there really isn't.
8374 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
8375 // even if we believe that we previously had an active representative of this interface.
8376 if (set
->McastTxRx
&& ((m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) || FirstOfType
|| set
->InterfaceActive
))
8379 // Normally, after an interface comes up, we pause half a second before beginning probing.
8380 // This is to guard against cases where there's rapid interface changes, where we could be confused by
8381 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
8382 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
8383 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
8384 // and think it's a conflicting answer to our probe.
8385 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
8386 const mDNSs32 probedelay
= flapping
? mDNSPlatformOneSecond
* 5 : mDNSPlatformOneSecond
/ 2;
8387 const mDNSu8 numannounce
= flapping
? (mDNSu8
)1 : InitialAnnounceCount
;
8389 // Use a small amount of randomness:
8390 // In the case of a network administrator turning on an Ethernet hub so that all the
8391 // connected machines establish link at exactly the same time, we don't want them all
8392 // to go and hit the network with identical queries at exactly the same moment.
8393 // We set a random delay of up to InitialQuestionInterval (1/3 second).
8394 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
8395 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
8396 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
8397 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
8398 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
8399 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
8401 if (flapping
) LogMsg("RegisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
8403 LogInfo("RegisterInterface: %s (%#a) probedelay %d", set
->ifname
, &set
->ip
, probedelay
);
8404 if (m
->SuppressProbes
== 0 ||
8405 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
8406 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
8408 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
8409 if (mDNSOpaque16IsZero(q
->TargetQID
))
8410 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
8411 { // then reactivate this question
8412 // If flapping, delay between first and second queries is nine seconds instead of one second
8413 mDNSBool dodelay
= flapping
&& (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
8414 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
8415 mDNSs32 qdelay
= dodelay
? mDNSPlatformOneSecond
* 5 : 0;
8416 if (dodelay
) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q
->qname
.c
, DNSTypeName(q
->qtype
));
8418 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
8420 q
->ThisQInterval
= initial
;
8421 q
->RequestUnicast
= 2; // Set to 2 because is decremented once *before* we check it
8423 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
8424 q
->RecentAnswerPkts
= 0;
8425 SetNextQueryTime(m
,q
);
8428 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
8429 // we now need them to re-probe if necessary, and then re-announce.
8430 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
8431 if (!AuthRecord_uDNS(rr
))
8432 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
8434 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
8435 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
8436 if (rr
->AnnounceCount
< numannounce
) rr
->AnnounceCount
= numannounce
;
8437 rr
->SendNSECNow
= mDNSNULL
;
8438 InitializeLastAPTime(m
, rr
);
8442 RestartRecordGetZoneData(m
);
8444 CheckSuppressUnusableQuestions(m
);
8446 mDNS_UpdateAllowSleep(m
);
8449 return(mStatus_NoError
);
8452 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
8453 // the record list and/or question list.
8454 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8455 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
8457 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
8459 mDNSBool revalidate
= mDNSfalse
;
8460 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
8461 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
8462 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
8463 if (m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) revalidate
= mDNStrue
;
8467 // Find this record in our list
8468 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
8469 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
8471 mDNS_DeactivateNetWake_internal(m
, set
);
8473 // Unlink this record from our list
8475 set
->next
= mDNSNULL
;
8477 if (!set
->InterfaceActive
)
8479 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
8480 NetworkInterfaceInfo
*intf
;
8481 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8482 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
8483 UpdateInterfaceProtocols(m
, intf
);
8487 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
8490 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
8491 " making it active", set
->InterfaceID
, set
->ifname
, &set
->ip
);
8492 if (intf
->InterfaceActive
)
8493 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set
->ifname
, &set
->ip
);
8494 intf
->InterfaceActive
= mDNStrue
;
8495 UpdateInterfaceProtocols(m
, intf
);
8497 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
8499 // See if another representative *of the same type* exists. If not, we mave have gone from
8500 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
8501 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8502 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
8504 if (!intf
) revalidate
= mDNStrue
;
8514 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
8515 " marking questions etc. dormant", set
->InterfaceID
, set
->ifname
, &set
->ip
);
8517 if (set
->McastTxRx
&& flapping
)
8518 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
8520 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
8521 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
8522 for (q
= m
->Questions
; q
; q
=q
->next
)
8524 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
8525 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
8527 q
->FlappingInterface2
= q
->FlappingInterface1
;
8528 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
8532 // 2. Flush any cache records received on this interface
8533 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
8534 FORALL_CACHERECORDS(slot
, cg
, rr
)
8535 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
8537 // If this interface is deemed flapping,
8538 // postpone deleting the cache records in case the interface comes back again
8539 if (set
->McastTxRx
&& flapping
)
8541 // For a flapping interface we want these record to go away after 30 seconds
8542 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
8543 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
8544 // if the interface does come back, any relevant questions will be reactivated anyway
8545 rr
->UnansweredQueries
= MaxUnansweredQueries
;
8548 mDNS_PurgeCacheResourceRecord(m
, rr
);
8551 // 3. Any DNS servers specific to this interface are now unusable
8552 for (s
= m
->DNSServers
; s
; s
= s
->next
)
8553 if (s
->interface
== set
->InterfaceID
)
8555 s
->interface
= mDNSInterface_Any
;
8556 s
->teststate
= DNSServer_Disabled
;
8561 // If we were advertising on this interface, deregister those address and reverse-lookup records now
8562 if (set
->Advertise
) DeadvertiseInterface(m
, set
);
8564 // If we have any cache records received on this interface that went away, then re-verify them.
8565 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
8566 // giving the false impression that there's an active representative of this interface when there really isn't.
8567 // Don't need to do this when shutting down, because *all* interfaces are about to go away
8568 if (revalidate
&& !m
->ShutdownTime
)
8573 FORALL_CACHERECORDS(slot
, cg
, rr
)
8574 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
8575 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
8578 CheckSuppressUnusableQuestions(m
);
8580 mDNS_UpdateAllowSleep(m
);
8585 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
8587 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
8588 (void)m
; // Unused parameter
8592 char *msg
= "Unknown result";
8593 if (result
== mStatus_NoError
) msg
= "Name Registered";
8594 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
8595 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
8596 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
8600 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
8601 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
8603 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
8604 if (result
== mStatus_NameConflict
)
8606 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
8607 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
8611 if (result
== mStatus_MemFree
)
8613 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
8614 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
8615 // every record is finished cleaning up.
8617 ExtraResourceRecord
*e
= sr
->Extras
;
8619 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8620 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8621 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8622 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8623 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8627 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8631 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
8632 // then we can now report the NameConflict to the client
8633 if (sr
->Conflict
) result
= mStatus_NameConflict
;
8637 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered": "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
8638 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
8639 // function is allowed to do anything, including deregistering this service and freeing its memory.
8640 if (sr
->ServiceCallback
)
8641 sr
->ServiceCallback(m
, sr
, result
);
8644 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
8646 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
8647 if (sr
->ServiceCallback
)
8648 sr
->ServiceCallback(m
, sr
, result
);
8652 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
8653 // Type is service type (e.g. "_ipp._tcp.")
8654 // Domain is fully qualified domain name (i.e. ending with a null label)
8655 // We always register a TXT, even if it is empty (so that clients are not
8656 // left waiting forever looking for a nonexistent record.)
8657 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
8658 // then the default host name (m->MulticastHostname) is automatically used
8659 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
8660 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
8661 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
8662 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
8663 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
8664 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
)
8669 sr
->ServiceCallback
= Callback
;
8670 sr
->ServiceContext
= Context
;
8671 sr
->Conflict
= mDNSfalse
;
8673 sr
->Extras
= mDNSNULL
;
8674 sr
->NumSubTypes
= NumSubTypes
;
8675 sr
->SubTypes
= SubTypes
;
8677 // Initialize the AuthRecord objects to sane values
8678 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
8679 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, ServiceCallback
, sr
);
8680 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
8681 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
8682 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
8684 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
8685 if (mDNSIPPortIsZero(port
))
8686 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, mDNSInterface_Any
, NSSCallback
, sr
));
8688 // If the client is registering an oversized TXT record,
8689 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
8690 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
8691 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
8693 // Set up the record names
8694 // For now we only create an advisory record for the main type, not for subtypes
8695 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
8696 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
8697 return(mStatus_BadParamErr
);
8698 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8699 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8700 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
8702 // 1. Set up the ADV record rdata to advertise our service type
8703 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
8705 // 2. Set up the PTR record rdata to point to our service name
8706 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
8707 // Note: uDNS registration code assumes that Additional1 points to the SRV record
8708 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
8709 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
8710 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
8712 // 2a. Set up any subtype PTRs to point to our service name
8713 // If the client is using subtypes, it is the client's responsibility to have
8714 // already set the first label of the record name to the subtype being registered
8715 for (i
=0; i
<NumSubTypes
; i
++)
8718 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
8719 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
8720 AppendDomainName(&st
, type
);
8721 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
8722 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8723 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
8724 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
8725 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
8728 // 3. Set up the SRV record rdata.
8729 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
8730 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
8731 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
8733 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
8734 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
8735 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
8737 // 4. Set up the TXT record rdata,
8738 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
8739 // Note: uDNS registration code assumes that DependentOn points to the SRV record
8740 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
8741 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
8743 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
8744 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
8745 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
8747 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
8750 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
8751 // that if the SRV cannot find a target, rest of the records that belong to this service
8752 // will not be activated.
8753 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
8754 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
8755 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
8756 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
8757 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
8758 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
8759 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
8760 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
8761 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
8762 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
8766 if (err
) mDNS_DeregisterService(m
, sr
);
8770 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
8771 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
)
8773 ExtraResourceRecord
**e
;
8776 extra
->next
= mDNSNULL
;
8777 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
8778 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
8779 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
8783 while (*e
) e
= &(*e
)->next
;
8785 if (ttl
== 0) ttl
= kStandardTTL
;
8787 extra
->r
.DependentOn
= &sr
->RR_SRV
;
8789 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
8790 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
8792 status
= mDNS_Register_internal(m
, &extra
->r
);
8793 if (status
== mStatus_NoError
) *e
= extra
;
8799 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
8800 mDNSRecordCallback MemFreeCallback
, void *Context
)
8802 ExtraResourceRecord
**e
;
8807 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
8810 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
8811 status
= mStatus_BadReferenceErr
;
8815 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
8816 extra
->r
.RecordCallback
= MemFreeCallback
;
8817 extra
->r
.RecordContext
= Context
;
8819 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
8825 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
8827 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
8828 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
8829 domainlabel name1
, name2
;
8830 domainname type
, domain
;
8831 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
8832 ExtraResourceRecord
*extras
= sr
->Extras
;
8835 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
8839 IncrementLabelSuffix(&name2
, mDNStrue
);
8843 if (SameDomainName(&domain
, &localdomain
))
8844 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
8845 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
8847 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
8848 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
8849 sr
->SubTypes
, sr
->NumSubTypes
,
8850 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
);
8852 // mDNS_RegisterService() just reset sr->Extras to NULL.
8853 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
8854 // through the old list of extra records, and re-add them to our freshly created service registration
8855 while (!err
&& extras
)
8857 ExtraResourceRecord
*e
= extras
;
8858 extras
= extras
->next
;
8859 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
);
8865 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
8866 // which may change the record list and/or question list.
8867 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8868 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
8870 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
8871 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
8873 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
8875 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
8876 return(mStatus_BadReferenceErr
);
8878 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
8880 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
8881 // Avoid race condition:
8882 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
8883 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
8884 // If the client happens to deregister the service in the middle of that process, then
8885 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
8886 // instead of incorrectly promoting it to mStatus_NameConflict.
8887 // This race condition is exposed particularly when the conformance test generates
8888 // a whole batch of simultaneous conflicts across a range of services all advertised
8889 // using the same system default name, and if we don't take this precaution then
8890 // we end up incrementing m->nicelabel multiple times instead of just once.
8891 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
8892 sr
->Conflict
= mDNSfalse
;
8893 return(mStatus_NoError
);
8899 ExtraResourceRecord
*e
;
8903 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
8904 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
8905 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
8906 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
8908 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
8910 // We deregister all of the extra records, but we leave the sr->Extras list intact
8911 // in case the client wants to do a RenameAndReregister and reinstate the registration
8914 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
8918 for (i
=0; i
<sr
->NumSubTypes
; i
++)
8919 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
8921 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
8927 // Create a registration that asserts that no such service exists with this name.
8928 // This can be useful where there is a given function is available through several protocols.
8929 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
8930 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
8931 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
8932 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
8933 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
8934 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
8935 const domainname
*const host
,
8936 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
)
8938 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, Callback
, Context
);
8939 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8940 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
8941 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
8942 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
8943 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
8944 else rr
->AutoTarget
= Target_AutoHost
;
8945 return(mDNS_Register(m
, rr
));
8948 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
8949 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
8951 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, mDNSNULL
, mDNSNULL
);
8952 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
8953 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
8954 return(mDNS_Register(m
, rr
));
8957 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
8960 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
8964 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
8967 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
8971 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
8976 for (i
=0; i
<10; i
++)
8978 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
8979 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
8982 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
8987 // ***************************************************************************
8988 #if COMPILER_LIKES_PRAGMA_MARK
8990 #pragma mark - Sleep Proxy Server
8993 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
8995 // If we see an ARP from a machine we think is sleeping, then either
8996 // (i) the machine has woken, or
8997 // (ii) it's just a stray old packet from before the machine slept
8998 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
8999 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
9000 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
9001 // 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*
9002 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
9003 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
9005 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
9006 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
9008 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
9009 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
9010 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
9011 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
9012 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
9013 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
9014 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
9015 InitializeLastAPTime(m
, rr
);
9018 rr
->AnnounceCount
= InitialAnnounceCount
;
9019 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
9020 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
9021 SetNextAnnounceProbeTime(m
, rr
);
9025 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
9027 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
9029 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
9035 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
9036 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
9037 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
9038 // The times we might need to react to an ARP Announcement are:
9039 // (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
9040 // (ii) if it's a conflicting Announcement from another host
9041 // -- and we check for these in Pass 2 below.
9042 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
9044 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9045 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9046 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
9048 static const char msg1
[] = "ARP Req from owner -- re-probing";
9049 static const char msg2
[] = "Ignoring ARP Request from ";
9050 static const char msg3
[] = "Creating Local ARP Cache entry ";
9051 static const char msg4
[] = "Answering ARP Request from ";
9052 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
9053 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
9054 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
9055 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
9056 intf
->ifname
, msg
, &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9057 if (msg
== msg1
) RestartARPProbing(m
, rr
);
9058 else if (msg
== msg3
) mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
9059 else if (msg
== msg4
) SendARP(m
, 2, rr
, &arp
->tpa
, &arp
->sha
, &arp
->spa
, &arp
->sha
);
9064 // 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.
9065 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
9066 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
9067 // 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.
9068 // If we see an apparently conflicting ARP, we check the sender hardware address:
9069 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
9070 // 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.
9071 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
9072 debugf("ARP from self for %.4a", &arp
->tpa
);
9075 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
9076 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9077 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9078 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
))
9080 RestartARPProbing(m
, rr
);
9081 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
9082 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
9083 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
9084 &arp
->sha
, &arp
->spa
, &arp
->tpa
, ARDisplayString(m
, rr
));
9087 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
9088 &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9089 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
9098 // Option 1 is Source Link Layer Address Option
9099 // Option 2 is Target Link Layer Address Option
9100 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
9102 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
9103 while (options < end)
9105 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
9106 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
9107 options += options[1] * 8;
9113 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
9114 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
9117 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
9122 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
9123 if (ndp
->type
== NDP_Sol
)
9125 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
9127 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9128 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9129 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
9131 static const char msg1
[] = "NDP Req from owner -- re-probing";
9132 static const char msg2
[] = "Ignoring NDP Request from ";
9133 static const char msg3
[] = "Creating Local NDP Cache entry ";
9134 static const char msg4
[] = "Answering NDP Request from ";
9135 static const char msg5
[] = "Answering NDP Probe from ";
9136 const char *const msg
= sha
&& mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
9137 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
9138 sha
&& mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
9139 spa
&& mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
9140 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
9141 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9142 if (msg
== msg1
) RestartARPProbing(m
, rr
);
9143 else if (msg
== msg3
)
9145 if (!(m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
))
9146 mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
9148 else if (msg
== msg4
) SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
9149 else if (msg
== msg5
) SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
9153 // 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.
9154 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
9155 debugf("NDP from self for %.16a", &ndp
->target
);
9158 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
9159 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
9160 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
9161 // Hence it is the NDP target address we care about, not the actual packet source address.
9162 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
9163 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
9164 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9165 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9166 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
))
9168 RestartARPProbing(m
, rr
);
9169 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
9170 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
9171 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
9174 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
9175 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9176 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
9184 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
9185 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
9187 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
9188 mDNSBool wake
= mDNSfalse
;
9192 #define XX wake ? "Received" : "Ignoring", end-p
9193 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
9197 #define SSH_AsNumber 22
9198 static const mDNSIPPort SSH
= { { SSH_AsNumber
>> 8, SSH_AsNumber
& 0xFF } };
9201 // (a) RST is not set, AND
9202 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
9203 wake
= (!(t
->tcp
.flags
& 4) && (t
->tcp
.flags
& 3) != 1);
9205 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
9206 // except for ssh connections, where we'll wake for plain data packets too
9207 if (!mDNSSameIPPort(port
, SSH
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
9209 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
9210 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
9211 (t
->tcp
.flags
& 2) ? " SYN" : "",
9212 (t
->tcp
.flags
& 1) ? " FIN" : "",
9213 (t
->tcp
.flags
& 4) ? " RST" : "");
9218 #define ARD_AsNumber 3283
9219 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
9220 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
9221 if (udplen
>= sizeof(UDPHeader
))
9223 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
9226 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
9227 if (mDNSSameIPPort(port
, IPSECPort
))
9229 // Specifically ignore NAT keepalive packets
9230 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
9233 // Skip over the Non-ESP Marker if present
9234 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
9235 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
9236 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
9237 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
9238 if ((ike
->Version
& 0x10) == 0x10)
9240 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
9241 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
9242 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
9243 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
9248 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
9249 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
9250 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
9251 // UDP header (8 bytes)
9252 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
9253 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
9255 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
9260 case 0x3A: if (&t
->bytes
[len
] <= end
)
9262 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
9263 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
9264 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
9268 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
9274 AuthRecord
*rr
, *r2
;
9277 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9278 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
9279 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9280 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
9282 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
9283 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
9284 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
9285 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9286 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
9287 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
9289 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
9292 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
9293 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
9294 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
9297 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
9298 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
9304 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
9306 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
9307 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
9308 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
9309 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
9310 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
9312 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
9313 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
9314 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
9315 // since it points to a an address 14 bytes before pkt.
9316 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
9317 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
9319 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
9321 // Is ARP? Length must be at least 14 + 28 = 42 bytes
9322 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
9323 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
9324 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
9325 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
9327 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
9328 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
, &pkt
->v4
.dst
);
9329 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
9330 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
9331 if (end
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
9332 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
, 0);
9334 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
9335 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
9337 const mDNSu8
*const trans
= p
+ 54;
9338 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
, &pkt
->v6
.dst
);
9339 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
9340 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
9341 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
9342 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
9343 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
9347 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
9349 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d %#s",
9350 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, &m
->nicelabel
);
9353 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
9355 if (result
== mStatus_NameConflict
)
9356 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
9357 else if (result
== mStatus_MemFree
)
9363 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
9367 ConstructSleepProxyServerName(m
, &name
);
9368 mDNS_RegisterService(m
, srs
,
9369 &name
, &SleepProxyServiceType
, &localdomain
,
9370 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
9371 (mDNSu8
*)"", 1, // TXT data, length
9372 mDNSNULL
, 0, // Subtypes (none)
9373 mDNSInterface_Any
, // Interface ID
9374 SleepProxyServerCallback
, mDNSNULL
); // Callback and context
9376 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
9381 // Called with lock held
9382 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
)
9384 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
9385 mDNS_DropLockBeforeCallback();
9387 // If turning off SPS, close our socket
9388 // (Do this first, BEFORE calling mDNS_DeregisterService below)
9389 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
9391 // If turning off, or changing type, deregister old name
9392 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
9393 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
9395 // Record our new SPS parameters
9397 m
->SPSPortability
= port
;
9398 m
->SPSMarginalPower
= marginalpower
;
9399 m
->SPSTotalPower
= totpower
;
9401 // If turning on, open socket and advertise service
9406 m
->SPSSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
9407 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
9409 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
9411 else if (m
->SPSState
)
9413 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
9414 m
->NextScheduledSPS
= m
->timenow
;
9417 mDNS_ReclaimLockAfterCallback();
9420 // ***************************************************************************
9421 #if COMPILER_LIKES_PRAGMA_MARK
9423 #pragma mark - Startup and Shutdown
9426 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
9428 if (storage
&& numrecords
)
9431 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
9432 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
9433 storage
[numrecords
-1].next
= m
->rrcache_free
;
9434 m
->rrcache_free
= storage
;
9435 m
->rrcache_size
+= numrecords
;
9439 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
9442 mDNS_GrowCache_internal(m
, storage
, numrecords
);
9446 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
9447 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
9448 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
9454 if (!rrcachestorage
) rrcachesize
= 0;
9458 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
9459 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
9460 m
->DivertMulticastAdvertisements
= mDNSfalse
;
9461 m
->mDNSPlatformStatus
= mStatus_Waiting
;
9462 m
->UnicastPort4
= zeroIPPort
;
9463 m
->UnicastPort6
= zeroIPPort
;
9464 m
->PrimaryMAC
= zeroEthAddr
;
9465 m
->MainCallback
= Callback
;
9466 m
->MainContext
= Context
;
9467 m
->rec
.r
.resrec
.RecordType
= 0;
9469 // For debugging: To catch and report locking failures
9471 m
->mDNS_reentrancy
= 0;
9472 m
->ShutdownTime
= 0;
9473 m
->lock_rrcache
= 0;
9474 m
->lock_Questions
= 0;
9475 m
->lock_Records
= 0;
9477 // Task Scheduling variables
9478 result
= mDNSPlatformTimeInit();
9479 if (result
!= mStatus_NoError
) return(result
);
9480 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
9481 timenow
= mDNS_TimeNow_NoLock(m
);
9483 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
9484 m
->timenow_last
= timenow
;
9485 m
->NextScheduledEvent
= timenow
;
9486 m
->SuppressSending
= timenow
;
9487 m
->NextCacheCheck
= timenow
+ 0x78000000;
9488 m
->NextScheduledQuery
= timenow
+ 0x78000000;
9489 m
->NextScheduledProbe
= timenow
+ 0x78000000;
9490 m
->NextScheduledResponse
= timenow
+ 0x78000000;
9491 m
->NextScheduledNATOp
= timenow
+ 0x78000000;
9492 m
->NextScheduledSPS
= timenow
+ 0x78000000;
9493 m
->RandomQueryDelay
= 0;
9494 m
->RandomReconfirmDelay
= 0;
9496 m
->LocalRemoveEvents
= mDNSfalse
;
9497 m
->SleepState
= SleepState_Awake
;
9499 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
9500 m
->SentSleepProxyRegistration
= mDNSfalse
;
9501 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
9505 // These fields only required for mDNS Searcher...
9506 m
->Questions
= mDNSNULL
;
9507 m
->NewQuestions
= mDNSNULL
;
9508 m
->CurrentQuestion
= mDNSNULL
;
9509 m
->LocalOnlyQuestions
= mDNSNULL
;
9510 m
->NewLocalOnlyQuestions
= mDNSNULL
;
9511 m
->rrcache_size
= 0;
9512 m
->rrcache_totalused
= 0;
9513 m
->rrcache_active
= 0;
9514 m
->rrcache_report
= 10;
9515 m
->rrcache_free
= mDNSNULL
;
9517 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
9519 m
->rrcache_hash
[slot
] = mDNSNULL
;
9520 m
->rrcache_nextcheck
[slot
] = timenow
+ 0x78000000;;
9523 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
9525 // Fields below only required for mDNS Responder...
9526 m
->hostlabel
.c
[0] = 0;
9527 m
->nicelabel
.c
[0] = 0;
9528 m
->MulticastHostname
.c
[0] = 0;
9529 m
->HIHardware
.c
[0] = 0;
9530 m
->HISoftware
.c
[0] = 0;
9531 m
->ResourceRecords
= mDNSNULL
;
9532 m
->DuplicateRecords
= mDNSNULL
;
9533 m
->NewLocalRecords
= mDNSNULL
;
9534 m
->CurrentRecord
= mDNSNULL
;
9535 m
->HostInterfaces
= mDNSNULL
;
9536 m
->ProbeFailTime
= 0;
9537 m
->NumFailedProbes
= 0;
9538 m
->SuppressProbes
= 0;
9540 #ifndef UNICAST_DISABLED
9541 m
->NextuDNSEvent
= timenow
+ 0x78000000;
9542 m
->NextSRVUpdate
= timenow
+ 0x78000000;
9544 m
->DNSServers
= mDNSNULL
;
9546 m
->Router
= zeroAddr
;
9547 m
->AdvertisedV4
= zeroAddr
;
9548 m
->AdvertisedV6
= zeroAddr
;
9550 m
->AuthInfoList
= mDNSNULL
;
9552 m
->ReverseMap
.ThisQInterval
= -1;
9553 m
->StaticHostname
.c
[0] = 0;
9555 m
->Hostnames
= mDNSNULL
;
9556 m
->AutoTunnelHostAddr
.b
[0] = 0;
9557 m
->AutoTunnelHostAddrActive
= mDNSfalse
;
9558 m
->AutoTunnelLabel
.c
[0] = 0;
9560 m
->StartWABQueries
= mDNSfalse
;
9561 m
->RegisterAutoTunnel6
= mDNStrue
;
9563 // NAT traversal fields
9564 m
->NATTraversals
= mDNSNULL
;
9565 m
->CurrentNATTraversal
= mDNSNULL
;
9566 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
9567 m
->retryGetAddr
= timenow
+ 0x78000000; // absolute time when we retry
9568 m
->ExternalAddress
= zerov4Addr
;
9570 m
->NATMcastRecvskt
= mDNSNULL
;
9571 m
->LastNATupseconds
= 0;
9572 m
->LastNATReplyLocalTime
= timenow
;
9573 m
->LastNATMapResultCode
= NATErr_None
;
9575 m
->UPnPInterfaceID
= 0;
9576 m
->SSDPSocket
= mDNSNULL
;
9577 m
->SSDPWANPPPConnection
= mDNSfalse
;
9578 m
->UPnPRouterPort
= zeroIPPort
;
9579 m
->UPnPSOAPPort
= zeroIPPort
;
9580 m
->UPnPRouterURL
= mDNSNULL
;
9581 m
->UPnPWANPPPConnection
= mDNSfalse
;
9582 m
->UPnPSOAPURL
= mDNSNULL
;
9583 m
->UPnPRouterAddressString
= mDNSNULL
;
9584 m
->UPnPSOAPAddressString
= mDNSNULL
;
9586 m
->SPSPortability
= 0;
9587 m
->SPSMarginalPower
= 0;
9588 m
->SPSTotalPower
= 0;
9590 m
->SPSProxyListChanged
= mDNSNULL
;
9591 m
->SPSSocket
= mDNSNULL
;
9592 m
->SPSBrowseCallback
= mDNSNULL
;
9593 m
->ProxyRecords
= 0;
9597 #if APPLE_OSX_mDNSResponder
9598 m
->TunnelClients
= mDNSNULL
;
9601 CHECK_WCF_FUNCTION(WCFConnectionNew
)
9603 m
->WCF
= WCFConnectionNew();
9604 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
9610 result
= mDNSPlatformInit(m
);
9612 #ifndef UNICAST_DISABLED
9613 // It's better to do this *after* the platform layer has set up the
9614 // interface list and security credentials
9615 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
9621 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
9623 if (m
->SPSState
== 1)
9625 domainlabel name
, newname
;
9626 domainname type
, domain
;
9627 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
9628 ConstructSleepProxyServerName(m
, &newname
);
9629 if (!SameDomainLabelCS(name
.c
, newname
.c
))
9631 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
9632 // When SleepProxyServerCallback gets the mStatus_MemFree message,
9633 // it will reregister the service under the new name
9635 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
9639 if (m
->MainCallback
)
9640 m
->MainCallback(m
, mStatus_ConfigChanged
);
9643 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
9646 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
9647 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
9650 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
, const DNSServer
* const ptr
, mDNSBool lameduck
)
9652 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
9653 cr
->resrec
.rrtype
== kDNSType_A
||
9654 cr
->resrec
.rrtype
== kDNSType_AAAA
||
9655 cr
->resrec
.rrtype
== kDNSType_SRV
;
9659 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
9660 purge
? "purging" : "reconfirming",
9661 lameduck
? "lame duck" : "new",
9662 ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
, CRDisplayString(m
, cr
));
9666 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
9667 mDNS_PurgeCacheResourceRecord(m
, cr
);
9671 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
9672 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
9676 mDNSlocal
void CacheRecordResetDNSServer(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
9678 const mDNSu32 slot
= HashSlot(&q
->qname
);
9679 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
9681 mDNSBool found
= mDNSfalse
;
9682 mDNSBool foundNew
= mDNSfalse
;
9683 DNSServer
*old
= q
->qDNSServer
;
9684 mDNSBool newQuestion
= IsQuestionNew(m
, q
);
9687 // This function is called when the DNSServer is updated to the new question. There may already be
9688 // some cache entries matching the old DNSServer and/or new DNSServer. There are four cases. In the
9689 // following table, "Yes" denotes that a cache entry was found for old/new DNSServer.
9691 // old DNSServer new DNSServer
9698 // Case 1: There are cache entries for both old and new DNSServer. We handle this case by simply
9699 // expiring the old Cache entries, deliver a RMV event (if an ADD event was delivered before)
9700 // followed by the ADD event of the cache entries corresponding to the new server. This
9701 // case happens when we pick a DNSServer, issue a query and get a valid response and create
9702 // cache entries after which it stops responding. Another query (non-duplicate) picks a different
9703 // DNSServer and creates identical cache entries (perhaps through records in Additional records).
9704 // Now if the first one expires and tries to pick the new DNSServer (the original DNSServer
9705 // is not responding) we will find cache entries corresponding to both DNSServers.
9707 // Case 2: There are no cache entries for the old DNSServer but there are some for the new DNSServer.
9708 // This means we should deliver an ADD event. Normally ADD events are delivered by
9709 // AnswerNewQuestion if it is a new question. So, we check to see if it is a new question
9710 // and if so, leave it to AnswerNewQuestion to deliver it. Otherwise, we use
9711 // AnswerQuestionsForDNSServerChanges to deliver the ADD event. This case happens when a
9712 // question picks a DNS server for which AnswerNewQuestion could not deliver an answer even
9713 // though there were potential cache entries but DNSServer did not match. Now when we
9714 // pick a new DNSServer, those cache entries may answer this question.
9716 // Case 3: There are the cache entries for the old DNSServer but none for the new. We just move
9717 // the old cache entries to point to the new DNSServer and the caller is expected to
9718 // do a purge or reconfirm to delete or validate the RDATA. We don't need to do anything
9719 // special for delivering ADD events, as it should have been done/will be done by
9720 // AnswerNewQuestion. This case happens when we picked a DNSServer, sent the query and
9721 // got a response and the cache is expired now and we are reissuing the question but the
9722 // original DNSServer does not respond.
9724 // Case 4: There are no cache entries either for the old or for the new DNSServer. There is nothing
9725 // much we can do here.
9727 // Case 2 and 3 are the most common while case 4 is possible when no DNSServers are working. Case 1
9728 // is relatively less likely to happen in practice
9730 // Temporarily set the DNSServer to look for the matching records for the new DNSServer.
9731 q
->qDNSServer
= new;
9732 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
9734 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
9736 LogInfo("CacheRecordResetDNSServer: Found cache record %##s for new DNSServer address: %#a", rp
->resrec
.name
->c
,
9737 (rp
->resrec
.rDNSServer
!= mDNSNULL
? &rp
->resrec
.rDNSServer
->addr
: mDNSNULL
));
9738 foundNew
= mDNStrue
;
9742 q
->qDNSServer
= old
;
9744 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
9746 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
9752 LogInfo("CacheRecordResetDNSServer: Flushing Resourcerecord %##s, before:%#a, after:%#a", rp
->resrec
.name
->c
,
9753 (rp
->resrec
.rDNSServer
!= mDNSNULL
? &rp
->resrec
.rDNSServer
->addr
: mDNSNULL
),
9754 (new != mDNSNULL
? &new->addr
: mDNSNULL
));
9755 mDNS_PurgeCacheResourceRecord(m
, rp
);
9758 // "q" is not a duplicate question. If it is a newQuestion, then the CRActiveQuestion can't be
9759 // possibly set as it is set only when we deliver the ADD event to the question.
9760 if (rp
->CRActiveQuestion
!= mDNSNULL
)
9762 LogMsg("CacheRecordResetDNSServer: ERROR!!: CRActiveQuestion %p set, current question %p, name %##s", rp
->CRActiveQuestion
, q
, q
->qname
.c
);
9763 rp
->CRActiveQuestion
= mDNSNULL
;
9765 // if this is a new question, then we never delivered an ADD yet, so don't deliver the RMV.
9769 LogInfo("CacheRecordResetDNSServer: resetting cache record %##s DNSServer address before:%#a,"
9770 " after:%#a, CRActiveQuestion %p", rp
->resrec
.name
->c
, (rp
->resrec
.rDNSServer
!= mDNSNULL
?
9771 &rp
->resrec
.rDNSServer
->addr
: mDNSNULL
), (new != mDNSNULL
? &new->addr
: mDNSNULL
),
9772 rp
->CRActiveQuestion
);
9773 // Though we set it to the new DNS server, the caller is *assumed* to do either a purge
9774 // or reconfirm or send out questions to the "new" server to verify whether the cached
9776 rp
->resrec
.rDNSServer
= new;
9780 // Case 1 and Case 2
9781 if ((found
&& foundNew
) || (!found
&& foundNew
))
9784 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9785 else if (QuerySuppressed(q
))
9786 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for suppressed question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9789 LogInfo("CacheRecordResetDNSServer: deliverAddEvents set for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9790 q
->deliverAddEvents
= mDNStrue
;
9791 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9792 if (qptr
->DuplicateOf
== q
) qptr
->deliverAddEvents
= mDNStrue
;
9797 // Case 3 and Case 4
9801 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
9805 // 1. Whenever we change the DNS server, we change the message identifier also so that response
9806 // from the old server is not accepted as a response from the new server but only messages
9807 // from the new server are accepted as valid responses. We do it irrespective of whether "new"
9808 // is NULL or not. It is possible that we send two queries, no responses, pick a new DNS server
9809 // which is NULL and now the response comes back and will try to penalize the DNS server which
9810 // is NULL. By setting the messageID here, we will not accept that as a valid response.
9812 q
->TargetQID
= mDNS_NewMessageID(m
);
9814 // 2. Move the old cache records to point them at the new DNSServer so that we can deliver the ADD/RMV events
9815 // appropriately. At any point in time, we want all the cache records point only to one DNSServer for a given
9816 // question. "DNSServer" here is the DNSServer object and not the DNS server itself. It is possible to
9817 // have the same DNS server address in two objects, one scoped and another not scoped. But, the cache is per
9818 // DNSServer object. By maintaining the question and the cache entries point to the same DNSServer
9819 // always, the cache maintenance and delivery of ADD/RMV events becomes simpler.
9821 // CacheRecordResetDNSServer should be called only once for the non-duplicate question as once the cache
9822 // entries are moved to point to the new DNSServer, we don't need to call it for the duplicate question
9823 // and it is wrong to call for the duplicate question as it's decision to mark deliverAddevents will be
9827 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
9829 CacheRecordResetDNSServer(m
, q
, new);
9831 // 3. Make sure all the duplicate questions point to the same DNSServer so that delivery
9832 // of events for all of them are consistent. Duplicates for a question are always inserted
9833 // after in the list.
9834 q
->qDNSServer
= new;
9835 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9837 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
9841 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
9849 DNSServer
*ptr
, **p
= &m
->DNSServers
;
9850 const DNSServer
*oldServers
= m
->DNSServers
;
9853 debugf("uDNS_SetupDNSConfig: entry");
9855 // Let the platform layer get the current DNS information
9856 // The m->StartWABQueries boolean is so that we lazily get the search domain list only on-demand
9857 // and start the domain enumeration queries. (no need to hit the network with domain enumeration
9858 // queries until we actually need that information).
9860 uDNS_SetupSearchDomains(m
, m
->StartWABQueries
? (UDNS_START_WAB_QUERY
| UDNS_START_CF_QUERY
) :
9861 (UDNS_START_CF_QUERY
));
9865 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
9867 ptr
->penaltyTime
= 0;
9868 ptr
->flags
|= DNSServer_FlagDelete
;
9871 mDNSPlatformSetDNSConfig(m
, mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
);
9873 // Mark the records to be flushed that match a new resolver. We need to do this before
9874 // we walk the questions below where we change the DNSServer pointer of the cache
9876 FORALL_CACHERECORDS(slot
, cg
, cr
)
9878 if (cr
->resrec
.InterfaceID
) continue;
9880 // We just mark them for purge or reconfirm. We can't affect the DNSServer pointer
9881 // here as the code below that calls CacheRecordResetDNSServer relies on this
9883 // The new DNSServer may be a scoped or non-scoped one. We use the active question's
9884 // InterfaceID for looking up the right DNS server
9885 ptr
= GetServerForName(m
, cr
->resrec
.name
, cr
->CRActiveQuestion
? cr
->CRActiveQuestion
->InterfaceID
: mDNSNULL
);
9887 // Purge or Reconfirm if this cache entry would use the new DNS server
9888 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
9890 // As the DNSServers for this cache record is not the same anymore, we don't
9891 // want any new questions to pick this old value
9892 if (cr
->CRActiveQuestion
== mDNSNULL
)
9894 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s", CRDisplayString(m
, cr
));
9895 mDNS_PurgeCacheResourceRecord(m
, cr
);
9898 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNSfalse
);
9901 // Update our qDNSServer pointers before we go and free the DNSServer object memory
9902 for (q
= m
->Questions
; q
; q
=q
->next
)
9903 if (!mDNSOpaque16IsZero(q
->TargetQID
))
9907 if (q
->DuplicateOf
) continue;
9908 SetValidDNSServers(m
, q
);
9909 q
->triedAllServersOnce
= 0;
9910 s
= GetServerForQuestion(m
, q
);
9914 // If DNS Server for this question has changed, reactivate it
9915 debugf("uDNS_SetupDNSConfig: Updating DNS Server from %p %#a:%d (%##s) to %p %#a:%d (%##s) for %##s (%s)",
9916 t
, t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), t
? t
->domain
.c
: (mDNSu8
*)"",
9917 s
, s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), s
? s
->domain
.c
: (mDNSu8
*)"",
9918 q
->qname
.c
, DNSTypeName(q
->qtype
));
9920 // After we reset the DNSServer pointer on the cache records here, three things could happen:
9922 // 1) The query gets sent out and when the actual response comes back later it is possible
9923 // that the response has the same RDATA, in which case we update our cache entry.
9924 // If the response is different, then the entry will expire and a new entry gets added.
9925 // For the latter case to generate a RMV followed by ADD events, we need to reset the DNS
9926 // server here to match the question and the cache record.
9928 // 2) We might have marked the cache entries for purge above and for us to be able to generate the RMV
9929 // events for the questions, the DNSServer on the question should match the Cache Record
9931 // 3) We might have marked the cache entries for reconfirm above, for which we send the query out which is
9932 // the same as the first case above.
9934 DNSServerChangeForQuestion(m
, q
, s
);
9935 q
->unansweredQueries
= 0;
9936 // We still need to pick a new DNSServer for the questions that have been
9937 // suppressed, but it is wrong to activate the query as DNS server change
9938 // could not possibly change the status of SuppressUnusable questions
9939 if (!QuerySuppressed(q
))
9941 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9942 ActivateUnicastQuery(m
, q
, mDNStrue
);
9943 // ActivateUnicastQuery is called for duplicate questions also as it does something
9944 // special for AutoTunnel questions
9945 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9947 if (qptr
->DuplicateOf
== q
) ActivateUnicastQuery(m
, qptr
, mDNStrue
);
9953 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
9954 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), q
->DuplicateOf
, q
->SuppressUnusable
);
9955 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9956 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
9962 if (((*p
)->flags
& DNSServer_FlagDelete
) != 0)
9964 // Scan our cache, looking for uDNS records that we would have queried this server for.
9965 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
9966 // different DNS servers can give different answers to the same question.
9968 FORALL_CACHERECORDS(slot
, cg
, cr
)
9970 if (cr
->resrec
.InterfaceID
) continue;
9971 if (cr
->resrec
.rDNSServer
== ptr
)
9973 // If we don't have an active question for this cache record, neither Purge can
9974 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
9975 // pointer on the record NULL so that we don't point to freed memory (We might dereference
9976 // DNSServer pointers from resource record for logging purposes).
9978 // If there is an active question, point to its DNSServer as long as it does not point to the
9979 // freed one. We already went through the questions above and made them point at either the
9980 // new server or NULL if there is no server and also affected the cache entries that match
9981 // this question. Hence, whenever we hit a resource record with a DNSServer that is just
9982 // about to be deleted, we should never have an active question. The code below just tries to
9983 // be careful logging messages if we ever hit this case.
9985 if (cr
->CRActiveQuestion
)
9987 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
9988 if (qptr
->qDNSServer
== mDNSNULL
)
9989 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) with DNSServer Address NULL, Server to be deleted %#a",
9990 CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), &ptr
->addr
);
9992 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) DNSServer Address %#a, Server to be deleted %#a",
9993 CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), &qptr
->qDNSServer
->addr
, &ptr
->addr
);
9995 if (qptr
->qDNSServer
== ptr
)
9997 qptr
->validDNSServers
= zeroOpaque64
;
9998 qptr
->qDNSServer
= mDNSNULL
;
9999 cr
->resrec
.rDNSServer
= mDNSNULL
;
10003 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
10008 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
10009 cr
->resrec
.name
, &cr
->resrec
.rDNSServer
->addr
, &ptr
->addr
);
10010 cr
->resrec
.rDNSServer
= mDNSNULL
;
10013 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNStrue
);
10017 debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
);
10018 mDNSPlatformMemFree(ptr
);
10019 NumUnicastDNSServers
--;
10023 (*p
)->flags
&= ~DNSServer_FlagNew
;
10028 // 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).
10029 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
10030 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
10031 // 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.
10032 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
10035 FORALL_CACHERECORDS(slot
, cg
, cr
) if (!cr
->resrec
.InterfaceID
) { mDNS_PurgeCacheResourceRecord(m
, cr
); count
++; }
10036 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
10037 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
10039 // Force anything that needs to get zone data to get that information again
10040 RestartRecordGetZoneData(m
);
10043 // Did our FQDN change?
10044 if (!SameDomainName(&fqdn
, &m
->FQDN
))
10046 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
10048 AssignDomainName(&m
->FQDN
, &fqdn
);
10052 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
10053 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
10059 // handle router and primary interface changes
10060 v4
= v6
= r
= zeroAddr
;
10061 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
10063 if (mDNSPlatformGetPrimaryInterface(m
, &v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
10065 mDNS_SetPrimaryInterfaceInfo(m
,
10066 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
10067 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
10068 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
10072 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
10073 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
10076 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers
);
10077 return mStatus_NoError
;
10080 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
10082 m
->mDNSPlatformStatus
= result
;
10083 if (m
->MainCallback
)
10086 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
10087 m
->MainCallback(m
, mStatus_NoError
);
10088 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
10093 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
10095 m
->CurrentRecord
= start
;
10096 while (m
->CurrentRecord
)
10098 AuthRecord
*rr
= m
->CurrentRecord
;
10099 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
10100 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
10101 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
10102 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
10103 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
10104 else if (rr
->AnnounceCount
> 1)
10106 rr
->AnnounceCount
= 1;
10107 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
10109 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10110 // new records could have been added to the end of the list as a result of that call.
10111 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
10112 m
->CurrentRecord
= rr
->next
;
10116 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
10118 NetworkInterfaceInfo
*intf
;
10123 LogInfo("mDNS_StartExit");
10124 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
10126 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0);
10128 #if APPLE_OSX_mDNSResponder
10130 CHECK_WCF_FUNCTION(WCFConnectionDealloc
)
10132 if (m
->WCF
) WCFConnectionDealloc((WCFConnection
*)m
->WCF
);
10137 #ifndef UNICAST_DISABLED
10141 // Don't need to do SleepRecordRegistrations() here
10142 // because we deregister all records and services later in this routine
10143 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
10145 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
10146 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
10147 // and we may crash because the list still contains dangling pointers.
10148 for (s
= SearchList
; s
; s
= s
->next
)
10149 while (s
->AuthRecs
)
10151 ARListElem
*dereg
= s
->AuthRecs
;
10152 s
->AuthRecs
= s
->AuthRecs
->next
;
10153 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
10158 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10159 if (intf
->Advertise
)
10160 DeadvertiseInterface(m
, intf
);
10162 // Shut down all our active NAT Traversals
10163 while (m
->NATTraversals
)
10165 NATTraversalInfo
*t
= m
->NATTraversals
;
10166 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
10168 // After stopping the NAT Traversal, we zero out the fields.
10169 // This has particularly important implications for our AutoTunnel records --
10170 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
10171 // handlers to just turn around and attempt to re-register those same records.
10172 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
10174 t
->ExternalAddress
= zerov4Addr
;
10175 t
->ExternalPort
= zeroIPPort
;
10176 t
->RequestedPort
= zeroIPPort
;
10178 t
->Result
= mStatus_NoError
;
10181 // Make sure there are nothing but deregistering records remaining in the list
10182 if (m
->CurrentRecord
)
10183 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
10185 // We're in the process of shutting down, so queries, etc. are no longer available.
10186 // Consequently, determining certain information, e.g. the uDNS update server's IP
10187 // address, will not be possible. The records on the main list are more likely to
10188 // already contain such information, so we deregister the duplicate records first.
10189 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
10190 DeregLoop(m
, m
->DuplicateRecords
);
10191 LogInfo("mDNS_StartExit: Deregistering resource records");
10192 DeregLoop(m
, m
->ResourceRecords
);
10194 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
10195 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
10196 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
10198 m
->NextScheduledResponse
= m
->timenow
;
10199 m
->SuppressSending
= 0;
10202 if (m
->ResourceRecords
) LogInfo("mDNS_StartExit: Sending final record deregistrations");
10203 else LogInfo("mDNS_StartExit: No deregistering records remain");
10205 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
10206 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
10208 // If any deregistering records remain, send their deregistration announcements before we exit
10209 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
10213 LogInfo("mDNS_StartExit: done");
10216 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
10218 mDNSu32 rrcache_active
= 0;
10219 mDNSu32 rrcache_totalused
= 0;
10223 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
10224 mDNSPlatformClose(m
);
10226 rrcache_totalused
= m
->rrcache_totalused
;
10227 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
10229 while (m
->rrcache_hash
[slot
])
10231 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
10232 while (cg
->members
)
10234 CacheRecord
*cr
= cg
->members
;
10235 cg
->members
= cg
->members
->next
;
10236 if (cr
->CRActiveQuestion
) rrcache_active
++;
10237 ReleaseCacheRecord(m
, cr
);
10239 cg
->rrcache_tail
= &cg
->members
;
10240 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
10243 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
10244 if (rrcache_active
!= m
->rrcache_active
)
10245 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active
, m
->rrcache_active
);
10247 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
10248 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
10250 LogInfo("mDNS_FinalExit: done");