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 mDNS_StartQuery_internal(m
, q
); // start new query
2862 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
2863 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
2864 q
->CNAMEReferrals
= c
;
2869 // New Questions are answered through AnswerNewQuestion. But there may not have been any
2870 // matching cache records for the questions when it is called. There are two possibilities.
2872 // 1) There are no cache records
2873 // 2) There are cache records but the DNSServers between question and cache record don't match.
2875 // In the case of (1), where there are no cache records and later we add them when we get a response,
2876 // CacheRecordAdd/CacheRecordDeferredAdd will take care of adding the cache and delivering the ADD
2877 // events to the application. If we already have a cache entry, then no ADD events are delivered
2878 // unless the RDATA has changed
2880 // In the case of (2) where we had the cache records and did not answer because of the DNSServer mismatch,
2881 // we need to answer them whenever we change the DNSServer. But we can't do it at the instant the DNSServer
2882 // changes because when we do the callback, the question can get deleted and the calling function would not
2883 // know how to handle it. So, we run this function from mDNS_Execute to handle DNSServer changes on the
2886 mDNSlocal
void AnswerQuestionsForDNSServerChanges(mDNS
*const m
)
2894 if (m
->CurrentQuestion
)
2895 LogMsg("AnswerQuestionsForDNSServerChanges: ERROR m->CurrentQuestion already set: %##s (%s)",
2896 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2898 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
= qnext
)
2902 // multicast or DNSServers did not change.
2903 if (mDNSOpaque16IsZero(q
->TargetQID
)) continue;
2904 if (!q
->deliverAddEvents
) continue;
2906 // We are going to look through the cache for this question since it changed
2907 // its DNSserver last time. Reset it so that we don't call them again. Calling
2908 // them again will deliver duplicate events to the application
2909 q
->deliverAddEvents
= mDNSfalse
;
2910 if (QuerySuppressed(q
)) continue;
2911 m
->CurrentQuestion
= q
;
2912 slot
= HashSlot(&q
->qname
);
2913 cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
2914 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
2916 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
2918 LogInfo("AnswerQuestionsForDNSServerChanges: Calling AnswerCurrentQuestionWithResourceRecord for question %p %##s using resource record %s",
2919 q
, q
->qname
.c
, CRDisplayString(m
, rr
));
2920 // When this question penalizes a DNS server and has no more DNS servers to pick, we normally
2921 // deliver a negative cache response and suspend the question for 60 seconds (see uDNS_CheckCurrentQuestion).
2922 // But sometimes we may already find the negative cache entry and deliver that here as the process
2923 // of changing DNS servers. When the cache entry is about to expire, we will resend the question and
2924 // that time, we need to make sure that we have a valid DNS server. Otherwise, we will deliver
2925 // a negative cache response without trying the server.
2926 if (!q
->qDNSServer
&& !q
->DuplicateOf
&& rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
2929 SetValidDNSServers(m
, q
);
2930 q
->qDNSServer
= GetServerForQuestion(m
, q
);
2931 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
2932 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
2934 q
->CurrentAnswers
++;
2935 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
2936 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
2937 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
2938 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
2942 m
->CurrentQuestion
= mDNSNULL
;
2945 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*rr
)
2947 rr
->DelayDelivery
= 0;
2948 if (m
->CurrentQuestion
)
2949 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
2950 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2951 m
->CurrentQuestion
= m
->Questions
;
2952 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
2954 DNSQuestion
*q
= m
->CurrentQuestion
;
2955 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
2956 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
2957 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
2958 m
->CurrentQuestion
= q
->next
;
2960 m
->CurrentQuestion
= mDNSNULL
;
2963 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSu32 slot
)
2965 const mDNSs32 threshhold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
2966 const mDNSs32 start
= m
->timenow
- 0x10000000;
2967 mDNSs32 delay
= start
;
2968 CacheGroup
*cg
= CacheGroupForName(m
, slot
, namehash
, name
);
2969 const CacheRecord
*rr
;
2970 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
2971 if (threshhold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
2972 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
2973 delay
= RRExpireTime(rr
);
2974 if (delay
- start
> 0) return(NonZeroTime(delay
));
2978 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
2979 // If new questions are created as a result of invoking client callbacks, they will be added to
2980 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
2981 // rr is a new CacheRecord just received into our cache
2982 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
2983 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
2984 // which may change the record list and/or question list.
2985 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2986 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
2990 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
2991 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
2992 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
2994 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
2996 // If this question is one that's actively sending queries, and it's received ten answers within one
2997 // second of sending the last query packet, then that indicates some radical network topology change,
2998 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
2999 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3000 // because we will anyway send another query within a few seconds. The first reset query is sent out
3001 // randomized over the next four seconds to reduce possible synchronization between machines.
3002 if (q
->LastAnswerPktNum
!= m
->PktNum
)
3004 q
->LastAnswerPktNum
= m
->PktNum
;
3005 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
3006 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
3008 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3009 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
3010 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
3011 q
->ThisQInterval
= InitialQuestionInterval
;
3012 SetNextQueryTime(m
,q
);
3015 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr
, rr
->resrec
.name
->c
,
3016 DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
, rr
->resrec
.rDNSServer
?
3017 &rr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(rr
->resrec
.rDNSServer
?
3018 rr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
3019 q
->CurrentAnswers
++;
3020 q
->unansweredQueries
= 0;
3021 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
3022 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
3023 if (q
->CurrentAnswers
> 4000)
3025 static int msgcount
= 0;
3026 if (msgcount
++ < 10)
3027 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3028 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
3029 rr
->resrec
.rroriginalttl
= 0;
3030 rr
->UnansweredQueries
= MaxUnansweredQueries
;
3035 if (!rr
->DelayDelivery
)
3037 if (m
->CurrentQuestion
)
3038 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3039 m
->CurrentQuestion
= m
->Questions
;
3040 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3042 q
= m
->CurrentQuestion
;
3043 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3044 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
3045 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3046 m
->CurrentQuestion
= q
->next
;
3048 m
->CurrentQuestion
= mDNSNULL
;
3051 SetNextCacheCheckTimeForRecord(m
, rr
);
3054 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3055 // If new questions are created as a result of invoking client callbacks, they will be added to
3056 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3057 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3058 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3059 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3060 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3061 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3062 // which may change the record list and/or question list.
3063 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3064 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*rr
)
3066 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
3067 if (m
->CurrentQuestion
)
3068 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3069 m
->CurrentQuestion
= m
->Questions
;
3070 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
3071 // since we're not caching the record and we'll get no opportunity to do this later
3072 while (m
->CurrentQuestion
)
3074 DNSQuestion
*q
= m
->CurrentQuestion
;
3075 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3076 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
3077 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3078 m
->CurrentQuestion
= q
->next
;
3080 m
->CurrentQuestion
= mDNSNULL
;
3083 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3084 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3085 // If new questions are created as a result of invoking client callbacks, they will be added to
3086 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3087 // rr is an existing cache CacheRecord that just expired and is being deleted
3088 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3089 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3090 // which may change the record list and/or question list.
3091 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3092 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
3094 if (m
->CurrentQuestion
)
3095 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3096 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3097 m
->CurrentQuestion
= m
->Questions
;
3099 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3100 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3101 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3103 DNSQuestion
*q
= m
->CurrentQuestion
;
3104 // When a question enters suppressed state, we generate RMV events and generate a negative
3105 // response. A cache may be present that answers this question e.g., cache entry generated
3106 // before the question became suppressed. We need to skip the suppressed questions here as
3107 // the RMV event has already been generated.
3108 if (!QuerySuppressed(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3110 verbosedebugf("CacheRecordRmv %p %s", rr
, CRDisplayString(m
, rr
));
3111 q
->FlappingInterface1
= mDNSNULL
;
3112 q
->FlappingInterface2
= mDNSNULL
;
3114 // When a question changes DNS server, it is marked with deliverAddEvents if we find any
3115 // cache entry corresponding to the new DNS server. Before we deliver the ADD event, the
3116 // cache entry may be removed in which case CurrentAnswers can be zero.
3117 if (q
->deliverAddEvents
&& !q
->CurrentAnswers
)
3119 LogInfo("CacheRecordRmv: Question %p %##s (%s) deliverAddEvents set, DNSServer %#a:%d",
3120 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
3121 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
3122 m
->CurrentQuestion
= q
->next
;
3125 if (q
->CurrentAnswers
== 0)
3126 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3127 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
3128 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
3131 q
->CurrentAnswers
--;
3132 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
3133 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
3135 if (rr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
3137 if (q
->CurrentAnswers
== 0)
3139 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3140 q
->qname
.c
, DNSTypeName(q
->qtype
));
3141 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
3143 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
3146 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3147 m
->CurrentQuestion
= q
->next
;
3149 m
->CurrentQuestion
= mDNSNULL
;
3152 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
3154 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3156 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
3158 e
->next
= m
->rrcache_free
;
3159 m
->rrcache_free
= e
;
3160 m
->rrcache_totalused
--;
3163 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
3165 CacheEntity
*e
= (CacheEntity
*)(*cp
);
3166 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3167 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
3168 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3169 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
3170 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3171 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
3172 (*cp
)->name
= mDNSNULL
;
3173 *cp
= (*cp
)->next
; // Cut record from list
3174 ReleaseCacheEntity(m
, e
);
3177 mDNSlocal
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
3179 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3180 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
3181 r
->resrec
.rdata
= mDNSNULL
;
3182 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
3185 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3186 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3187 // callbacks for old records are delivered before callbacks for newer records.
3188 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
3190 CacheRecord
**rp
= &cg
->members
;
3192 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3193 m
->lock_rrcache
= 1;
3197 CacheRecord
*const rr
= *rp
;
3198 mDNSs32 event
= RRExpireTime(rr
);
3199 if (m
->timenow
- event
>= 0) // If expired, delete it
3201 *rp
= rr
->next
; // Cut it from the list
3202 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3203 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
3204 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
3206 DNSQuestion
*q
= rr
->CRActiveQuestion
;
3207 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3208 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3209 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3210 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3211 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3212 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3213 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
3214 if (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
&& ActiveQuestion(q
))
3216 q
->ThisQInterval
= InitialQuestionInterval
;
3217 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3218 SetNextQueryTime(m
, q
);
3220 CacheRecordRmv(m
, rr
);
3221 m
->rrcache_active
--;
3223 ReleaseCacheRecord(m
, rr
);
3225 else // else, not expired; see if we need to query
3227 // If waiting to delay delivery, do nothing until then
3228 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
3229 event
= rr
->DelayDelivery
;
3232 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
3233 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3235 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
3236 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
3237 else // else trigger our question to go out now
3239 // Set NextScheduledQuery to timenow so that SendQueries() will run.
3240 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
3241 m
->NextScheduledQuery
= m
->timenow
;
3242 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3243 // which will correctly update m->NextCacheCheck for us.
3244 event
= m
->timenow
+ 0x3FFFFFFF;
3248 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3249 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
3250 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3251 m
->rrcache_nextcheck
[slot
] = event
;
3255 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
3256 cg
->rrcache_tail
= rp
;
3257 m
->lock_rrcache
= 0;
3260 // Caller should hold the lock
3261 mDNSlocal
void AnswerSuppressUnusableQuestion(mDNS
*const m
, DNSQuestion
*q
)
3263 LogInfo("AnswerSuppressUnusableQuestion: Generating negative response for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3264 if (!m
->CurrentQuestion
) LogMsg("AnswerSuppressUnusableQuestion: ERROR!! CurrentQuestion not set");
3266 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, mDNSNULL
);
3267 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
3268 if (m
->CurrentQuestion
== q
) q
->ThisQInterval
= 0; // Deactivate this question
3269 // Don't touch the question after this
3270 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
3273 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
3275 mDNSBool ShouldQueryImmediately
= mDNStrue
;
3276 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
3277 const mDNSu32 slot
= HashSlot(&q
->qname
);
3278 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
3280 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3282 if (cg
) CheckCacheExpiration(m
, slot
, cg
);
3283 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
3284 m
->NewQuestions
= q
->next
;
3285 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3286 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3288 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3289 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
3290 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3291 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3292 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3293 // advanced it), that means the question was deleted, so we no longer need to worry about answering
3294 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3295 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
3297 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
3298 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3299 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3300 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3302 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3303 // This should be safe, because calling the client's question callback may cause the
3304 // question list to be modified, but should not ever cause the rrcache list to be modified.
3305 // If the client's question callback deletes the question, then m->CurrentQuestion will
3306 // be advanced, and we'll exit out of the loop
3307 m
->lock_rrcache
= 1;
3308 if (m
->CurrentQuestion
)
3309 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3310 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3311 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
3313 if (q
->NoAnswer
== NoAnswer_Fail
)
3315 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3316 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
3317 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
3318 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
3319 q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
3320 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
3322 if (m
->CurrentQuestion
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit
; }
3324 // If 'mDNSInterface_Any' question, see if we want to tell it about LocalOnly records
3325 if (q
->InterfaceID
== mDNSInterface_Any
)
3327 if (m
->CurrentRecord
)
3328 LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3329 m
->CurrentRecord
= m
->ResourceRecords
;
3330 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
3332 AuthRecord
*rr
= m
->CurrentRecord
;
3333 m
->CurrentRecord
= rr
->next
;
3334 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
3335 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3337 AnswerLocalQuestionWithLocalAuthRecord(m
, q
, rr
, mDNStrue
);
3338 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3341 m
->CurrentRecord
= mDNSNULL
;
3343 if (m
->CurrentQuestion
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit
; }
3345 // If we are not supposed to answer this question, generate a negative response.
3346 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
3347 if (QuerySuppressed(q
)) { q
->SuppressQuery
= mDNSfalse
; AnswerSuppressUnusableQuestion(m
, q
); q
->SuppressQuery
= mDNStrue
; }
3351 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
3352 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
3354 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
3355 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3356 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
3358 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
3359 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, CRDisplayString(m
, rr
), m
->timenow
, rr
->TimeRcvd
);
3360 continue; // Go to next one in loop
3363 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
3364 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
3365 if ((rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
3366 ShouldQueryImmediately
= mDNSfalse
;
3367 q
->CurrentAnswers
++;
3368 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
3369 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
3370 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
3371 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3373 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
3374 ShouldQueryImmediately
= mDNSfalse
;
3376 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
3377 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
3378 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
3380 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
3382 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3383 q
->ThisQInterval
= InitialQuestionInterval
;
3384 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3385 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
3387 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
3388 if (!m
->RandomQueryDelay
)
3389 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
3390 q
->LastQTime
+= m
->RandomQueryDelay
;
3394 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
3395 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
3396 // answers for this question until *after* its scheduled transmission time, in which case
3397 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
3398 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
3399 SetNextQueryTime(m
,q
);
3402 m
->CurrentQuestion
= mDNSNULL
;
3403 m
->lock_rrcache
= 0;
3406 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
3407 // appropriate answers, stopping if it reaches a NewLocalRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
3408 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
3410 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
3411 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
3413 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3415 if (m
->CurrentQuestion
)
3416 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3417 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3418 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
3420 if (m
->CurrentRecord
)
3421 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3422 m
->CurrentRecord
= m
->ResourceRecords
;
3424 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
3426 AuthRecord
*rr
= m
->CurrentRecord
;
3427 m
->CurrentRecord
= rr
->next
;
3428 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3430 AnswerLocalQuestionWithLocalAuthRecord(m
, q
, rr
, mDNStrue
);
3431 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3435 m
->CurrentQuestion
= mDNSNULL
;
3436 m
->CurrentRecord
= mDNSNULL
;
3439 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
3441 CacheEntity
*e
= mDNSNULL
;
3443 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
3444 m
->lock_rrcache
= 1;
3446 // If we have no free records, ask the client layer to give us some more memory
3447 if (!m
->rrcache_free
&& m
->MainCallback
)
3449 if (m
->rrcache_totalused
!= m
->rrcache_size
)
3450 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
3451 m
->rrcache_totalused
, m
->rrcache_size
);
3453 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
3454 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
3455 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
3456 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
3457 // and recycle them, instead of allocating more memory.
3458 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
3459 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
3460 m
->rrcache_size
, m
->rrcache_active
);
3463 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
3464 m
->MainCallback(m
, mStatus_GrowCache
);
3465 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3469 // If we still have no free records, recycle all the records we can.
3470 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
3471 if (!m
->rrcache_free
)
3473 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
3475 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3477 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
3480 CacheRecord
**rp
= &(*cp
)->members
;
3483 // Records that answer still-active questions are not candidates for recycling
3484 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
3485 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
3489 CacheRecord
*rr
= *rp
;
3490 *rp
= (*rp
)->next
; // Cut record from list
3491 ReleaseCacheRecord(m
, rr
);
3494 if ((*cp
)->rrcache_tail
!= rp
)
3495 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
3496 (*cp
)->rrcache_tail
= rp
;
3497 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
3498 else ReleaseCacheGroup(m
, cp
);
3501 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
3502 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
3505 if (m
->rrcache_free
) // If there are records in the free list, take one
3507 e
= m
->rrcache_free
;
3508 m
->rrcache_free
= e
->next
;
3509 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
3511 LogInfo("RR Cache now using %ld objects", m
->rrcache_totalused
);
3512 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
3513 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
3514 else m
->rrcache_report
+= 1000;
3516 mDNSPlatformMemZero(e
, sizeof(*e
));
3519 m
->lock_rrcache
= 0;
3524 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
3526 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
3529 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
3530 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
3532 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
3533 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
3534 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
3540 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
3542 mDNSu16 namelen
= DomainNameLength(rr
->name
);
3543 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
3544 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
3545 cg
->next
= m
->rrcache_hash
[slot
];
3546 cg
->namehash
= rr
->namehash
;
3547 cg
->members
= mDNSNULL
;
3548 cg
->rrcache_tail
= &cg
->members
;
3549 cg
->name
= (domainname
*)cg
->namestorage
;
3550 //LogMsg("GetCacheGroup: %-10s %d-byte cache name %##s",
3551 // (namelen > InlineCacheGroupNameSize) ? "Allocating" : "Inline", namelen, rr->name->c);
3552 if (namelen
> InlineCacheGroupNameSize
) cg
->name
= mDNSPlatformMemAllocate(namelen
);
3555 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
3556 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
3559 AssignDomainName(cg
->name
, rr
->name
);
3561 if (CacheGroupForRecord(m
, slot
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
3562 m
->rrcache_hash
[slot
] = cg
;
3563 if (CacheGroupForRecord(m
, slot
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
3568 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
3570 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
3571 LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
3572 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
3573 // a positive answer using an expired record (e.g. from an interface that has gone away).
3574 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
3575 // summary deletion without giving the proper callback to any questions that are monitoring it.
3576 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
3577 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
3578 rr
->UnansweredQueries
= MaxUnansweredQueries
;
3579 rr
->resrec
.rroriginalttl
= 0;
3580 SetNextCacheCheckTimeForRecord(m
, rr
);
3583 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
3586 mDNSPlatformLock(m
);
3589 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
3590 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
3593 if (m
->timenow
) time
= m
->timenow
;
3594 else time
= mDNS_TimeNow_NoLock(m
);
3595 mDNSPlatformUnlock(m
);
3599 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
3600 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
3601 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
3602 #define SetSPSProxyListChanged(X) do { \
3603 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
3604 m->SPSProxyListChanged = (X); } while(0)
3606 // Called from mDNS_Execute() to expire stale proxy records
3607 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
3609 m
->CurrentRecord
= list
;
3610 while (m
->CurrentRecord
)
3612 AuthRecord
*rr
= m
->CurrentRecord
;
3613 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
3615 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
3616 // so we need to cease proxying for *all* records we may have, expired or not.
3617 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
3619 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
3620 m
->NextScheduledSPS
= rr
->TimeExpire
;
3622 else // else proxy record expired, so remove it
3624 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
3625 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
3626 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
3627 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
3628 // Don't touch rr after this -- memory may have been free'd
3631 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
3632 // new records could have been added to the end of the list as a result of that call.
3633 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
3634 m
->CurrentRecord
= rr
->next
;
3638 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
3640 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
3642 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
3645 AuthRecord
*head
, *tail
;
3647 verbosedebugf("mDNS_Execute");
3649 if (m
->CurrentQuestion
)
3650 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
3651 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3653 if (m
->CurrentRecord
)
3654 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
3656 // 1. If we're past the probe suppression time, we can clear it
3657 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
3659 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
3660 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
3662 // 3. Purge our cache of stale old records
3663 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
3665 mDNSu32 slot
, numchecked
= 0;
3666 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
3667 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3669 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
3671 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
3672 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ 0x3FFFFFFF;
3675 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
3677 CheckCacheExpiration(m
, slot
, *cp
);
3678 if ((*cp
)->members
) cp
=&(*cp
)->next
;
3679 else ReleaseCacheGroup(m
, cp
);
3682 // Even if we didn't need to actually check this slot yet, still need to
3683 // factor its nextcheck time into our overall NextCacheCheck value
3684 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
3685 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
3687 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
3690 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
3692 m
->NextScheduledSPS
= m
->timenow
+ 0x3FFFFFFF;
3693 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
3694 CheckProxyRecords(m
, m
->ResourceRecords
);
3697 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
3699 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
3700 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0) m
->AnnounceOwner
= 0;
3702 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
3705 if (m
->SleepState
== SleepState_Transferring
)
3707 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
3708 BeginSleepProcessing(m
);
3712 // 4. See if we can answer any of our new local questions from the cache
3713 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
3715 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
3716 AnswerNewQuestion(m
);
3718 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
3720 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
3721 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
3722 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
3724 m
->LocalRemoveEvents
= mDNSfalse
;
3725 m
->CurrentRecord
= m
->ResourceRecords
;
3726 while (m
->CurrentRecord
)
3728 AuthRecord
*rr
= m
->CurrentRecord
;
3729 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3731 debugf("mDNS_Execute: Generating local RMV events for %s", ARDisplayString(m
, rr
));
3732 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
3733 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
);
3734 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
3736 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
3737 rr
->AnsweredLocalQ
= mDNSfalse
;
3740 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
3741 m
->CurrentRecord
= rr
->next
;
3744 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
3746 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
3747 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
3749 head
= tail
= mDNSNULL
;
3750 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
3752 AuthRecord
*rr
= m
->NewLocalRecords
;
3753 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
3754 if (LocalRecordReady(rr
))
3756 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
3757 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNStrue
);
3761 // If we have just one record that is not ready, we don't have to unlink and
3762 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
3763 // terminate and set the NewLocalRecords to rr.
3764 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
3765 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
3766 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
3772 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
3773 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
3774 // if this is the first record we are skipping, move to the end of the list.
3775 // if we have already skipped records before, append it at the end.
3776 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
3777 if (*p
) *p
= rr
->next
; // Cut this record from the list
3778 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
3781 while (*p
) p
=&(*p
)->next
;
3790 rr
->next
= mDNSNULL
;
3793 m
->NewLocalRecords
= head
;
3794 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
3796 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
3798 // 5. Some questions may have picked a new DNS server and the cache may answer these questions now.
3799 AnswerQuestionsForDNSServerChanges(m
);
3801 // 6. See what packets we need to send
3802 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
3803 DiscardDeregistrations(m
);
3804 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
3806 // If the platform code is ready, and we're not suppressing packet generation right now
3807 // then send our responses, probes, and questions.
3808 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
3809 // We send queries next, because there might be final-stage probes that complete their probing here, causing
3810 // them to advance to announcing state, and we want those to be included in any announcements we send out.
3811 // Finally, we send responses, including the previously mentioned records that just completed probing.
3812 m
->SuppressSending
= 0;
3814 // 7. Send Query packets. This may cause some probing records to advance to announcing state
3815 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
3816 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
3819 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
3820 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
3821 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
3822 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3823 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
3824 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3826 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
3828 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
3829 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
3830 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
3833 // 8. Send Response packets, including probing records just advanced to announcing state
3834 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
3835 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
3837 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
3838 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
3842 // Clear RandomDelay values, ready to pick a new different value next time
3843 m
->RandomQueryDelay
= 0;
3844 m
->RandomReconfirmDelay
= 0;
3846 #ifndef UNICAST_DISABLED
3847 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
3848 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
3849 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
3853 // Note about multi-threaded systems:
3854 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
3855 // performing mDNS API operations that change our next scheduled event time.
3857 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
3858 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
3859 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
3860 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
3861 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
3862 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
3863 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
3864 // without blocking. This avoids the race condition between the signal from the other thread arriving
3865 // just *before* or just *after* the main thread enters the blocking primitive.
3867 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
3868 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
3869 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
3870 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
3871 // by the time it gets to the timer callback function).
3873 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
3874 return(m
->NextScheduledEvent
);
3877 mDNSlocal
void SuspendLLQs(mDNS
*m
)
3880 for (q
= m
->Questions
; q
; q
= q
->next
)
3881 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
3882 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
3885 // ActivateUnicastQuery() is called from three places:
3886 // 1. When a new question is created
3887 // 2. On wake from sleep
3888 // 3. When the DNS configuration changes
3889 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
3890 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
3891 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
3893 // For now this AutoTunnel stuff is specific to Mac OS X.
3894 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
3895 #if APPLE_OSX_mDNSResponder
3896 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
3897 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
3898 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
3899 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
3900 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
3901 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
3903 if (RRTypeIsAddressType(question
->qtype
) && PrivateQuery(question
) &&
3904 !SameDomainLabel(question
->qname
.c
, (const mDNSu8
*)"\x0c_autotunnel6")&& question
->QuestionCallback
!= AutoTunnelCallback
)
3906 question
->NoAnswer
= NoAnswer_Suspended
;
3907 AddNewClientTunnel(m
, question
);
3910 #endif // APPLE_OSX_mDNSResponder
3912 if (!question
->DuplicateOf
)
3914 debugf("ActivateUnicastQuery: %##s %s%s%s",
3915 question
->qname
.c
, DNSTypeName(question
->qtype
), PrivateQuery(question
) ? " (Private)" : "", ScheduleImmediately
? " ScheduleImmediately" : "");
3916 question
->CNAMEReferrals
= 0;
3917 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
3918 if (question
->LongLived
)
3920 question
->state
= LLQ_InitialRequest
;
3921 question
->id
= zeroOpaque64
;
3922 question
->servPort
= zeroIPPort
;
3923 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
3925 if (ScheduleImmediately
)
3927 question
->ThisQInterval
= InitialQuestionInterval
;
3928 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
3929 SetNextQueryTime(m
, question
);
3934 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
3938 #ifndef UNICAST_DISABLED
3939 // Retrigger all our uDNS questions
3940 if (m
->CurrentQuestion
)
3941 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
3942 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3943 m
->CurrentQuestion
= m
->Questions
;
3944 while (m
->CurrentQuestion
)
3946 q
= m
->CurrentQuestion
;
3947 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3948 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
)) ActivateUnicastQuery(m
, q
, mDNStrue
);
3952 // Retrigger all our mDNS questions
3953 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
3954 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
3956 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
3957 q
->RequestUnicast
= 2; // Set to 2 because is decremented once *before* we check it
3958 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3959 q
->RecentAnswerPkts
= 0;
3960 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
3961 m
->NextScheduledQuery
= m
->timenow
;
3965 // ***************************************************************************
3966 #if COMPILER_LIKES_PRAGMA_MARK
3968 #pragma mark - Power Management (Sleep/Wake)
3971 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
3973 #ifndef IDLESLEEPCONTROL_DISABLED
3974 mDNSBool allowSleep
= mDNStrue
;
3976 if (m
->SystemSleepOnlyIfWakeOnLAN
)
3978 // Don't sleep if we are a proxy for any services
3979 if (m
->ProxyRecords
)
3981 allowSleep
= mDNSfalse
;
3982 LogInfo("Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
3985 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
3987 // Scan the list of active interfaces
3988 NetworkInterfaceInfo
*intf
;
3989 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
3991 if (intf
->McastTxRx
)
3993 // Disallow sleep if this interface doesn't support NetWake
3996 allowSleep
= mDNSfalse
;
3997 LogInfo("Sleep disabled because %s does not support NetWake", intf
->ifname
);
4001 // Disallow sleep if there is no sleep proxy server
4002 if (FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
) == mDNSNULL
)
4004 allowSleep
= mDNSfalse
;
4005 LogInfo("Sleep disabled because %s has no sleep proxy", intf
->ifname
);
4011 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
4014 // Call the platform code to enable/disable sleep
4015 mDNSPlatformSetAllowSleep(m
, allowSleep
);
4018 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*intf
, const mDNSOpaque16 id
)
4020 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
4021 const int sps
= intf
->NextSPSAttempt
/ 3;
4024 if (!intf
->SPSAddr
[sps
].type
)
4026 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
4027 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
4028 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
4029 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
4033 // Mark our mDNS records (not unicast records) for transfer to SPS
4034 if (mDNSOpaque16IsZero(id
))
4035 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4036 if (rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
4037 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
4038 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
4042 mDNSu8
*p
= m
->omsg
.data
;
4043 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
4044 // For now we follow that same logic for SPS registrations too.
4045 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
4046 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
4047 InitializeDNSMessage(&m
->omsg
.h
, mDNSOpaque16IsZero(id
) ? mDNS_NewMessageID(m
) : id
, UpdateReqFlags
);
4049 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4050 if (rr
->SendRNow
|| (!mDNSOpaque16IsZero(id
) && !AuthRecord_uDNS(rr
) && mDNSSameOpaque16(rr
->updateid
, id
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0))
4053 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
4054 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
4055 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
4056 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
4057 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
4059 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
4062 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, rr
));
4063 rr
->SendRNow
= mDNSNULL
;
4064 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
4065 rr
->LastAPTime
= m
->timenow
;
4066 rr
->updateid
= m
->omsg
.h
.id
;
4067 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
4068 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
4073 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
4077 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
4078 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
4079 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
4080 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
4081 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
4082 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
4083 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
4084 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]);
4085 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
4086 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
4088 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
4092 // Once we've attempted to register, we need to include our OWNER option in our packets when we re-awaken
4093 m
->SentSleepProxyRegistration
= mDNStrue
;
4095 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
4096 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
4097 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
4098 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSNULL
);
4099 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
4100 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv6
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
4102 LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
4103 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_A
;
4104 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
4111 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
4114 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
4117 // RetrySPSRegistrations is called from SendResponses, with the lock held
4118 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
4121 NetworkInterfaceInfo
*intf
;
4123 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
4124 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4125 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
4126 intf
->NextSPSAttemptTime
++;
4128 // Retry any record registrations that are due
4129 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4130 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
4131 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4132 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
)
4134 LogSPS("RetrySPSRegistrations: %s", ARDisplayString(m
, rr
));
4135 SendSPSRegistration(m
, intf
, rr
->updateid
);
4138 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
4139 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4140 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
4141 intf
->NextSPSAttempt
++;
4144 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
4146 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
4147 int sps
= (int)(question
- intf
->NetWakeResolve
);
4149 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
4151 if (!AddRecord
) return; // Don't care about REMOVE events
4152 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
4154 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
4156 if (answer
->rrtype
== kDNSType_SRV
)
4158 // 1. Got the SRV record; now look up the target host's IPv6 link-local address
4159 mDNS_StopQuery(m
, question
);
4160 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
4161 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
4162 question
->qtype
= kDNSType_AAAA
;
4163 mDNS_StartQuery(m
, question
);
4165 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
4167 // 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
4168 mDNS_StopQuery(m
, question
);
4169 question
->ThisQInterval
= -1;
4170 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
4171 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
4173 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
4176 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== 0)
4178 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
4179 mDNS_StopQuery(m
, question
);
4180 LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps
, question
->qname
.c
);
4181 question
->qtype
= kDNSType_A
;
4182 mDNS_StartQuery(m
, question
);
4184 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
4186 // 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
4187 mDNS_StopQuery(m
, question
);
4188 question
->ThisQInterval
= -1;
4189 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
4190 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
4192 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
4197 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
4200 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4201 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
))
4206 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
)
4209 m
->SleepState
= SleepState_Sleeping
;
4211 #ifndef UNICAST_DISABLED
4212 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
4213 #endif /* UNICAST_DISABLED */
4215 // Mark all the records we need to deregister and send them
4216 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4217 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
4218 rr
->ImmedAnswer
= mDNSInterfaceMark
;
4222 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
4223 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
4225 mDNSBool SendGoodbyes
= mDNStrue
;
4226 const CacheRecord
*sps
[3] = { mDNSNULL
};
4228 m
->NextScheduledSPRetry
= m
->timenow
;
4230 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
4231 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
4232 else // If we have at least one advertised service
4234 NetworkInterfaceInfo
*intf
;
4235 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4237 if (!intf
->NetWake
) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
4238 #if APPLE_OSX_mDNSResponder
4239 else if (ActivateLocalProxy(m
, intf
->ifname
) == mStatus_NoError
)
4241 SendGoodbyes
= mDNSfalse
;
4242 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
4243 // This will leave m->SleepState set to SleepState_Transferring,
4244 // which is okay because with no outstanding resolves, or updates in flight,
4245 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
4247 #endif // APPLE_OSX_mDNSResponder
4250 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
4251 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
4252 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
4256 SendGoodbyes
= mDNSfalse
;
4257 intf
->NextSPSAttempt
= 0;
4258 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
4259 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
4263 if (intf
->SPSAddr
[i
].type
)
4264 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
); *(long*)0 = 0; }
4265 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
4266 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
); *(long*)0 = 0; }
4268 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
4269 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
4270 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
4273 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
4274 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
4275 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
4276 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
4284 if (SendGoodbyes
) // If we didn't find even one Sleep Proxy
4286 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
4287 SendSleepGoodbyes(m
);
4291 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
4292 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
4293 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
4294 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
4298 LogSPS("%s (old state %d) at %ld", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
4300 if (sleep
&& !m
->SleepState
) // Going to sleep
4303 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
4306 mDNSu8 oldstate
= m
->SPSState
;
4307 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
4309 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
4310 mDNS_ReclaimLockAfterCallback();
4313 m
->SleepState
= SleepState_Transferring
;
4314 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
4316 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
4317 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
4318 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
4323 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
4324 BeginSleepProcessing(m
);
4327 #ifndef UNICAST_DISABLED
4331 // RemoveAutoTunnel6Record needs to be called outside the lock, as it grabs the lock also.
4332 #if APPLE_OSX_mDNSResponder
4333 RemoveAutoTunnel6Record(m
);
4335 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m
->SleepState
,
4336 m
->SleepState
== SleepState_Transferring
? "Transferring" :
4337 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
4339 else if (!sleep
) // Waking up
4344 NetworkInterfaceInfo
*intf
;
4347 // Reset SleepLimit back to 0 now that we're awake again.
4350 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
4351 if (m
->SleepState
!= SleepState_Awake
)
4353 m
->SleepState
= SleepState_Awake
;
4355 if (m
->SentSleepProxyRegistration
) // Include OWNER option in packets for 60 seconds after waking
4357 m
->SentSleepProxyRegistration
= mDNSfalse
;
4358 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
4360 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
4361 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
4362 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
4363 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
4364 m
->DelaySleep
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 16);
4367 if (m
->SPSState
== 3)
4370 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
);
4373 // In case we gave up waiting and went to sleep before we got an ack from the Sleep Proxy,
4374 // on wake we go through our record list and clear updateid back to zero
4375 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) rr
->updateid
= zeroID
;
4377 // ... and the same for NextSPSAttempt
4378 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
4380 // Restart unicast and multicast queries
4381 mDNSCoreRestartQueries(m
);
4383 // and reactivtate service registrations
4384 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
4385 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
4387 // 2. Re-validate our cache records
4388 FORALL_CACHERECORDS(slot
, cg
, cr
)
4389 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
4391 // 3. Retrigger probing and announcing for all our authoritative records
4392 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4393 if (AuthRecord_uDNS(rr
))
4395 ActivateUnicastRegistration(m
, rr
);
4399 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
4400 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
4401 rr
->AnnounceCount
= InitialAnnounceCount
;
4402 rr
->SendNSECNow
= mDNSNULL
;
4403 InitializeLastAPTime(m
, rr
);
4406 // 4. Refresh NAT mappings
4407 // We don't want to have to assume that all hardware can necessarily keep accurate
4408 // track of passage of time while asleep, so on wake we refresh our NAT mappings
4409 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
4410 // When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
4411 // mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
4412 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
4413 m
->retryGetAddr
= m
->timenow
+ mDNSPlatformOneSecond
* 5;
4414 LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m
->retryGetAddr
- m
->timenow
, m
->timenow
);
4415 RecreateNATMappings(m
);
4420 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
4424 NetworkInterfaceInfo
*intf
;
4428 if (m
->DelaySleep
) goto notready
;
4430 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
4431 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
4433 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
4435 // See if we might need to retransmit any lost Sleep Proxy Registrations
4436 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4437 if (intf
->NextSPSAttempt
>= 0)
4439 if (now
- intf
->NextSPSAttemptTime
>= 0)
4441 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
4442 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
4443 SendSPSRegistration(m
, intf
, zeroID
);
4444 // Don't need to "goto notready" here, because if we do still have record registrations
4445 // that have not been acknowledged yet, we'll catch that in the record list scan below.
4448 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
4449 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
4452 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
4453 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4455 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
4456 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
4458 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
4459 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
4464 // Scan list of registered records
4465 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4466 if (!AuthRecord_uDNS(rr
))
4467 if (!mDNSOpaque16IsZero(rr
->updateid
))
4468 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS Update ID %d %s", mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto spsnotready
; }
4470 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
4471 for (q
= m
->Questions
; q
; q
= q
->next
)
4472 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
4474 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4478 // Scan list of registered records
4479 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4480 if (AuthRecord_uDNS(rr
))
4482 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
4483 { LogSPS("mDNSCoreReadyForSleep: waiting for Record Update ID %d %s", mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto notready
; }
4484 #if APPLE_OSX_mDNSResponder
4485 if (!RecordReadyForSleep(m
, rr
)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m
, rr
)); goto notready
; }
4494 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
4495 // and allow up to ten seconds more to complete wide-area deregistration instead
4496 if (now
- m
->SleepLimit
>= 0)
4498 LogMsg("Failed to register with SPS, now sending goodbyes");
4500 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4501 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
4503 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
4504 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
4505 mDNS_DeactivateNetWake_internal(m
, intf
);
4508 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
4509 if (!AuthRecord_uDNS(rr
))
4510 if (!mDNSOpaque16IsZero(rr
->updateid
))
4512 LogSPS("ReadyForSleep clearing updateid for %s", ARDisplayString(m
, rr
));
4513 rr
->updateid
= zeroID
;
4516 // We'd really like to allow up to ten seconds more here,
4517 // but if we don't respond to the sleep notification within 30 seconds
4518 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
4519 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
4520 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
4521 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
4522 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
4524 SendSleepGoodbyes(m
);
4532 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
)
4536 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
4537 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
4538 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
4539 // and if that happens we don't want to just give up and go back to sleep and never try again.
4540 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
4542 NATTraversalInfo
*nat
;
4543 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
4544 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
4546 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
4547 if (e
- t
> 0) e
= t
;
4548 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
4549 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
4550 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
4551 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
4552 nat
->retryInterval
/ mDNSPlatformOneSecond
,
4553 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
4554 (t
- now
) / mDNSPlatformOneSecond
);
4557 // This loop checks both the time we need to renew wide-area registrations,
4558 // and the time we need to renew Sleep Proxy registrations
4559 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
4560 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
4562 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
4563 if (e
- t
> 0) e
= t
;
4564 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
4565 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4566 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4567 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
4568 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
4574 // ***************************************************************************
4575 #if COMPILER_LIKES_PRAGMA_MARK
4577 #pragma mark - Packet Reception Functions
4580 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
4582 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
4583 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
4585 mDNSu8
*responseptr
= response
->data
;
4586 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
4587 const mDNSu8
*ptr
= query
->data
;
4589 mDNSu32 maxttl
= 0x70000000;
4592 // Initialize the response fields so we can answer the questions
4593 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
4596 // *** 1. Write out the list of questions we are actually going to answer with this packet
4600 maxttl
= kStaticCacheTTL
;
4601 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4604 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
4605 if (!ptr
) return(mDNSNULL
);
4607 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
4609 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
4610 { // then put the question in the question section
4611 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
4612 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
4613 break; // break out of the ResponseRecords loop, and go on to the next question
4618 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
4622 // *** 2. Write Answers
4624 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4625 if (rr
->NR_AnswerTo
)
4627 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
4628 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
4629 if (p
) responseptr
= p
;
4630 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
4634 // *** 3. Write Additionals
4636 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
4637 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
4639 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
4640 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
4641 if (p
) responseptr
= p
;
4642 else debugf("GenerateUnicastResponse: No more space for additionals");
4645 return(responseptr
);
4648 // AuthRecord *our is our Resource Record
4649 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
4650 // Returns 0 if there is no conflict
4651 // Returns +1 if there was a conflict and we won
4652 // Returns -1 if there was a conflict and we lost and have to rename
4653 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
4655 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
4656 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
4657 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
4658 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
4660 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
4661 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
4662 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
4663 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
4665 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
4666 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
4667 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
4668 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
4670 LogMsg("CompareRData ERROR: Invalid state");
4674 // See if we have an authoritative record that's identical to this packet record,
4675 // whose canonical DependentOn record is the specified master record.
4676 // The DependentOn pointer is typically used for the TXT record of service registrations
4677 // It indicates that there is no inherent conflict detection for the TXT record
4678 // -- it depends on the SRV record to resolve name conflicts
4679 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
4680 // pointer chain (if any) to make sure we reach the canonical DependentOn record
4681 // If the record has no DependentOn, then just return that record's pointer
4682 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4683 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
4685 const AuthRecord
*r1
;
4686 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
4688 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
4690 const AuthRecord
*r2
= r1
;
4691 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
4692 if (r2
== master
) return(mDNStrue
);
4695 for (r1
= m
->DuplicateRecords
; 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
);
4707 // Find the canonical RRSet pointer for this RR received in a packet.
4708 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
4709 // pointers (if any) to make sure we return the canonical member of this name/type/class
4710 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
4711 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
4713 const AuthRecord
*rr
;
4714 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
4716 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
4718 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
4725 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
4726 // as one of our records (our) but different rdata.
4727 // 1. If our record is not a type that's supposed to be unique, we don't care.
4728 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
4729 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
4730 // points to our record, ignore this conflict (e.g. the packet record matches one of our
4731 // TXT records, and that record is marked as dependent on 'our', its SRV record).
4732 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
4733 // are members of the same RRSet, then this is not a conflict.
4734 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
4736 // If not supposed to be unique, not a conflict
4737 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
4739 // If a dependent record, not a conflict
4740 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
4743 // If the pktrr matches a member of ourset, not a conflict
4744 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
4745 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
4746 if (pktset
== ourset
) return(mDNSfalse
);
4748 // For records we're proxying, where we don't know the full
4749 // relationship between the records, having any matching record
4750 // in our AuthRecords list is sufficient evidence of non-conflict
4751 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
4754 // Okay, this is a conflict
4758 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
4759 // the record list and/or question list.
4760 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4761 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4762 DNSQuestion
*q
, AuthRecord
*our
)
4765 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
4766 mDNSBool FoundUpdate
= mDNSfalse
;
4768 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
4770 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
4772 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
4774 FoundUpdate
= mDNStrue
;
4775 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
4777 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
4778 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
4779 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
4782 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
4783 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
4784 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
4786 // 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.
4787 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
4788 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
4791 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
4792 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
4793 our
->AnnounceCount
= InitialAnnounceCount
;
4794 InitializeLastAPTime(m
, our
);
4801 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
4802 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
4806 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4809 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
4811 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4814 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
4816 mDNSu32 slot
= HashSlot(pktrr
->name
);
4817 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, pktrr
);
4820 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4822 match
= !pktrr
->InterfaceID
? pktrr
->rDNSServer
== rr
->resrec
.rDNSServer
: pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
;
4823 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
4828 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
4829 // to check our lists and discard any stale duplicates of this record we already have
4830 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
4832 if (m
->CurrentRecord
)
4833 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4834 m
->CurrentRecord
= thelist
;
4835 while (m
->CurrentRecord
)
4837 AuthRecord
*const rr
= m
->CurrentRecord
;
4838 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
4839 if (IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
4841 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
4842 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
4843 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
4844 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
4845 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
4846 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
4848 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4849 // new records could have been added to the end of the list as a result of that call.
4850 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
4851 m
->CurrentRecord
= rr
->next
;
4855 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
4856 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
4858 if (m
->CurrentRecord
)
4859 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4860 m
->CurrentRecord
= thelist
;
4861 while (m
->CurrentRecord
)
4863 AuthRecord
*const rr
= m
->CurrentRecord
;
4864 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
4865 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
4867 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
4869 // We don't do this here because we know that the host is waking up at this point, so we don't send
4870 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
4871 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
4872 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
4873 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
4874 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
4875 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
4878 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
4879 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
4880 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
4881 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
4882 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
4883 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
4884 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
4885 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
4887 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4888 // new records could have been added to the end of the list as a result of that call.
4889 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
4890 m
->CurrentRecord
= rr
->next
;
4894 // ProcessQuery examines a received query to see if we have any answers to give
4895 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
4896 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
4897 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
4899 mDNSBool FromLocalSubnet
= srcaddr
&& mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
4900 AuthRecord
*ResponseRecords
= mDNSNULL
;
4901 AuthRecord
**nrp
= &ResponseRecords
;
4902 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
4903 CacheRecord
**eap
= &ExpectedAnswers
;
4904 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
4905 DNSQuestion
**dqp
= &DupQuestions
;
4906 mDNSs32 delayresponse
= 0;
4907 mDNSBool SendLegacyResponse
= mDNSfalse
;
4909 mDNSu8
*responseptr
= mDNSNULL
;
4914 // *** 1. Look in Additional Section for an OPT record
4916 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
4919 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
4920 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
4922 const rdataOPT
*opt
;
4923 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
4924 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
4925 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
4926 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
4927 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
4929 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
4930 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
4933 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4937 // *** 2. Parse Question Section and mark potential answers
4940 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
4942 mDNSBool QuestionNeedsMulticastResponse
;
4943 int NumAnswersForThisQuestion
= 0;
4944 AuthRecord
*NSECAnswer
= mDNSNULL
;
4945 DNSQuestion pktq
, *q
;
4946 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
4947 if (!ptr
) goto exit
;
4949 // The only queries that *need* a multicast response are:
4950 // * Queries sent via multicast
4952 // * that don't have the kDNSQClass_UnicastResponse bit set
4953 // These queries need multicast responses because other clients will:
4954 // * suppress their own identical questions when they see these questions, and
4955 // * expire their cache records if they don't see the expected responses
4956 // For other queries, we may still choose to send the occasional multicast response anyway,
4957 // to keep our neighbours caches warm, and for ongoing conflict detection.
4958 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
4959 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
4960 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
4962 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
4963 // can result in user callbacks which may change the record list and/or question list.
4964 // Also note: we just mark potential answer records here, without trying to build the
4965 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
4966 // from that list while we're in the middle of trying to build it.
4967 if (m
->CurrentRecord
)
4968 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4969 m
->CurrentRecord
= m
->ResourceRecords
;
4970 while (m
->CurrentRecord
)
4972 rr
= m
->CurrentRecord
;
4973 m
->CurrentRecord
= rr
->next
;
4974 if (AnyTypeRecordAnswersQuestion(&rr
->resrec
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
4976 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
4978 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
4979 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
4980 else if (ResourceRecordIsValidAnswer(rr
))
4982 NumAnswersForThisQuestion
++;
4983 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
4984 // unicast answer back to the source, because timeliness in answering probes is important.
4987 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
4988 // NR_AnswerTo == (mDNSu8*)~1 means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
4989 // NR_AnswerTo == (mDNSu8*)~0 means "definitely answer via multicast" (can't downgrade to unicast later)
4990 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
4991 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
4992 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
4993 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
4995 // We only mark this question for sending if it is at least one second since the last time we multicast it
4996 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
4997 // This is to guard against the case where someone blasts us with queries as fast as they can.
4998 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
4999 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
5000 rr
->NR_AnswerTo
= (mDNSu8
*)~0;
5002 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: (mDNSu8
*)~1;
5005 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
5007 // If we don't have any answers for this question, but we do own another record with the same name,
5008 // then we'll want to mark it to generate an NSEC record on this interface
5009 if (!NSECAnswer
) NSECAnswer
= rr
;
5014 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
5016 NumAnswersForThisQuestion
++;
5017 NSECAnswer
->SendNSECNow
= InterfaceID
;
5018 m
->NextScheduledResponse
= m
->timenow
;
5021 // If we couldn't answer this question, someone else might be able to,
5022 // so use random delay on response to reduce collisions
5023 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
5025 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5026 if (QuestionNeedsMulticastResponse
)
5028 // We only do the following accelerated cache expiration and duplicate question suppression processing
5029 // for non-truncated multicast queries with multicast responses.
5030 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
5031 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
5032 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
5033 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5036 const mDNSu32 slot
= HashSlot(&pktq
.qname
);
5037 CacheGroup
*cg
= CacheGroupForName(m
, slot
, pktq
.qnamehash
, &pktq
.qname
);
5040 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
5041 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
5042 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5043 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5045 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
5046 if (SameNameRecordAnswersQuestion(&cr
->resrec
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
5047 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
5050 eap
= &cr
->NextInKAList
;
5051 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5052 if (cr
->MPUnansweredQ
== 0 || m
->timenow
- cr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
5054 // Although MPUnansweredQ is only really used for multi-packet query processing,
5055 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
5056 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
5057 cr
->MPUnansweredQ
++;
5058 cr
->MPLastUnansweredQT
= m
->timenow
;
5059 cr
->MPExpectingKA
= mDNStrue
;
5064 // Check if this question is the same as any of mine.
5065 // We only do this for non-truncated queries. Right now it would be too complicated to try
5066 // to keep track of duplicate suppression state between multiple packets, especially when we
5067 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
5068 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5069 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5071 for (q
= m
->Questions
; q
; q
=q
->next
)
5072 if (!q
->Target
.type
&& ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
5073 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
5074 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
5075 if (q
->qtype
== pktq
.qtype
&&
5076 q
->qclass
== pktq
.qclass
&&
5077 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
5078 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
5083 // *** 3. Now we can safely build the list of marked answers
5085 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
5086 if (rr
->NR_AnswerTo
) // If we marked the record...
5087 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
5090 // *** 4. Add additional records
5092 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
5095 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
5097 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
5099 // Get the record...
5100 CacheRecord
*ourcacherr
;
5101 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
5102 if (!ptr
) goto exit
;
5103 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
5105 // See if this Known-Answer suppresses any of our currently planned answers
5106 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5107 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
5108 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5110 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
5111 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
5113 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
5114 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
5116 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5118 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
5120 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5122 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
5124 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
5126 rr
->ImmedAnswer
= mDNSNULL
;
5127 rr
->ImmedUnicast
= mDNSfalse
;
5128 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5129 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
5135 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
5137 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5138 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
5139 // 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).
5140 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
5142 ourcacherr
->MPUnansweredKA
++;
5143 ourcacherr
->MPExpectingKA
= mDNSfalse
;
5147 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
5148 // any records that are suppressed by the Known Answer list in this packet.
5149 eap
= &ExpectedAnswers
;
5152 CacheRecord
*cr
= *eap
;
5153 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
5154 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
5155 else eap
= &cr
->NextInKAList
;
5158 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
5161 dqp
= &DupQuestions
;
5164 DNSQuestion
*q
= *dqp
;
5165 if (ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
5166 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
5167 else dqp
= &q
->NextInDQList
;
5171 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
5175 // *** 6. Cancel any additionals that were added because of now-deleted records
5177 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5178 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
5179 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
5182 // *** 7. Mark the send flags on the records we plan to send
5184 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5186 if (rr
->NR_AnswerTo
)
5188 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
5189 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
5191 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
5192 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0)
5194 SendMulticastResponse
= mDNStrue
;
5195 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
5196 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
5197 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
5198 if (rr
->NR_AnswerTo
== (mDNSu8
*)~1) rr
->NR_AnswerTo
= (mDNSu8
*)~0;
5201 // If the client insists on a multicast response, then we'd better send one
5202 if (rr
->NR_AnswerTo
== (mDNSu8
*)~0) SendMulticastResponse
= mDNStrue
;
5203 else if (rr
->NR_AnswerTo
== (mDNSu8
*)~1) SendUnicastResponse
= mDNStrue
;
5204 else if (rr
->NR_AnswerTo
) SendLegacyResponse
= mDNStrue
;
5206 if (SendMulticastResponse
|| SendUnicastResponse
)
5208 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5209 rr
->ImmedAnswerMarkTime
= m
->timenow
;
5211 m
->NextScheduledResponse
= m
->timenow
;
5212 // If we're already planning to send this on another interface, just send it on all interfaces
5213 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
5214 rr
->ImmedAnswer
= mDNSInterfaceMark
;
5217 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
5218 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
5219 if (srcaddr
->type
== mDNSAddrType_IPv4
)
5221 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
5222 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
5224 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
5226 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
5227 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
5231 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
5232 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
5233 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
5234 // else, for a simple unique record reply, we can reply immediately; no need for delay
5235 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
5236 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
5238 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== (mDNSu8
*)~0)
5240 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
5241 // If two clients on different interfaces do queries that invoke the same optional additional answer,
5242 // then the earlier client is out of luck
5243 rr
->ImmedAdditional
= InterfaceID
;
5244 // No need to set m->NextScheduledResponse here
5245 // We'll send these additional records when we send them, or not, as the case may be
5250 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
5252 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
5254 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5255 mDNSs32 oldss
= m
->SuppressSending
;
5256 if (oldss
&& delayresponse
)
5257 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
5259 // Pick a random delay:
5260 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
5261 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
5262 // This is an integer value, with resolution determined by the platform clock rate.
5263 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
5264 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
5265 // The +49 before dividing is to ensure we round up, not down, to ensure that even
5266 // on platforms where the native clock rate is less than fifty ticks per second,
5267 // we still guarantee that the final calculated delay is at least one platform tick.
5268 // We want to make sure we don't ever allow the delay to be zero ticks,
5269 // because if that happens we'll fail the Bonjour Conformance Test.
5270 // Our final computed delay is 20-120ms for normal delayed replies,
5271 // or 400-500ms in the case of multi-packet known-answer lists.
5272 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
5273 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
5274 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
5275 if (oldss
&& delayresponse
)
5276 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
5281 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
5283 if (SendLegacyResponse
)
5284 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
5287 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
5290 // *** 10. Finally, clear our link chains ready for use next time
5292 while (ResponseRecords
)
5294 rr
= ResponseRecords
;
5295 ResponseRecords
= rr
->NextResponse
;
5296 rr
->NextResponse
= mDNSNULL
;
5297 rr
->NR_AnswerTo
= mDNSNULL
;
5298 rr
->NR_AdditionalTo
= mDNSNULL
;
5301 while (ExpectedAnswers
)
5303 CacheRecord
*cr
= ExpectedAnswers
;
5304 ExpectedAnswers
= cr
->NextInKAList
;
5305 cr
->NextInKAList
= mDNSNULL
;
5307 // For non-truncated queries, we can definitively say that we should expect
5308 // to be seeing a response for any records still left in the ExpectedAnswers list
5309 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5310 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
)
5312 cr
->UnansweredQueries
++;
5313 cr
->LastUnansweredTime
= m
->timenow
;
5314 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5315 if (cr
->UnansweredQueries
> 1)
5316 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
5317 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
5319 SetNextCacheCheckTimeForRecord(m
, cr
);
5322 // If we've seen multiple unanswered queries for this record,
5323 // then mark it to expire in five seconds if we don't get a response by then.
5324 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
5326 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5327 // Only show debugging message if this record was not about to expire anyway
5328 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5329 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5330 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
5332 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
5334 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5335 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
5336 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
5337 // possible packet loss of up to 20% of the additional KA packets.)
5338 else if (cr
->MPUnansweredQ
* 4 > cr
->MPUnansweredKA
* 5 + 8)
5340 // We want to do this conservatively.
5341 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
5342 // then we don't want them to all hit the network simultaneously with their final expiration queries.
5343 // By setting the record to expire in four minutes, we achieve two things:
5344 // (a) the 90-95% final expiration queries will be less bunched together
5345 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
5346 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(cr
) - m
->timenow
) / 4;
5347 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
5348 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
5350 // Only show debugging message if this record was not about to expire anyway
5351 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
5352 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
5353 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
5355 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
5356 cr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
5357 cr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
5358 cr
->MPUnansweredKA
= 0;
5359 cr
->MPExpectingKA
= mDNSfalse
;
5361 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
5362 remain
= kDefaultReconfirmTimeForNoAnswer
;
5363 mDNS_Reconfirm_internal(m
, cr
, remain
);
5368 while (DupQuestions
)
5370 DNSQuestion
*q
= DupQuestions
;
5371 DupQuestions
= q
->NextInDQList
;
5372 q
->NextInDQList
= mDNSNULL
;
5373 i
= RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
5374 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
5375 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6", i
);
5378 return(responseptr
);
5381 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
5382 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5383 const mDNSInterfaceID InterfaceID
)
5385 mDNSu8
*responseend
= mDNSNULL
;
5386 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
5387 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
5389 if (!InterfaceID
&& dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
))
5391 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
5392 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
5393 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
5394 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5395 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5396 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5397 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
5401 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
5402 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
5403 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
5404 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
5405 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
5406 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5407 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
5409 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
5410 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
5412 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
5414 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
5415 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
5416 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
5417 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
5418 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
5419 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
);
5424 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
5428 (void)srcaddr
; // Unused
5429 for (s
= m
->DNSServers
; s
; s
= s
->next
)
5430 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
5435 struct UDPSocket_struct
5437 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
5440 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
, const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
)
5443 for (q
= m
->Questions
; q
; q
=q
->next
)
5445 if (!tcp
&& !q
->LocalSocket
) continue;
5446 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
5447 mDNSSameOpaque16(q
->TargetQID
, id
) &&
5448 q
->qtype
== question
->qtype
&&
5449 q
->qclass
== question
->qclass
&&
5450 q
->qnamehash
== question
->qnamehash
&&
5451 SameDomainName(&q
->qname
, &question
->qname
))
5457 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
5458 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
5464 // Unicast records have zero as InterfaceID
5465 if (rr
->resrec
.InterfaceID
) return mDNSNULL
;
5467 for (q
= m
->Questions
; q
; q
=q
->next
)
5469 if (!q
->DuplicateOf
&& UnicastResourceRecordAnswersQuestion(&rr
->resrec
, q
))
5471 if (!mDNSOpaque16IsZero(q
->TargetQID
))
5473 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
5475 if (mDNSSameOpaque16(q
->TargetQID
, id
))
5480 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
5484 srcp
= q
->tcpSrcPort
;
5486 if (mDNSSameIPPort(srcp
, port
)) return(q
);
5488 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
5489 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
5490 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
5491 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
5492 q
->qname
.c
, DNSTypeName(q
->qtype
), &q
->Target
, mDNSVal16(srcp
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
5498 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
5506 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
5507 // Currently this applies only to rdata types containing more than one domainname,
5508 // or types where the domainname is not the last item in the structure.
5509 // In addition, NSEC currently requires less space for in-memory storage than its in-packet representation.
5510 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
5514 case kDNSType_SOA
: return sizeof(rdataSOA
);
5515 case kDNSType_RP
: return sizeof(rdataRP
);
5516 case kDNSType_PX
: return sizeof(rdataPX
);
5517 case kDNSType_NSEC
:return sizeof(rdataNSEC
);
5518 default: return rr
->rdlength
;
5522 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
)
5524 CacheRecord
*rr
= mDNSNULL
;
5525 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
5527 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
5529 //if (RDLength > InlineCacheRDSize)
5530 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
5532 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
5533 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
5534 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
5537 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
5538 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
5539 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
5540 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
5541 rr
->DelayDelivery
= delay
;
5543 // If this is an oversized record with external storage allocated, copy rdata to external storage
5544 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
5545 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
5546 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
5547 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
5548 if (RDLength
> InlineCacheRDSize
)
5549 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
5551 rr
->next
= mDNSNULL
; // Clear 'next' pointer
5552 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
5553 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
5555 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
5560 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
5562 rr
->TimeRcvd
= m
->timenow
;
5563 rr
->resrec
.rroriginalttl
= ttl
;
5564 rr
->UnansweredQueries
= 0;
5565 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
5566 rr
->MPUnansweredQ
= 0;
5567 rr
->MPUnansweredKA
= 0;
5568 rr
->MPExpectingKA
= mDNSfalse
;
5570 SetNextCacheCheckTimeForRecord(m
, rr
);
5573 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
5576 const mDNSu32 slot
= HashSlot(&q
->qname
);
5577 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
5578 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5579 if (rr
->CRActiveQuestion
== q
)
5581 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
5582 RefreshCacheRecord(m
, rr
, lease
);
5586 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
5588 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
5589 else if (LLQType
== uDNS_LLQ_Events
)
5591 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
5592 if (ttl
== 0xFFFFFFFF) ttl
= 0;
5593 else ttl
= kLLQ_DefLease
;
5595 else // else not LLQ (standard uDNS response)
5597 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
5598 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
5599 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
5601 // Adjustment factor to avoid race condition:
5602 // 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.
5603 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
5604 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
5605 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
5606 // We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
5607 // the cached copy at our local caching server will already have expired, so the server will be forced
5608 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
5611 // For mDNS, TTL zero means "delete this record"
5612 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
5613 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
5614 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
5615 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
5616 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
5617 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
5618 // (with the current code) result in the server having even less than three seconds to respond
5619 // before we deleted the record and reported a "remove" event to any active questions.
5620 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
5621 // then things really break (e.g. we end up making a negative cache entry).
5622 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
5623 if (ttl
< 15) ttl
= 15;
5629 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
5630 // the record list and/or question list.
5631 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
5632 // InterfaceID non-NULL tells us the interface this multicast response was received on
5633 // InterfaceID NULL tells us this was a unicast response
5634 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
5635 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
5636 const DNSMessage
*const response
, const mDNSu8
*end
,
5637 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
5638 const mDNSInterfaceID InterfaceID
)
5641 mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
5642 mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
5643 DNSQuestion
*llqMatch
= mDNSNULL
;
5644 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
5646 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
5647 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
5648 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
5649 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
5650 CacheRecord
**cfp
= &CacheFlushRecords
;
5652 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
5653 // to guard against spoof responses, then the only credible protection against that is cryptographic
5654 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
5655 int firstauthority
= response
->h
.numAnswers
;
5656 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
5657 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
5658 const mDNSu8
*ptr
= response
->data
;
5659 DNSServer
*uDNSServer
= mDNSNULL
;
5661 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
5662 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
5663 srcaddr
, dstaddr
, InterfaceID
,
5664 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
5665 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5666 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5667 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
5669 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
5670 // When a DNS client receives a reply with TC
5671 // set, it should ignore that response, and query again, using a
5672 // mechanism, such as a TCP connection, that will permit larger replies.
5673 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
5674 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
5675 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
5676 // <rdar://problem/6690034> Can't bind to Active Directory
5677 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
5678 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
5679 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
5680 // and not even do the TCP query.
5681 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
5682 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
)) return;
5684 if (LLQType
== uDNS_LLQ_Ignore
) return;
5686 // 1. We ignore questions (if any) in mDNS response packets
5687 // 2. If this is an LLQ response, we handle it much the same
5688 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
5689 // answer as being the authoritative complete RRSet, and respond by deleting all other
5690 // matching cache records that don't appear in this packet.
5691 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
5692 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
|| (response
->h
.flags
.b
[0] & kDNSFlag0_TC
))
5693 ptr
= LocateAnswers(response
, end
);
5694 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
5695 // in this response packet are immediately deemed to be invalid.
5698 mDNSu8 rcode
= (mDNSu8
)(response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
5699 mDNSBool failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
5700 mDNSBool returnEarly
= mDNSfalse
;
5701 // We could possibly combine this with the similar loop at the end of this function --
5702 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
5703 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
5704 // which it was received (or refreshed), and then at the end if we find any cache records which
5705 // answer questions in this packet's question section, but which aren't tagged with this packet's
5706 // packet number, then we deduce they are old and delete them
5707 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
5709 DNSQuestion q
, *qptr
= mDNSNULL
;
5710 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
5711 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
5716 const mDNSu32 slot
= HashSlot(&q
.qname
);
5717 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
5718 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5719 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
5721 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
5722 rr
->resrec
.InterfaceID
, CRDisplayString(m
, rr
));
5723 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
5724 rr
->TimeRcvd
= m
->timenow
- TicksTTL(rr
) - 1;
5725 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5732 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr
->qDNSServer
, rcode
, q
.qname
.c
, DNSTypeName(q
.qtype
));
5733 PenalizeDNSServer(m
, qptr
);
5735 returnEarly
= mDNStrue
;
5741 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
5742 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
5743 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
5744 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
5745 // not goto exit because we won't have any CacheFlushRecords and we do not want to
5746 // generate negative cache entries (we want to query the next server)
5751 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
5753 // All responses sent via LL multicast are acceptable for caching
5754 // All responses received over our outbound TCP connections are acceptable for caching
5755 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
;
5756 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
5757 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
5759 const mDNSu8 RecordType
=
5760 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
5761 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
5762 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
5763 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
5764 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
) { m
->rec
.r
.resrec
.RecordType
= 0; continue; }
5766 // Don't want to cache OPT or TSIG pseudo-RRs
5767 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
) { m
->rec
.r
.resrec
.RecordType
= 0; continue; }
5768 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
5770 const rdataOPT
*opt
;
5771 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
5772 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
5773 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
5774 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
5775 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
5777 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
5778 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
5780 m
->rec
.r
.resrec
.RecordType
= 0;
5784 // if a CNAME record points to itself, then don't add it to the cache
5785 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
5787 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
5788 m
->rec
.r
.resrec
.RecordType
= 0;
5792 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
5793 // In the case of active LLQs, we'll get remove events when the records actually do go away
5794 // In the case of polling LLQs, we assume the record remains valid until the next poll
5795 if (!mDNSOpaque16IsZero(response
->h
.id
))
5796 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
5798 // If response was not sent via LL multicast,
5799 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
5804 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
5805 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
5806 // queries to get ADD/RMV events. To lookup the question, we can't use
5807 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
5808 // has already matched the question using the 64 bit Id in the packet and we use that here.
5810 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
5812 else if (!AcceptableResponse
|| !dstaddr
)
5814 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
5815 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
5816 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
5819 DNSQuestion
*q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
5821 // Intialize the DNS server on the resource record which will now filter what questions we answer with
5824 // We could potentially lookup the DNS server based on the source address, but that may not work always
5825 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
5826 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
5827 // on the "id" and "source port", then this response answers the question and assume the response
5828 // came from the same DNS server that we sent the query to.
5832 AcceptableResponse
= mDNStrue
;
5835 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5836 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
5841 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
5842 // the question. The code below does that. So, make this record unacceptable for now
5845 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
5846 AcceptableResponse
= mDNSfalse
;
5852 // 1. Check that this packet resource record does not conflict with any of ours
5853 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
5855 if (m
->CurrentRecord
)
5856 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
5857 m
->CurrentRecord
= m
->ResourceRecords
;
5858 while (m
->CurrentRecord
)
5860 AuthRecord
*rr
= m
->CurrentRecord
;
5861 m
->CurrentRecord
= rr
->next
;
5862 // We accept all multicast responses, and unicast responses resulting from queries we issued
5863 // For other unicast responses, this code accepts them only for responses with an
5864 // (apparently) local source address that pertain to a record of our own that's in probing state
5865 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
5867 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
5869 // ... check to see if type and rdata are identical
5870 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
5872 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
5873 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
5875 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
5876 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
5880 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
5881 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5884 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
5885 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
5887 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
5888 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
-> resrec
.rdatahash
, ARDisplayString(m
, rr
));
5890 // If this record is marked DependentOn another record for conflict detection purposes,
5891 // then *that* record has to be bumped back to probing state to resolve the conflict
5892 if (rr
->DependentOn
)
5894 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
5895 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
-> resrec
.rdatahash
, ARDisplayString(m
, rr
));
5898 // If we've just whacked this record's ProbeCount, don't need to do it again
5899 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
5900 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
5901 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
5902 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
5905 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
5906 // If we'd previously verified this record, put it back to probing state and try again
5907 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
5909 LogMsg("mDNSCoreReceiveResponse: Reseting to Probing: %s", ARDisplayString(m
, rr
));
5910 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5911 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
5912 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
5913 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
5914 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
5915 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
5916 rr
->AnnounceCount
= InitialAnnounceCount
;
5917 InitializeLastAPTime(m
, rr
);
5918 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
5920 // If we're probing for this record, we just failed
5921 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
5923 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will rename %s", rr
->ProbeCount
, ARDisplayString(m
, rr
));
5924 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5926 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the same machine giving
5927 // different answers for the reverse mapping record.) This is simply a misconfiguration, and we don't try to recover from it.
5928 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
5930 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
5931 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
5934 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
5937 // Else, matching signature, different type or rdata, but not a considered a conflict.
5938 // If the packet record has the cache-flush bit set, then we check to see if we
5939 // have any record(s) of the same type that we should re-assert to rescue them
5940 // (see note about "multi-homing and bridged networks" at the end of this function).
5941 else if (m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
)
5942 if ((m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
5943 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
5948 if (!AcceptableResponse
)
5950 const CacheRecord
*cr
;
5951 for (cr
= CacheFlushRecords
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
5953 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
5954 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
5955 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
5956 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
5957 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
5958 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
5960 if (target
&& cr
->resrec
.rdatahash
== m
->rec
.r
.resrec
.namehash
&& SameDomainName(target
, m
->rec
.r
.resrec
.name
))
5962 debugf("mDNSCoreReceiveResponse: Found a matching entry for %##s in the CacheFlushRecords", m
->rec
.r
.resrec
.name
->c
);
5963 AcceptableResponse
= mDNStrue
;
5964 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
5970 // 2. See if we want to add this packet resource record to our cache
5971 // We only try to cache answers if we have a cache to put them in
5972 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
5973 if (!AcceptableResponse
) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m
, &m
->rec
.r
));
5974 if (m
->rrcache_size
&& AcceptableResponse
)
5976 const mDNSu32 slot
= HashSlot(m
->rec
.r
.resrec
.name
);
5977 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &m
->rec
.r
.resrec
);
5980 // 2a. Check if this packet resource record is already in our cache
5981 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
5983 mDNSBool match
= !InterfaceID
? m
->rec
.r
.resrec
.rDNSServer
== rr
->resrec
.rDNSServer
: rr
->resrec
.InterfaceID
== InterfaceID
;
5984 // If we found this exact resource record, refresh its TTL
5985 if (match
&& IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
5987 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
5988 verbosedebugf("Found record size %5d interface %p already in cache: %s",
5989 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
5991 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
5993 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
5994 if (rr
->NextInCFList
== mDNSNULL
&& cfp
!= &rr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
5995 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; *cfp
= (CacheRecord
*)1; }
5997 // If this packet record is marked unique, and our previous cached copy was not, then fix it
5998 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
6001 for (q
= m
->Questions
; q
; q
=q
->next
) if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) q
->UniqueAnswers
++;
6002 rr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
6006 if (!SameRDataBody(&m
->rec
.r
.resrec
, &rr
->resrec
.rdata
->u
, SameDomainNameCS
))
6008 // If the rdata of the packet record differs in name capitalization from the record in our cache
6009 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
6010 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
6011 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
6012 rr
->resrec
.rroriginalttl
= 0;
6013 rr
->TimeRcvd
= m
->timenow
;
6014 rr
->UnansweredQueries
= MaxUnansweredQueries
;
6015 SetNextCacheCheckTimeForRecord(m
, rr
);
6016 LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m
,rr
));
6017 LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m
,&m
->rec
.r
));
6018 LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
6019 NextCacheCheckEvent(rr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
6020 // DO NOT break out here -- we want to continue as if we never found it
6022 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
6025 //if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
6026 RefreshCacheRecord(m
, rr
, m
->rec
.r
.resrec
.rroriginalttl
);
6028 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
6029 // polling the network once we get a valid response back. For the first time when a new
6030 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
6031 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
6032 // configuration changed, without flushing the cache, we reset the question interval here.
6033 // Currently, we do this for for both multicast and unicast questions as long as the record
6034 // type is unique. For unicast, resource record is always unique and for multicast it is
6035 // true for records like A etc. but not for PTR.
6036 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
6038 for (q
= m
->Questions
; q
; q
=q
->next
)
6040 if (!q
->DuplicateOf
&& !q
->LongLived
&&
6041 ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
6043 q
->LastQTime
= m
->timenow
;
6044 q
->LastQTxTime
= m
->timenow
;
6045 q
->RecentAnswerPkts
= 0;
6046 q
->ThisQInterval
= MaxQuestionInterval
;
6047 q
->RequestUnicast
= mDNSfalse
;
6048 q
->unansweredQueries
= 0;
6049 debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
6050 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
6058 // If the packet TTL is zero, that means we're deleting this record.
6059 // To give other hosts on the network a chance to protest, we push the deletion
6060 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
6061 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
6062 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
6063 // If record's current expiry time is more than a second from now, we set it to expire in one second.
6064 // If the record is already going to expire in less than one second anyway, we leave it alone --
6065 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
6066 debugf("DE for %s", CRDisplayString(m
, rr
));
6067 if (RRExpireTime(rr
) - m
->timenow
> mDNSPlatformOneSecond
)
6069 rr
->resrec
.rroriginalttl
= 1;
6070 rr
->TimeRcvd
= m
->timenow
;
6071 rr
->UnansweredQueries
= MaxUnansweredQueries
;
6072 SetNextCacheCheckTimeForRecord(m
, rr
);
6079 // If packet resource record not in our cache, add it now
6080 // (unless it is just a deletion of a record we never had, in which case we don't care)
6081 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
6083 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
6084 const mDNSs32 delay
= AddToCFList
? NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
) :
6085 CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
, slot
);
6086 // If unique, assume we may have to delay delivery of this 'add' event.
6087 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
6088 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
6089 // to schedule an mDNS_Execute task at the appropriate time.
6090 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
);
6093 if (AddToCFList
) { *cfp
= rr
; cfp
= &rr
->NextInCFList
; *cfp
= (CacheRecord
*)1; }
6094 else if (rr
->DelayDelivery
) ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
6098 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6102 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6104 // If we've just received one or more records with their cache flush bits set,
6105 // then scan that cache slot to see if there are any old stale records we need to flush
6106 while (CacheFlushRecords
!= (CacheRecord
*)1)
6108 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
6109 const mDNSu32 slot
= HashSlot(r1
->resrec
.name
);
6110 const CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &r1
->resrec
);
6111 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
6112 r1
->NextInCFList
= mDNSNULL
;
6114 // Look for records in the cache with the same signature as this new one with the cache flush
6115 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
6116 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
6117 // We make these TTL adjustments *only* for records that still have *more* than one second
6118 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
6119 // (and now has half a second remaining) could inadvertently get its life extended, by either
6120 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
6121 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
6122 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
6123 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
6124 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
6125 // To avoid this, we need to ensure that the cache flushing operation will only act to
6126 // *decrease* a record's remaining lifetime, never *increase* it.
6127 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
6128 // For Unicast (null InterfaceID) the DNSservers should also match
6129 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
6130 (r1
->resrec
.InterfaceID
|| (r1
->resrec
.rDNSServer
== r2
->resrec
.rDNSServer
)) &&
6131 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
6132 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
)
6134 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
6135 // else, if record is old, mark it to be flushed
6136 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
6138 // If we find mismatched TTLs in an RRSet, correct them.
6139 // We only do this for records with a TTL of 2 or higher. It's possible to have a
6140 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
6141 // which we treat as a goodbye followed by an addition) and in that case it would be
6142 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
6143 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
6144 // because certain early Bonjour devices are known to have this specific mismatch, and
6145 // there's no point filling syslog with messages about something we already know about.
6146 // We also don't log this for uDNS responses, since a caching name server is obliged
6147 // to give us an aged TTL to correct for how long it has held the record,
6148 // so our received TTLs are expected to vary in that case
6149 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
6151 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
6152 mDNSOpaque16IsZero(response
->h
.id
))
6153 LogInfo("Correcting TTL from %4d to %4d for %s",
6154 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
6155 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
6157 r2
->TimeRcvd
= m
->timenow
;
6159 else // else, if record is old, mark it to be flushed
6161 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
6162 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
6163 // We set stale records to expire in one second.
6164 // This gives the owner a chance to rescue it if necessary.
6165 // This is important in the case of multi-homing and bridged networks:
6166 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
6167 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
6168 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
6169 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
6170 // By delaying the deletion by one second, we give X a change to notice that this bridging has
6171 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
6173 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
6174 // final expiration queries for this record.
6176 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
6177 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
6178 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
6179 // <rdar://problem/5636422> Updating TXT records is too slow
6180 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
6181 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
6182 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
6184 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
6185 r2
->resrec
.rroriginalttl
= 0;
6187 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
6189 // We only set a record to expire in one second if it currently has *more* than a second to live
6190 // If it's already due to expire in a second or less, we just leave it alone
6191 r2
->resrec
.rroriginalttl
= 1;
6192 r2
->UnansweredQueries
= MaxUnansweredQueries
;
6193 r2
->TimeRcvd
= m
->timenow
- 1;
6194 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
6195 // that we marked for deletion via an explicit DE record
6198 SetNextCacheCheckTimeForRecord(m
, r2
);
6201 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
6203 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
, slot
);
6204 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
6205 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
6206 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
6210 // See if we need to generate negative cache entries for unanswered unicast questions
6211 ptr
= response
->data
;
6212 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
6215 DNSQuestion
*qptr
= mDNSNULL
;
6216 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
6217 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
6219 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
6220 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
6221 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
6222 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
6223 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
6224 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
6225 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
6226 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
6227 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
6228 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
6229 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
6230 LogInfo("Skipping check to see if we need to generate a negative cache entry for %##s (%s)", q
.qname
.c
, DNSTypeName(q
.qtype
));
6233 CacheRecord
*rr
, *neg
= mDNSNULL
;
6234 mDNSu32 slot
= HashSlot(&q
.qname
);
6235 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
6236 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
6237 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
6239 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
6240 if (RRExpireTime(rr
) - m
->timenow
> 0) break;
6241 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
6242 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= rr
;
6247 // We start off assuming a negative caching TTL of 60 seconds
6248 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
6249 mDNSu32 negttl
= 60;
6251 const domainname
*name
= &q
.qname
;
6252 mDNSu32 hash
= q
.qnamehash
;
6254 // Special case for our special Microsoft Active Directory "local SOA" check.
6255 // Some cheap home gateways don't include an SOA record in the authority section when
6256 // they send negative responses, so we don't know how long to cache the negative result.
6257 // Because we don't want to keep hitting the root name servers with our query to find
6258 // if we're on a network using Microsoft Active Directory using "local" as a private
6259 // internal top-level domain, we make sure to cache the negative result for at least one day.
6260 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
6262 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
6263 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
6265 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
6266 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
6268 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
6269 mDNSu32 ttl_s
= soa
->min
;
6270 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
6271 // for the SOA record for ".", where the record is reported as non-cacheable
6272 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
6273 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
6274 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
6275 if (negttl
< ttl_s
) negttl
= ttl_s
;
6277 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
6278 // with an Authority Section SOA record for d.com, then this is a hint that the authority
6279 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
6280 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
6281 if (q
.qtype
== kDNSType_SOA
)
6283 int qcount
= CountLabels(&q
.qname
);
6284 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
6285 if (qcount
- 1 > scount
)
6286 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
6287 repeat
= qcount
- 1 - scount
;
6290 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6293 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
6294 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
6295 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
6296 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
6297 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
6298 // so that we back off our polling rate and don't keep hitting the server continually.
6301 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
6302 negttl
= neg
->resrec
.rroriginalttl
* 2;
6307 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
6309 // If we already had a negative cache entry just update it, else make one or more new negative cache entries
6312 debugf("Renewing negative TTL from %d to %d %s", neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
6313 RefreshCacheRecord(m
, neg
, negttl
);
6317 debugf("mDNSCoreReceiveResponse making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
6318 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
6319 CreateNewCacheEntry(m
, slot
, cg
, 0); // We never need any delivery delay for these generated negative cache records
6320 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6323 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
6324 hash
= DomainNameHashValue(name
);
6325 slot
= HashSlot(name
);
6326 cg
= CacheGroupForName(m
, slot
, hash
, name
);
6334 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
6337 for (rr
= thelist
; rr
; rr
=rr
->next
)
6338 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
6339 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6342 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
6344 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
6345 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
6348 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
6350 if (result
&& result
!= mStatus_MemFree
)
6351 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
6353 if (result
== mStatus_NameConflict
)
6355 LogMsg("Received Conflicting mDNS -- waking %s %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
6356 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
);
6357 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
);
6359 else if (result
== mStatus_MemFree
)
6362 mDNSPlatformMemFree(ar
);
6363 mDNS_UpdateAllowSleep(m
);
6367 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
6368 const DNSMessage
*const msg
, const mDNSu8
*end
,
6369 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
6370 const mDNSInterfaceID InterfaceID
)
6374 mDNSu8
*p
= m
->omsg
.data
;
6375 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
6376 mDNSu32 updatelease
= 0;
6379 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6380 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6381 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
6382 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
6383 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
6384 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
6385 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
6387 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
6389 if (mDNS_PacketLoggingEnabled
)
6390 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
6392 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
6395 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
6396 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
6399 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
6400 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
6402 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
6403 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
6406 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6409 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
6411 if (!updatelease
|| !owner
.HMAC
.l
[0])
6413 static int msgs
= 0;
6417 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
6418 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
6420 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
6422 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
6424 static int msgs
= 0;
6428 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
6429 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
6431 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
6435 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
6437 if (updatelease
> 24 * 60 * 60)
6438 updatelease
= 24 * 60 * 60;
6440 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
6441 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
6443 ptr
= LocateAuthorities(msg
, end
);
6444 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
6446 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
6447 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
6449 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
6450 AuthRecord
*ar
= mDNSPlatformMemAllocate(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
6451 if (!ar
) { m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
; break; }
6454 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
6455 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
6456 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
6457 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
6458 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, SPSRecordCallback
, ar
);
6459 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
6460 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
6461 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
6462 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
6463 ar
->ForceMCast
= mDNStrue
;
6465 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
6467 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
6468 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
6469 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
6470 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
6471 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
6473 ar
->TimeRcvd
= m
->timenow
;
6474 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
6475 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
6476 m
->NextScheduledSPS
= ar
->TimeExpire
;
6477 mDNS_Register_internal(m
, ar
);
6478 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
6479 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
6480 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
6481 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
6482 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
6483 if (m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
6484 if (ar
->resrec
.rrtype
== kDNSType_AAAA
) ar
->resrec
.rroriginalttl
= 0;
6486 mDNS_UpdateAllowSleep(m
);
6487 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
6490 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6493 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
6495 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
6496 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
6497 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
6501 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
6502 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
6503 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
6504 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
6505 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
6506 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
6507 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
6511 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
);
6514 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSInterfaceID InterfaceID
)
6519 mDNSu32 updatelease
= 60 * 60; // If SPS fails to indicate lease time, assume one hour
6520 const mDNSu8
*ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
);
6523 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
6524 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
6527 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
6528 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
6529 if (o
->opt
== kDNSOpt_Lease
)
6531 updatelease
= o
->u
.updatelease
;
6532 LogSPS("Sleep Proxy granted lease time %4d seconds", updatelease
);
6535 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6538 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6539 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
6540 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
6542 rr
->updateid
= zeroID
;
6543 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
6544 LogSPS("Sleep Proxy registered record %5d %s", updatelease
, ARDisplayString(m
,rr
));
6548 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
6549 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
6550 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
6553 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
6554 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
, DNSServer
*dnsserver
)
6556 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
6558 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
6564 // Create empty resource record
6565 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
6566 cr
->resrec
.InterfaceID
= InterfaceID
;
6567 cr
->resrec
.rDNSServer
= dnsserver
;
6568 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
6569 cr
->resrec
.rrtype
= rrtype
;
6570 cr
->resrec
.rrclass
= rrclass
;
6571 cr
->resrec
.rroriginalttl
= ttl_seconds
;
6572 cr
->resrec
.rdlength
= 0;
6573 cr
->resrec
.rdestimate
= 0;
6574 cr
->resrec
.namehash
= namehash
;
6575 cr
->resrec
.rdatahash
= 0;
6576 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
6577 cr
->resrec
.rdata
->MaxRDLength
= 0;
6579 cr
->NextInKAList
= mDNSNULL
;
6580 cr
->TimeRcvd
= m
->timenow
;
6581 cr
->DelayDelivery
= 0;
6582 cr
->NextRequiredQuery
= m
->timenow
;
6583 cr
->LastUsed
= m
->timenow
;
6584 cr
->CRActiveQuestion
= mDNSNULL
;
6585 cr
->UnansweredQueries
= 0;
6586 cr
->LastUnansweredTime
= 0;
6587 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6588 cr
->MPUnansweredQ
= 0;
6589 cr
->MPLastUnansweredQT
= 0;
6590 cr
->MPUnansweredKA
= 0;
6591 cr
->MPExpectingKA
= mDNSfalse
;
6593 cr
->NextInCFList
= mDNSNULL
;
6596 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, void *const pkt
, const mDNSu8
*const end
,
6597 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
6598 const mDNSInterfaceID InterfaceID
)
6600 mDNSInterfaceID ifid
= InterfaceID
;
6601 DNSMessage
*msg
= (DNSMessage
*)pkt
;
6602 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
6603 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
6604 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
6605 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
6607 mDNSu8
*ptr
= mDNSNULL
;
6608 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
6609 if (TLS
) dstaddr
= mDNSNULL
;
6611 #ifndef UNICAST_DISABLED
6612 if (mDNSSameAddress(srcaddr
, &m
->Router
))
6614 #ifdef _LEGACY_NAT_TRAVERSAL_
6615 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
6618 LNT_ConfigureRouterInfo(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
6623 if (mDNSSameIPPort(srcport
, NATPMPPort
))
6626 uDNS_ReceiveNATPMPPacket(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
6631 #ifdef _LEGACY_NAT_TRAVERSAL_
6632 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
6636 if ((unsigned)(end
- (mDNSu8
*)pkt
) < sizeof(DNSMessageHeader
))
6638 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
);
6641 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
6642 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
6643 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
6644 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
6645 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
6646 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
6647 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
6649 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
6651 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
6652 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
6653 if (srcaddr
&& !mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
6657 #ifndef UNICAST_DISABLED
6658 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
6659 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
6661 ifid
= mDNSInterface_Any
;
6662 if (mDNS_PacketLoggingEnabled
)
6663 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
6664 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
6665 // Note: mDNSCore also needs to get access to received unicast responses
6668 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
6669 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
6670 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
6671 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, InterfaceID
);
6674 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
6675 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
, InterfaceID
);
6676 if (mDNS_LoggingEnabled
)
6679 while (i
<end
- (mDNSu8
*)pkt
)
6682 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
6683 do if (i
<end
- (mDNSu8
*)pkt
) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", ((mDNSu8
*)pkt
)[i
]); while (++i
& 15);
6684 LogInfo("%s", buffer
);
6688 // Packet reception often causes a change to the task list:
6689 // 1. Inbound queries can cause us to need to send responses
6690 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
6691 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
6692 // 4. Response packets that answer questions may cause our client to issue new questions
6696 // ***************************************************************************
6697 #if COMPILER_LIKES_PRAGMA_MARK
6699 #pragma mark - Searcher Functions
6702 // Targets are considered the same if both queries are untargeted, or
6703 // if both are targeted to the same address+port
6704 // (If Target address is zero, TargetPort is undefined)
6705 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
6706 (mDNSSameAddress(&(A)->Target, &(B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
6708 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
6709 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
6710 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
6711 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
6712 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
6714 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
6715 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
6716 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
6717 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
6718 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
6719 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
6720 // breaks this design principle.
6722 // If IsLLQ(Q) is true, it means the question is both:
6723 // (a) long-lived and
6724 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
6725 // for multicast questions, we don't want to treat LongLived as anything special
6726 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
6728 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
6731 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
6732 // This prevents circular references, where two questions are each marked as a duplicate of the other.
6733 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
6734 // further in the list.
6735 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list for another question
6736 if (q
->InterfaceID
== question
->InterfaceID
&& // with the same InterfaceID,
6737 SameQTarget(q
, question
) && // and same unicast/multicast target settings
6738 q
->qtype
== question
->qtype
&& // type,
6739 q
->qclass
== question
->qclass
&& // class,
6740 IsLLQ(q
) == IsLLQ(question
) && // and long-lived status matches
6741 (!q
->AuthInfo
|| question
->AuthInfo
) && // to avoid deadlock, don't make public query dup of a private one
6742 (q
->SuppressQuery
== question
->SuppressQuery
) && // Questions that are suppressed/not suppressed
6743 q
->qnamehash
== question
->qnamehash
&&
6744 SameDomainName(&q
->qname
, &question
->qname
)) // and name
6749 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
6750 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
6753 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
6754 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
6755 if ((q
->DuplicateOf
= FindDuplicateQuestion(m
, q
)) == mDNSNULL
)
6757 // If q used to be a duplicate, but now is not,
6758 // then inherit the state from the question that's going away
6759 q
->LastQTime
= question
->LastQTime
;
6760 q
->ThisQInterval
= question
->ThisQInterval
;
6761 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
6762 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
6763 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
6764 q
->RequestUnicast
= question
->RequestUnicast
;
6765 q
->LastQTxTime
= question
->LastQTxTime
;
6766 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
6767 q
->nta
= question
->nta
;
6768 q
->servAddr
= question
->servAddr
;
6769 q
->servPort
= question
->servPort
;
6770 q
->qDNSServer
= question
->qDNSServer
;
6771 q
->validDNSServers
= question
->validDNSServers
;
6772 q
->unansweredQueries
= question
->unansweredQueries
;
6773 q
->noServerResponse
= question
->noServerResponse
;
6774 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
6776 q
->TargetQID
= question
->TargetQID
;
6777 q
->LocalSocket
= question
->LocalSocket
;
6779 q
->state
= question
->state
;
6780 // q->tcp = question->tcp;
6781 q
->ReqLease
= question
->ReqLease
;
6782 q
->expire
= question
->expire
;
6783 q
->ntries
= question
->ntries
;
6784 q
->id
= question
->id
;
6786 question
->LocalSocket
= mDNSNULL
;
6787 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
6788 // question->tcp = mDNSNULL;
6791 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6795 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6796 q
->nta
->ZoneDataContext
= q
;
6799 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
6800 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
6802 if (question
->state
== LLQ_Established
)
6804 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6805 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
6808 SetNextQueryTime(m
,q
);
6812 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
6815 if (server
->penaltyTime
!= 0)
6817 ptime
= server
->penaltyTime
- m
->timenow
;
6820 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
6821 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
6823 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
6824 ptime
, server
->penaltyTime
, m
->timenow
);
6825 server
->penaltyTime
= 0;
6832 //Checks to see whether the newname is a better match for the name, given the best one we have
6833 //seen so far (given in bestcount).
6834 //Returns -1 if the newname is not a better match
6835 //Returns 0 if the newname is the same as the old match
6836 //Returns 1 if the newname is a better match
6837 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
6840 // If the name contains fewer labels than the new server's domain or the new name
6841 // contains fewer labels than the current best, then it can't possibly be a better match
6842 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
6844 // If there is no match, return -1 and the caller will skip this newname for
6847 // If we find a match and the number of labels is the same as bestcount, then
6848 // we return 0 so that the caller can do additional logic to pick one of
6849 // the best based on some other factors e.g., penaltyTime
6851 // If we find a match and the number of labels is more than bestcount, then we
6852 // return 1 so that the caller can pick this over the old one.
6854 // Note: newcount can either be equal or greater than bestcount beause of the
6857 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
6858 return bestcount
== newcount
? 0 : 1;
6863 // Sets all the Valid DNS servers for a question
6864 mDNSexport
void SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
6866 DNSServer
*curmatch
= mDNSNULL
;
6867 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
6869 int bettermatch
, currcount
;
6872 question
->validDNSServers
= zeroOpaque64
;
6873 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
6875 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scoped
);
6876 // skip servers that will soon be deleted
6877 if (curr
->flags
& DNSServer_FlagDelete
)
6878 { debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
); continue; }
6880 currcount
= CountLabels(&curr
->domain
);
6881 if ((!curr
->scoped
&& (!question
->InterfaceID
|| (question
->InterfaceID
== mDNSInterface_Unicast
))) || (curr
->interface
== question
->InterfaceID
))
6883 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
6885 // If we found a better match (bettermatch == 1) then clear all the bits
6886 // corresponding to the old DNSServers that we have may set before and start fresh.
6887 // If we find an equal match, then include that DNSServer also by setting the corresponding
6889 if ((bettermatch
== 1) || (bettermatch
== 0))
6892 bestmatchlen
= currcount
;
6893 if (bettermatch
) { debugf("SetValidDNSServers: Resetting all the bits"); question
->validDNSServers
= zeroOpaque64
; }
6894 debugf("SetValidDNSServers: Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d", &curr
->addr
, curr
->domain
.c
, curr
->scoped
, index
);
6895 bit_set_opaque64(question
->validDNSServers
, index
);
6900 question
->noServerResponse
= 0;
6901 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
6902 question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
6905 // Get the Best server that matches a name. If you find penalized servers, look for the one
6906 // that will come out of the penalty box soon
6907 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSOpaque64 validBits
, int *selected
, mDNSBool nameMatch
)
6909 DNSServer
*curmatch
= mDNSNULL
;
6910 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
6912 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
6913 int bettermatch
, currcount
;
6917 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
6918 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
6919 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
6921 // skip servers that will soon be deleted
6922 if (curr
->flags
& DNSServer_FlagDelete
)
6923 { debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
); continue; }
6925 // Check if this is a valid DNSServer
6926 if (!bit_get_opaque64(validBits
, index
)) { debugf("GetBestServer: continuing for index %d", index
); index
++; continue; }
6928 currcount
= CountLabels(&curr
->domain
);
6929 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
6931 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
6932 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
6934 // If there are multiple best servers for a given question, we will pick the first one
6935 // if none of them are penalized. If some of them are penalized in that list, we pick
6936 // the least penalized one. BetterMatchForName walks through all best matches and
6937 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
6938 // in the list when there are no penalized servers and least one among them
6939 // when there are some penalized servers
6941 // Notes on InterfaceID matching:
6943 // 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
6944 // is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
6945 // entries by "scoped" being false. These are like any other unscoped entries except that
6946 // if it is picked e.g., domain match, when the packet is sent out later, the packet will
6947 // be sent out on that interface. Theese entries can be matched by either specifying a
6948 // zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
6949 // the question will cause an extra check on matching the InterfaceID on the question
6950 // against the DNSServer.
6952 // 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
6953 // is the new way of specifying an InterfaceID option for DNSServer. These will be considered
6954 // only when the question has non-zero interfaceID.
6956 if ((!curr
->scoped
&& !InterfaceID
) || (curr
->interface
== InterfaceID
))
6959 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
6960 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
6961 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
6962 // part and still do some redundant steps e.g., InterfaceID match
6964 if (nameMatch
) bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
6965 else bettermatch
= 0;
6967 // If we found a better match (bettermatch == 1) then we don't need to
6968 // compare penalty times. But if we found an equal match, then we compare
6969 // the penalty times to pick a better match
6971 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
6972 { currindex
= index
; curmatch
= curr
; bestmatchlen
= currcount
; bestPenaltyTime
= currPenaltyTime
; }
6976 if (selected
) *selected
= currindex
;
6980 // Look up a DNS Server, matching by name and InterfaceID
6981 mDNSexport DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
)
6983 DNSServer
*curmatch
= mDNSNULL
;
6984 char *ifname
= mDNSNULL
; // for logging purposes only
6985 mDNSOpaque64 allValid
;
6987 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
6988 InterfaceID
= mDNSNULL
;
6990 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
6992 // By passing in all ones, we make sure that every DNS server is considered
6993 allValid
.l
[0] = allValid
.l
[1] = 0xFFFFFFFF;
6995 curmatch
= GetBestServer(m
, name
, InterfaceID
, allValid
, mDNSNULL
, mDNStrue
);
6997 if (curmatch
!= mDNSNULL
)
6998 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch
->addr
,
6999 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
7002 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname
? ifname
: "None", InterfaceID
, name
);
7007 // Look up a DNS Server for a question within its valid DNSServer bits
7008 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
7010 DNSServer
*curmatch
= mDNSNULL
;
7011 char *ifname
= mDNSNULL
; // for logging purposes only
7012 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
7013 const domainname
*name
= &question
->qname
;
7016 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
7017 InterfaceID
= mDNSNULL
;
7019 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
7021 if (!mDNSOpaque64IsZero(&question
->validDNSServers
))
7023 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
7024 if (currindex
!= -1) bit_clr_opaque64(question
->validDNSServers
, currindex
);
7027 if (curmatch
!= mDNSNULL
)
7028 LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question
, &curmatch
->addr
,
7029 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
7030 InterfaceID
, name
, DNSTypeName(question
->qtype
));
7032 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question
, ifname
? ifname
: "None", InterfaceID
, name
, DNSTypeName(question
->qtype
));
7038 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
7039 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
7041 // Called in normal client context (lock not held)
7042 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
7047 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
7048 for (q
= m
->Questions
; q
; q
=q
->next
)
7049 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
7050 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
7051 #if APPLE_OSX_mDNSResponder
7052 UpdateAutoTunnelDomainStatuses(m
);
7057 mDNSlocal mDNSBool
ShouldSuppressQuery(mDNS
*const m
, domainname
*qname
, mDNSu16 qtype
, mDNSInterfaceID InterfaceID
)
7059 NetworkInterfaceInfo
*i
;
7061 DomainAuthInfo
*AuthInfo
;
7063 if (qtype
== kDNSType_A
) iptype
= mDNSAddrType_IPv4
;
7064 else if (qtype
== kDNSType_AAAA
) iptype
= mDNSAddrType_IPv6
;
7065 else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
7067 // We still want the ability to be able to listen to the local services and hence
7068 // don't fail .local requests. We always have a loopback interface which we don't
7070 if (IsLocalDomain(qname
)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
7072 // Skip Private domains as we have special addresses to get the hosts in the Private domain
7073 AuthInfo
= GetAuthInfoForName_internal(m
, qname
);
7074 if (AuthInfo
&& !AuthInfo
->deltime
&& AuthInfo
->AutoTunnel
)
7075 { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
7077 // Match on Type, Address and InterfaceID
7079 // Check whether we are looking for a name that ends in .local, then presence of a link-local
7080 // address on the interface is sufficient.
7081 for (i
= m
->HostInterfaces
; i
; i
= i
->next
)
7083 if (i
->ip
.type
!= iptype
) continue;
7085 if (!InterfaceID
|| (InterfaceID
== mDNSInterface_LocalOnly
) || (InterfaceID
== mDNSInterface_P2P
) ||
7086 (i
->InterfaceID
== InterfaceID
))
7088 if (iptype
== mDNSAddrType_IPv4
&& !mDNSv4AddressIsLoopback(&i
->ip
.ip
.v4
) && !mDNSv4AddressIsLinkLocal(&i
->ip
.ip
.v4
))
7090 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname
, DNSTypeName(qtype
),
7094 else if (iptype
== mDNSAddrType_IPv6
&&
7095 !mDNSv6AddressIsLoopback(&i
->ip
.ip
.v6
) &&
7096 !mDNSv6AddressIsLinkLocal(&i
->ip
.ip
.v6
) &&
7097 !mDNSSameIPv6Address(i
->ip
.ip
.v6
, m
->AutoTunnelHostAddr
) &&
7098 !mDNSSameIPv6Address(i
->ip
.ip
.v6
, m
->AutoTunnelRelayAddr
))
7100 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname
, DNSTypeName(qtype
),
7106 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname
, DNSTypeName(qtype
));
7110 mDNSlocal
void CheckSuppressedCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
7116 // Temporarily turn off suppression so that AnswerCurrentQuestionWithResourceRecord
7117 // can answer the question
7118 q
->SuppressQuery
= mDNSfalse
;
7119 slot
= HashSlot(&q
->qname
);
7120 cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
7121 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7123 // Don't deliver RMV events for negative records
7124 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
7126 LogInfo("CheckSuppressedCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
7127 CRDisplayString(m
, rr
), q
, q
->qname
.c
, DNSTypeName(q
->qtype
), rr
->CRActiveQuestion
, q
->CurrentAnswers
);
7131 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
7133 LogInfo("CheckSuppressedCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s",
7134 q
->qname
.c
, CRDisplayString(m
, rr
));
7136 q
->CurrentAnswers
--;
7137 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
7138 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
7140 if (rr
->CRActiveQuestion
== q
)
7143 // If this was the active question for this cache entry, it was the one that was
7144 // responsible for keeping the cache entry fresh when the cache entry was reaching
7145 // its expiry. We need to handover the responsibility to someone else. Otherwise,
7146 // when the cache entry is about to expire, we won't find an active question
7147 // (pointed by CRActiveQuestion) to refresh the cache.
7148 for (qptr
= m
->Questions
; qptr
; qptr
=qptr
->next
)
7149 if (ActiveQuestion(qptr
) && ResourceRecordAnswersQuestion(&rr
->resrec
, qptr
))
7153 LogInfo("CheckSuppressedCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
7154 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
7155 qptr
, CRDisplayString(m
,rr
), q
->CurrentAnswers
, qptr
->CurrentAnswers
, qptr
->SuppressUnusable
, qptr
->SuppressQuery
);
7157 rr
->CRActiveQuestion
= qptr
; // Question used to be active; new value may or may not be null
7158 if (!qptr
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
7160 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
7161 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
7164 if (m
->CurrentQuestion
== q
) q
->SuppressQuery
= mDNStrue
;
7167 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
7170 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
7171 if (q
== question
) return mDNStrue
;
7175 // The caller should hold the lock
7176 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
7178 DNSQuestion
*q
, *qnext
;
7179 DNSQuestion
*restart
= mDNSNULL
;
7181 // We look through all questions including new questions. During network change events,
7182 // we potentially restart questions here in this function that ends up as new questions,
7183 // which may be suppressed at this instance. Before it is handled we get another network
7184 // event that changes the status e.g., address becomes available. If we did not process
7185 // new questions, we would never change its SuppressQuery status.
7186 for (q
= m
->Questions
; q
; q
= qnext
)
7189 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->SuppressUnusable
)
7191 mDNSBool old
= q
->SuppressQuery
;
7192 q
->SuppressQuery
= ShouldSuppressQuery(m
, &q
->qname
, q
->qtype
, q
->InterfaceID
);
7193 if (q
->SuppressQuery
!= old
)
7195 if (q
->SuppressQuery
)
7197 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
7198 // followed by a negative cache response
7199 if (m
->CurrentQuestion
)
7200 LogMsg("CheckSuppressUnusableQuestions: ERROR m->CurrentQuestion already set: %##s (%s)",
7201 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
7203 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
7204 if (!IsQuestionNew(m
, q
))
7206 m
->CurrentQuestion
= q
;
7207 CheckSuppressedCurrentQuestion(m
, q
);
7208 if (m
->CurrentQuestion
!= q
)
7210 m
->CurrentQuestion
= mDNSNULL
;
7211 LogInfo("CheckSuppressUnusableQuestions: Question deleted while giving RMV events");
7214 m
->CurrentQuestion
= mDNSNULL
;
7216 else { debugf("CheckSuppressUnusableQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
7219 // There are two cases here.
7221 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
7222 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
7223 // because when we get the response, if we had entries in the cache already, it will not answer
7224 // this question if the cache entry did not change. Hence, we need to restart
7225 // the query so that it can be answered from the cache.
7227 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
7228 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
7229 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
7230 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
7231 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
7232 // immediate response and not want to be blocked behind a question that is querying DNS servers.
7233 // When the question is not suppressed, we don't want two active questions sending packets on the wire.
7234 // This affects both efficiency and also the current design where there is only one active question
7235 // pointed to from a cache entry.
7237 // We restart queries in a two step process by first calling stop and build a temporary list which we
7238 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
7239 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
7240 // will soon become the real question) including q->ThisQInterval which might be zero if it was
7241 // suppressed before. At the end when we have restarted all questions, none of them is active as each
7242 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
7244 // It is much cleaner and less error prone to build a list of questions and restart at the end.
7246 LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
7247 mDNS_StopQuery_internal(m
, q
);
7256 restart
= restart
->next
;
7258 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
7259 mDNS_StartQuery_internal(m
, q
);
7263 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
7265 if (question
->Target
.type
&& !ValidQuestionTarget(question
))
7267 LogMsg("Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery?)",
7268 question
->Target
.type
, mDNSVal16(question
->TargetPort
));
7269 question
->Target
.type
= mDNSAddrType_None
;
7272 if (!question
->Target
.type
) question
->TargetPort
= zeroIPPort
; // If no question->Target specified clear TargetPort
7274 question
->TargetQID
=
7275 #ifndef UNICAST_DISABLED
7276 (question
->Target
.type
|| Question_uDNS(question
)) ? mDNS_NewMessageID(m
) :
7277 #endif // UNICAST_DISABLED
7280 debugf("mDNS_StartQuery: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
7282 if (m
->rrcache_size
== 0) // Can't do queries if we have no cache space allocated
7283 return(mStatus_NoCache
);
7289 if (!ValidateDomainName(&question
->qname
))
7291 LogMsg("Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
7292 return(mStatus_Invalid
);
7295 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
7297 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
) q
= &m
->LocalOnlyQuestions
;
7298 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
7302 LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
7303 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
7304 return(mStatus_AlreadyRegistered
);
7309 // If this question is referencing a specific interface, verify it exists
7310 if (question
->InterfaceID
&& question
->InterfaceID
!= mDNSInterface_LocalOnly
&& question
->InterfaceID
!= mDNSInterface_Unicast
&& question
->InterfaceID
!= mDNSInterface_P2P
)
7312 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
7314 LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
7315 question
->InterfaceID
, question
->qname
.c
, DNSTypeName(question
->qtype
));
7318 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
7319 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
7320 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
7321 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
7322 // that to go out immediately.
7323 question
->next
= mDNSNULL
;
7324 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // MUST do this before FindDuplicateQuestion()
7325 question
->DelayAnswering
= CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
, HashSlot(&question
->qname
));
7326 question
->LastQTime
= m
->timenow
;
7327 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
7328 question
->ExpectUnicastResp
= 0;
7329 question
->LastAnswerPktNum
= m
->PktNum
;
7330 question
->RecentAnswerPkts
= 0;
7331 question
->CurrentAnswers
= 0;
7332 question
->LargeAnswers
= 0;
7333 question
->UniqueAnswers
= 0;
7334 question
->FlappingInterface1
= mDNSNULL
;
7335 question
->FlappingInterface2
= mDNSNULL
;
7336 // Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
7337 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
7338 if (question
->SuppressUnusable
)
7339 question
->SuppressQuery
= ShouldSuppressQuery(m
, &question
->qname
, question
->qtype
, question
->InterfaceID
);
7341 question
->SuppressQuery
= 0;
7342 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
7343 question
->NextInDQList
= mDNSNULL
;
7344 question
->SendQNow
= mDNSNULL
;
7345 question
->SendOnAll
= mDNSfalse
;
7346 question
->RequestUnicast
= 0;
7347 question
->LastQTxTime
= m
->timenow
;
7348 question
->CNAMEReferrals
= 0;
7350 // We'll create our question->LocalSocket on demand, if needed.
7351 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
7352 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
7353 // NAT mapping for receiving inbound add/remove events.
7354 question
->LocalSocket
= mDNSNULL
;
7355 question
->deliverAddEvents
= mDNSfalse
;
7356 question
->qDNSServer
= mDNSNULL
;
7357 question
->unansweredQueries
= 0;
7358 question
->nta
= mDNSNULL
;
7359 question
->servAddr
= zeroAddr
;
7360 question
->servPort
= zeroIPPort
;
7361 question
->tcp
= mDNSNULL
;
7362 question
->NoAnswer
= NoAnswer_Normal
;
7364 question
->state
= LLQ_InitialRequest
;
7365 question
->ReqLease
= 0;
7366 question
->expire
= 0;
7367 question
->ntries
= 0;
7368 question
->id
= zeroOpaque64
;
7369 question
->validDNSServers
= zeroOpaque64
;
7370 question
->triedAllServersOnce
= 0;
7371 question
->noServerResponse
= 0;
7373 if (question
->DuplicateOf
) question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
7375 for (i
=0; i
<DupSuppressInfoSize
; i
++)
7376 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
7378 debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
7379 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
7380 NextQSendTime(question
) - m
->timenow
,
7381 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
7382 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
7384 if (question
->DelayAnswering
)
7385 LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
7386 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
7388 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
)
7390 if (!m
->NewLocalOnlyQuestions
) m
->NewLocalOnlyQuestions
= question
;
7394 if (!m
->NewQuestions
) m
->NewQuestions
= question
;
7396 // If the question's id is non-zero, then it's Wide Area
7397 // MUST NOT do this Wide Area setup until near the end of
7398 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
7399 // NS, etc.) and if we haven't finished setting up our own question and setting
7400 // m->NewQuestions if necessary then we could end up recursively re-entering
7401 // this routine with the question list data structures in an inconsistent state.
7402 if (!mDNSOpaque16IsZero(question
->TargetQID
))
7404 // Duplicate questions should have the same DNSServers so that when we find
7405 // a matching resource record, all of them get the answers. Calling GetServerForQuestion
7406 // for the duplicate question may get a different DNS server from the original question
7407 if (question
->DuplicateOf
)
7409 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
7410 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
7411 LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
7412 question
, question
->DuplicateOf
, question
->qname
.c
, DNSTypeName(question
->qtype
),
7413 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
7414 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
7418 SetValidDNSServers(m
, question
);
7419 question
->qDNSServer
= GetServerForQuestion(m
, question
);
7420 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s), DNS Server %#a:%d",
7421 question
, question
->qname
.c
, DNSTypeName(question
->qtype
),
7422 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
7423 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
7425 ActivateUnicastQuery(m
, question
, mDNSfalse
);
7427 // If long-lived query, and we don't have our NAT mapping active, start it now
7428 if (question
->LongLived
&& !m
->LLQNAT
.clientContext
)
7430 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
7431 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
7432 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
7433 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
7434 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal is active
7435 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
7438 #if APPLE_OSX_mDNSResponder
7439 if (question
->LongLived
)
7440 UpdateAutoTunnelDomainStatuses(m
);
7444 SetNextQueryTime(m
,question
);
7447 return(mStatus_NoError
);
7451 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
7452 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
7454 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
7455 // This function may be called anytime to free the zone information.The question may or may not have stopped.
7456 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
7458 if (nta
->question
.ThisQInterval
!= -1)
7460 mDNS_StopQuery_internal(m
, &nta
->question
);
7461 if (nta
->question
.ThisQInterval
!= -1)
7462 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
7464 mDNSPlatformMemFree(nta
);
7467 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
7469 const mDNSu32 slot
= HashSlot(&question
->qname
);
7470 CacheGroup
*cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
7472 DNSQuestion
**qp
= &m
->Questions
;
7474 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
7476 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
) qp
= &m
->LocalOnlyQuestions
;
7477 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
7478 if (*qp
) *qp
= (*qp
)->next
;
7482 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
7484 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
7485 question
->qname
.c
, DNSTypeName(question
->qtype
));
7489 return(mStatus_BadReferenceErr
);
7492 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
7493 UpdateQuestionDuplicates(m
, question
);
7494 // But don't trash ThisQInterval until afterwards.
7495 question
->ThisQInterval
= -1;
7497 // If there are any cache records referencing this as their active question, then see if there is any
7498 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
7499 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7501 if (rr
->CRActiveQuestion
== question
)
7504 // Checking for ActiveQuestion filters questions that are suppressed also
7505 // as suppressed questions are not active
7506 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
7507 if (ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
7510 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
7511 "CurrentAnswers %d, SuppressQuery %d", q
, CRDisplayString(m
,rr
), question
->CurrentAnswers
, q
->CurrentAnswers
, q
->SuppressQuery
);
7512 rr
->CRActiveQuestion
= q
; // Question used to be active; new value may or may not be null
7513 if (!q
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
7517 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
7518 // bump its pointer forward one question.
7519 if (m
->CurrentQuestion
== question
)
7521 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
7522 question
->qname
.c
, DNSTypeName(question
->qtype
));
7523 m
->CurrentQuestion
= question
->next
;
7526 if (m
->NewQuestions
== question
)
7528 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
7529 question
->qname
.c
, DNSTypeName(question
->qtype
));
7530 m
->NewQuestions
= question
->next
;
7533 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
7535 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
7536 question
->next
= mDNSNULL
;
7538 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
7540 // And finally, cancel any associated GetZoneData operation that's still running.
7541 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
7542 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
7543 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
7544 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
7545 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
7546 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
7547 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
7549 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
7551 for (q
= m
->Questions
; q
; q
=q
->next
)
7552 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
7555 if (!m
->LLQNAT
.clientContext
) // Should never happen, but just in case...
7556 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
7559 LogInfo("Stopping LLQNAT");
7560 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
7561 m
->LLQNAT
.clientContext
= mDNSNULL
; // Means LLQ NAT Traversal not running
7565 // If necessary, tell server it can delete this LLQ state
7566 if (question
->state
== LLQ_Established
)
7568 question
->ReqLease
= 0;
7569 sendLLQRefresh(m
, question
);
7570 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
7571 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
7572 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
7573 // we let that run out its natural course and complete asynchronously.
7576 question
->tcp
->question
= mDNSNULL
;
7577 question
->tcp
= mDNSNULL
;
7580 #if APPLE_OSX_mDNSResponder
7581 UpdateAutoTunnelDomainStatuses(m
);
7584 // wait until we send the refresh above which needs the nta
7585 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
7587 return(mStatus_NoError
);
7590 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
7594 status
= mDNS_StartQuery_internal(m
, question
);
7599 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
7603 status
= mDNS_StopQuery_internal(m
, question
);
7608 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
7609 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
7610 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
7611 // specifically to catch and report if the client callback does try to make API calls
7612 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
7618 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
7619 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
7621 status
= mDNS_StopQuery_internal(m
, question
);
7622 if (status
== mStatus_NoError
&& !qq
)
7624 const CacheRecord
*rr
;
7625 const mDNSu32 slot
= HashSlot(&question
->qname
);
7626 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
7627 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
7628 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7629 if (rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameRecordAnswersQuestion(&rr
->resrec
, question
))
7631 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
7632 if (question
->QuestionCallback
)
7633 question
->QuestionCallback(m
, question
, &rr
->resrec
, mDNSfalse
);
7640 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
7644 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
7645 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
7650 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
7652 mStatus status
= mStatus_BadReferenceErr
;
7655 cr
= FindIdenticalRecordInCache(m
, rr
);
7656 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
7657 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
7658 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
7663 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
7664 const domainname
*const srv
, const domainname
*const domain
,
7665 const mDNSInterfaceID InterfaceID
, mDNSBool ForceMCast
, mDNSQuestionCallback
*Callback
, void *Context
)
7667 question
->InterfaceID
= InterfaceID
;
7668 question
->Target
= zeroAddr
;
7669 question
->qtype
= kDNSType_PTR
;
7670 question
->qclass
= kDNSClass_IN
;
7671 question
->LongLived
= mDNStrue
;
7672 question
->ExpectUnique
= mDNSfalse
;
7673 question
->ForceMCast
= ForceMCast
;
7674 question
->ReturnIntermed
= mDNSfalse
;
7675 question
->SuppressUnusable
= mDNSfalse
;
7676 question
->QuestionCallback
= Callback
;
7677 question
->QuestionContext
= Context
;
7678 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
)) return(mStatus_BadParamErr
);
7680 return(mDNS_StartQuery_internal(m
, question
));
7683 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
7684 const domainname
*const srv
, const domainname
*const domain
,
7685 const mDNSInterfaceID InterfaceID
, mDNSBool ForceMCast
, mDNSQuestionCallback
*Callback
, void *Context
)
7689 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, InterfaceID
, ForceMCast
, Callback
, Context
);
7694 mDNSlocal mDNSBool
MachineHasActiveIPv6(mDNS
*const m
)
7696 NetworkInterfaceInfo
*intf
;
7697 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
7698 if (intf
->ip
.type
== mDNSAddrType_IPv6
) return(mDNStrue
);
7702 mDNSlocal
void FoundServiceInfoSRV(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
7704 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
7705 mDNSBool PortChanged
= !mDNSSameIPPort(query
->info
->port
, answer
->rdata
->u
.srv
.port
);
7706 if (!AddRecord
) return;
7707 if (answer
->rrtype
!= kDNSType_SRV
) return;
7709 query
->info
->port
= answer
->rdata
->u
.srv
.port
;
7711 // If this is our first answer, then set the GotSRV flag and start the address query
7714 query
->GotSRV
= mDNStrue
;
7715 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
7716 AssignDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
);
7717 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
7718 AssignDomainName(&query
->qAv6
.qname
, &answer
->rdata
->u
.srv
.target
);
7719 mDNS_StartQuery(m
, &query
->qAv4
);
7720 // Only do the AAAA query if this machine actually has IPv6 active
7721 if (MachineHasActiveIPv6(m
)) mDNS_StartQuery(m
, &query
->qAv6
);
7723 // If this is not our first answer, only re-issue the address query if the target host name has changed
7724 else if ((query
->qAv4
.InterfaceID
!= query
->qSRV
.InterfaceID
&& query
->qAv4
.InterfaceID
!= answer
->InterfaceID
) ||
7725 !SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
))
7727 mDNS_StopQuery(m
, &query
->qAv4
);
7728 if (query
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery(m
, &query
->qAv6
);
7729 if (SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
) && !PortChanged
)
7731 // If we get here, it means:
7732 // 1. This is not our first SRV answer
7733 // 2. The interface ID is different, but the target host and port are the same
7734 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
7735 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
7736 query
->qAv4
.InterfaceID
= query
->qSRV
.InterfaceID
; // Will be mDNSInterface_Any, or a specific interface
7737 query
->qAv6
.InterfaceID
= query
->qSRV
.InterfaceID
;
7741 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
7742 AssignDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
);
7743 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
7744 AssignDomainName(&query
->qAv6
.qname
, &answer
->rdata
->u
.srv
.target
);
7746 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query
->qAv4
.qname
.c
, DNSTypeName(query
->qAv4
.qtype
));
7747 mDNS_StartQuery(m
, &query
->qAv4
);
7748 // Only do the AAAA query if this machine actually has IPv6 active
7749 if (MachineHasActiveIPv6(m
)) mDNS_StartQuery(m
, &query
->qAv6
);
7751 else if (query
->ServiceInfoQueryCallback
&& query
->GotADD
&& query
->GotTXT
&& PortChanged
)
7753 if (++query
->Answers
>= 100)
7754 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
7755 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.srv
.target
.c
,
7756 mDNSVal16(answer
->rdata
->u
.srv
.port
));
7757 query
->ServiceInfoQueryCallback(m
, query
);
7759 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7760 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7763 mDNSlocal
void FoundServiceInfoTXT(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
7765 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
7766 if (!AddRecord
) return;
7767 if (answer
->rrtype
!= kDNSType_TXT
) return;
7768 if (answer
->rdlength
> sizeof(query
->info
->TXTinfo
)) return;
7770 query
->GotTXT
= mDNStrue
;
7771 query
->info
->TXTlen
= answer
->rdlength
;
7772 query
->info
->TXTinfo
[0] = 0; // In case answer->rdlength is zero
7773 mDNSPlatformMemCopy(query
->info
->TXTinfo
, answer
->rdata
->u
.txt
.c
, answer
->rdlength
);
7775 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query
->info
->name
.c
, query
->GotADD
);
7777 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7778 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7779 if (query
->ServiceInfoQueryCallback
&& query
->GotADD
)
7781 if (++query
->Answers
>= 100)
7782 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
7783 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.txt
.c
);
7784 query
->ServiceInfoQueryCallback(m
, query
);
7788 mDNSlocal
void FoundServiceInfo(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
7790 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
7791 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
7792 if (!AddRecord
) return;
7794 if (answer
->rrtype
== kDNSType_A
)
7796 query
->info
->ip
.type
= mDNSAddrType_IPv4
;
7797 query
->info
->ip
.ip
.v4
= answer
->rdata
->u
.ipv4
;
7799 else if (answer
->rrtype
== kDNSType_AAAA
)
7801 query
->info
->ip
.type
= mDNSAddrType_IPv6
;
7802 query
->info
->ip
.ip
.v6
= answer
->rdata
->u
.ipv6
;
7806 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer
->name
->c
, answer
->rrtype
, DNSTypeName(answer
->rrtype
));
7810 query
->GotADD
= mDNStrue
;
7811 query
->info
->InterfaceID
= answer
->InterfaceID
;
7813 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query
->info
->ip
.type
, query
->info
->name
.c
, query
->GotTXT
);
7815 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
7816 // callback function is allowed to do anything, including deleting this query and freeing its memory.
7817 if (query
->ServiceInfoQueryCallback
&& query
->GotTXT
)
7819 if (++query
->Answers
>= 100)
7820 debugf(answer
->rrtype
== kDNSType_A
?
7821 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
7822 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
7823 query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.data
);
7824 query
->ServiceInfoQueryCallback(m
, query
);
7828 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
7829 // If the query is not interface-specific, then InterfaceID may be zero
7830 // Each time the Callback is invoked, the remainder of the fields will have been filled in
7831 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
7832 mDNSexport mStatus
mDNS_StartResolveService(mDNS
*const m
,
7833 ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
)
7838 query
->qSRV
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7839 query
->qSRV
.InterfaceID
= info
->InterfaceID
;
7840 query
->qSRV
.Target
= zeroAddr
;
7841 AssignDomainName(&query
->qSRV
.qname
, &info
->name
);
7842 query
->qSRV
.qtype
= kDNSType_SRV
;
7843 query
->qSRV
.qclass
= kDNSClass_IN
;
7844 query
->qSRV
.LongLived
= mDNSfalse
;
7845 query
->qSRV
.ExpectUnique
= mDNStrue
;
7846 query
->qSRV
.ForceMCast
= mDNSfalse
;
7847 query
->qSRV
.ReturnIntermed
= mDNSfalse
;
7848 query
->qSRV
.SuppressUnusable
= mDNSfalse
;
7849 query
->qSRV
.QuestionCallback
= FoundServiceInfoSRV
;
7850 query
->qSRV
.QuestionContext
= query
;
7852 query
->qTXT
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7853 query
->qTXT
.InterfaceID
= info
->InterfaceID
;
7854 query
->qTXT
.Target
= zeroAddr
;
7855 AssignDomainName(&query
->qTXT
.qname
, &info
->name
);
7856 query
->qTXT
.qtype
= kDNSType_TXT
;
7857 query
->qTXT
.qclass
= kDNSClass_IN
;
7858 query
->qTXT
.LongLived
= mDNSfalse
;
7859 query
->qTXT
.ExpectUnique
= mDNStrue
;
7860 query
->qTXT
.ForceMCast
= mDNSfalse
;
7861 query
->qTXT
.ReturnIntermed
= mDNSfalse
;
7862 query
->qTXT
.SuppressUnusable
= mDNSfalse
;
7863 query
->qTXT
.QuestionCallback
= FoundServiceInfoTXT
;
7864 query
->qTXT
.QuestionContext
= query
;
7866 query
->qAv4
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7867 query
->qAv4
.InterfaceID
= info
->InterfaceID
;
7868 query
->qAv4
.Target
= zeroAddr
;
7869 query
->qAv4
.qname
.c
[0] = 0;
7870 query
->qAv4
.qtype
= kDNSType_A
;
7871 query
->qAv4
.qclass
= kDNSClass_IN
;
7872 query
->qAv4
.LongLived
= mDNSfalse
;
7873 query
->qAv4
.ExpectUnique
= mDNStrue
;
7874 query
->qAv4
.ForceMCast
= mDNSfalse
;
7875 query
->qAv4
.ReturnIntermed
= mDNSfalse
;
7876 query
->qAv4
.SuppressUnusable
= mDNSfalse
;
7877 query
->qAv4
.QuestionCallback
= FoundServiceInfo
;
7878 query
->qAv4
.QuestionContext
= query
;
7880 query
->qAv6
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
7881 query
->qAv6
.InterfaceID
= info
->InterfaceID
;
7882 query
->qAv6
.Target
= zeroAddr
;
7883 query
->qAv6
.qname
.c
[0] = 0;
7884 query
->qAv6
.qtype
= kDNSType_AAAA
;
7885 query
->qAv6
.qclass
= kDNSClass_IN
;
7886 query
->qAv6
.LongLived
= mDNSfalse
;
7887 query
->qAv6
.ExpectUnique
= mDNStrue
;
7888 query
->qAv6
.ForceMCast
= mDNSfalse
;
7889 query
->qAv6
.ReturnIntermed
= mDNSfalse
;
7890 query
->qAv6
.SuppressUnusable
= mDNSfalse
;
7891 query
->qAv6
.QuestionCallback
= FoundServiceInfo
;
7892 query
->qAv6
.QuestionContext
= query
;
7894 query
->GotSRV
= mDNSfalse
;
7895 query
->GotTXT
= mDNSfalse
;
7896 query
->GotADD
= mDNSfalse
;
7900 query
->ServiceInfoQueryCallback
= Callback
;
7901 query
->ServiceInfoQueryContext
= Context
;
7903 // info->name = Must already be set up by client
7904 // info->interface = Must already be set up by client
7905 info
->ip
= zeroAddr
;
7906 info
->port
= zeroIPPort
;
7909 // We use mDNS_StartQuery_internal here because we're already holding the lock
7910 status
= mDNS_StartQuery_internal(m
, &query
->qSRV
);
7911 if (status
== mStatus_NoError
) status
= mDNS_StartQuery_internal(m
, &query
->qTXT
);
7912 if (status
!= mStatus_NoError
) mDNS_StopResolveService(m
, query
);
7918 mDNSexport
void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*q
)
7921 // We use mDNS_StopQuery_internal here because we're already holding the lock
7922 if (q
->qSRV
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qSRV
);
7923 if (q
->qTXT
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qTXT
);
7924 if (q
->qAv4
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qAv4
);
7925 if (q
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qAv6
);
7929 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
7930 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
7932 question
->InterfaceID
= InterfaceID
;
7933 question
->Target
= zeroAddr
;
7934 question
->qtype
= kDNSType_PTR
;
7935 question
->qclass
= kDNSClass_IN
;
7936 question
->LongLived
= mDNSfalse
;
7937 question
->ExpectUnique
= mDNSfalse
;
7938 question
->ForceMCast
= mDNSfalse
;
7939 question
->ReturnIntermed
= mDNSfalse
;
7940 question
->SuppressUnusable
= mDNSfalse
;
7941 question
->QuestionCallback
= Callback
;
7942 question
->QuestionContext
= Context
;
7943 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
7944 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
7945 if (!dom
) dom
= &localdomain
;
7946 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
7947 return(mDNS_StartQuery(m
, question
));
7950 // ***************************************************************************
7951 #if COMPILER_LIKES_PRAGMA_MARK
7953 #pragma mark - Responder Functions
7956 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
7960 status
= mDNS_Register_internal(m
, rr
);
7965 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
7966 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
7968 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
7970 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
7971 return(mStatus_Invalid
);
7976 // If TTL is unspecified, leave TTL unchanged
7977 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
7979 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
7982 RData
*n
= rr
->NewRData
;
7983 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
7984 if (rr
->UpdateCallback
)
7985 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
7988 rr
->NewRData
= newrdata
;
7989 rr
->newrdlength
= newrdlength
;
7990 rr
->UpdateCallback
= Callback
;
7992 #ifndef UNICAST_DISABLED
7993 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
&& rr
->resrec
.InterfaceID
!= mDNSInterface_P2P
&& !IsLocalDomain(rr
->resrec
.name
))
7995 mStatus status
= uDNS_UpdateRecord(m
, rr
);
7996 // The caller frees the memory on error, don't retain stale pointers
7997 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
8003 if (rr
->resrec
.rroriginalttl
== newttl
&&
8004 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
))
8005 CompleteRDataUpdate(m
, rr
);
8008 rr
->AnnounceCount
= InitialAnnounceCount
;
8009 InitializeLastAPTime(m
, rr
);
8010 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
8011 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
8012 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
8013 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
8014 if (rr
->UpdateCredits
<= 5)
8016 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
8017 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
8018 rr
->ThisAPInterval
*= 4;
8019 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
8020 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
8021 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
8023 rr
->resrec
.rroriginalttl
= newttl
;
8027 return(mStatus_NoError
);
8030 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
8031 // the record list and/or question list.
8032 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8033 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
8037 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
8042 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
8043 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
8045 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
8047 NetworkInterfaceInfo
*intf
;
8048 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8049 if (intf
->Advertise
) break;
8053 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8055 char buffer
[MAX_REVERSE_MAPPING_NAME
];
8056 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
8057 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
8059 // Send dynamic update for non-linklocal IPv4 Addresses
8060 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, kDNSRecordTypeUnique
, mDNS_HostNameCallback
, set
);
8061 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, mDNSNULL
, mDNSNULL
);
8062 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kHostNameTTL
, kDNSRecordTypeUnique
, mDNSNULL
, mDNSNULL
);
8064 #if ANSWER_REMOTE_HOSTNAME_QUERIES
8065 set
->RR_A
.AllowRemoteQuery
= mDNStrue
;
8066 set
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
8067 set
->RR_HINFO
.AllowRemoteQuery
= mDNStrue
;
8069 // 1. Set up Address record to map from host name ("foo.local.") to IP address
8070 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
8071 AssignDomainName(&set
->RR_A
.namestorage
, &m
->MulticastHostname
);
8072 if (set
->ip
.type
== mDNSAddrType_IPv4
)
8074 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
8075 set
->RR_A
.resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
8076 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
8077 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
8078 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
8080 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
8083 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
8084 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
8085 for (i
= 0; i
< 16; i
++)
8087 static const char hexValues
[] = "0123456789ABCDEF";
8088 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
8089 buffer
[i
* 4 + 1] = '.';
8090 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
8091 buffer
[i
* 4 + 3] = '.';
8093 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
8096 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.namestorage
, buffer
);
8097 set
->RR_PTR
.AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
8098 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
8100 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
8102 mDNS_Register_internal(m
, &set
->RR_A
);
8103 mDNS_Register_internal(m
, &set
->RR_PTR
);
8105 if (!NO_HINFO
&& m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
8107 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
8108 AssignDomainName(&set
->RR_HINFO
.namestorage
, &m
->MulticastHostname
);
8109 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
8110 mDNSPlatformMemCopy(p
, &m
->HIHardware
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
8112 mDNSPlatformMemCopy(p
, &m
->HISoftware
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
8113 mDNS_Register_internal(m
, &set
->RR_HINFO
);
8117 debugf("Not creating HINFO record: platform support layer provided no information");
8118 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
8122 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8124 NetworkInterfaceInfo
*intf
;
8126 // If we still have address records referring to this one, update them
8127 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
8128 AuthRecord
*A
= primary
? &primary
->RR_A
: mDNSNULL
;
8129 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8130 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
8131 intf
->RR_A
.RRSet
= A
;
8133 // Unregister these records.
8134 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
8135 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
8136 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
8137 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
8138 if (set
->RR_A
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
8139 if (set
->RR_PTR
. resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
8140 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
8143 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
8145 domainname newmname
;
8146 NetworkInterfaceInfo
*intf
;
8150 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
8151 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
8155 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
8158 AssignDomainName(&m
->MulticastHostname
, &newmname
);
8160 // 1. Stop advertising our address records on all interfaces
8161 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8162 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
);
8164 // 2. Start advertising our address records using the new name
8165 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8166 if (intf
->Advertise
) AdvertiseInterface(m
, intf
);
8169 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
8170 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) SetTargetToHostName(m
, rr
);
8171 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) SetTargetToHostName(m
, rr
);
8176 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
8178 (void)rr
; // Unused parameter
8182 char *msg
= "Unknown result";
8183 if (result
== mStatus_NoError
) msg
= "Name registered";
8184 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
8185 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
8189 if (result
== mStatus_NoError
)
8191 // Notify the client that the host name is successfully registered
8192 if (m
->MainCallback
)
8193 m
->MainCallback(m
, mStatus_NoError
);
8195 else if (result
== mStatus_NameConflict
)
8197 domainlabel oldlabel
= m
->hostlabel
;
8199 // 1. First give the client callback a chance to pick a new name
8200 if (m
->MainCallback
)
8201 m
->MainCallback(m
, mStatus_NameConflict
);
8203 // 2. If the client callback didn't do it, add (or increment) an index ourselves
8204 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
8205 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
8206 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
8207 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
8209 // 3. Generate the FQDNs from the hostlabel,
8210 // and make sure all SRV records, etc., are updated to reference our new hostname
8212 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
8214 else if (result
== mStatus_MemFree
)
8216 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
8217 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
8218 debugf("mDNS_HostNameCallback: MemFree (ignored)");
8221 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
8224 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
8226 NetworkInterfaceInfo
*intf
;
8227 active
->IPv4Available
= mDNSfalse
;
8228 active
->IPv6Available
= mDNSfalse
;
8229 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8230 if (intf
->InterfaceID
== active
->InterfaceID
)
8232 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
8233 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
8237 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
8240 LogInfo("RestartRecordGetZoneData: ResourceRecords");
8241 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
8242 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
8244 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
8245 // Zero out the updateid so that if we have a pending response from the server, it won't
8246 // be accepted as a valid response. If we accept the response, we might free the new "nta"
8247 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
8248 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
8252 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8255 set
->NetWakeBrowse
.ThisQInterval
= -1;
8258 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
8259 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
8261 set
->NextSPSAttempt
= -1;
8262 set
->NextSPSAttemptTime
= m
->timenow
;
8265 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8267 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
8268 while (p
&& p
!= set
) p
=p
->next
;
8269 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
8271 if (set
->InterfaceActive
)
8273 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
8274 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, set
->InterfaceID
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
8278 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
8280 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
8281 while (p
&& p
!= set
) p
=p
->next
;
8282 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
8284 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
8287 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
8289 // Stop our browse and resolve operations
8290 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
8291 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
8293 // Make special call to the browse callback to let it know it can to remove all records for this interface
8294 if (m
->SPSBrowseCallback
)
8296 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
8297 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
8298 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8301 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
8302 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
8303 InitializeNetWakeState(m
, set
);
8307 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
8310 mDNSBool FirstOfType
= mDNStrue
;
8311 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
8313 if (!set
->InterfaceID
)
8314 { LogMsg("Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set
->ip
); return(mStatus_Invalid
); }
8316 if (!mDNSAddressIsValidNonZero(&set
->mask
))
8317 { LogMsg("Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set
->ip
, &set
->mask
); return(mStatus_Invalid
); }
8321 // Assume this interface will be active now, unless we find a duplicate already in the list
8322 set
->InterfaceActive
= mDNStrue
;
8323 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
8324 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
8326 InitializeNetWakeState(m
, set
);
8328 // Scan list to see if this InterfaceID is already represented
8333 LogMsg("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
8335 return(mStatus_AlreadyRegistered
);
8338 if ((*p
)->InterfaceID
== set
->InterfaceID
)
8340 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
8341 set
->InterfaceActive
= mDNSfalse
;
8342 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
8343 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
8344 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
8350 set
->next
= mDNSNULL
;
8354 AdvertiseInterface(m
, set
);
8356 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set
->InterfaceID
, set
->ifname
, &set
->ip
,
8357 set
->InterfaceActive
?
8358 "not represented in list; marking active and retriggering queries" :
8359 "already represented in list; marking inactive for now");
8361 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
8363 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
8364 // giving the false impression that there's an active representative of this interface when there really isn't.
8365 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
8366 // even if we believe that we previously had an active representative of this interface.
8367 if (set
->McastTxRx
&& ((m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) || FirstOfType
|| set
->InterfaceActive
))
8370 // Normally, after an interface comes up, we pause half a second before beginning probing.
8371 // This is to guard against cases where there's rapid interface changes, where we could be confused by
8372 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
8373 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
8374 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
8375 // and think it's a conflicting answer to our probe.
8376 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
8377 const mDNSs32 probedelay
= flapping
? mDNSPlatformOneSecond
* 5 : mDNSPlatformOneSecond
/ 2;
8378 const mDNSu8 numannounce
= flapping
? (mDNSu8
)1 : InitialAnnounceCount
;
8380 // Use a small amount of randomness:
8381 // In the case of a network administrator turning on an Ethernet hub so that all the
8382 // connected machines establish link at exactly the same time, we don't want them all
8383 // to go and hit the network with identical queries at exactly the same moment.
8384 // We set a random delay of up to InitialQuestionInterval (1/3 second).
8385 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
8386 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
8387 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
8388 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
8389 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
8390 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
8392 if (flapping
) LogMsg("RegisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
8394 LogInfo("RegisterInterface: %s (%#a) probedelay %d", set
->ifname
, &set
->ip
, probedelay
);
8395 if (m
->SuppressProbes
== 0 ||
8396 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
8397 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
8399 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
8400 if (mDNSOpaque16IsZero(q
->TargetQID
))
8401 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
8402 { // then reactivate this question
8403 // If flapping, delay between first and second queries is nine seconds instead of one second
8404 mDNSBool dodelay
= flapping
&& (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
8405 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
8406 mDNSs32 qdelay
= dodelay
? mDNSPlatformOneSecond
* 5 : 0;
8407 if (dodelay
) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q
->qname
.c
, DNSTypeName(q
->qtype
));
8409 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
8411 q
->ThisQInterval
= initial
;
8412 q
->RequestUnicast
= 2; // Set to 2 because is decremented once *before* we check it
8414 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
8415 q
->RecentAnswerPkts
= 0;
8416 SetNextQueryTime(m
,q
);
8419 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
8420 // we now need them to re-probe if necessary, and then re-announce.
8421 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
8422 if (!AuthRecord_uDNS(rr
))
8423 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
8425 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
8426 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
8427 if (rr
->AnnounceCount
< numannounce
) rr
->AnnounceCount
= numannounce
;
8428 rr
->SendNSECNow
= mDNSNULL
;
8429 InitializeLastAPTime(m
, rr
);
8433 RestartRecordGetZoneData(m
);
8435 CheckSuppressUnusableQuestions(m
);
8437 mDNS_UpdateAllowSleep(m
);
8440 return(mStatus_NoError
);
8443 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
8444 // the record list and/or question list.
8445 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8446 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
8448 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
8450 mDNSBool revalidate
= mDNSfalse
;
8451 // If this platform has the "phantom interfaces" known bug (e.g. Jaguar), we have to revalidate records every
8452 // time an interface goes away. Otherwise, when you disconnect the Ethernet cable, the system reports that it
8453 // still has an IPv6 address, and if we don't revalidate those records don't get deleted in a timely fashion.
8454 if (m
->KnownBugs
& mDNS_KnownBug_PhantomInterfaces
) revalidate
= mDNStrue
;
8458 // Find this record in our list
8459 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
8460 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
8462 mDNS_DeactivateNetWake_internal(m
, set
);
8464 // Unlink this record from our list
8466 set
->next
= mDNSNULL
;
8468 if (!set
->InterfaceActive
)
8470 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
8471 NetworkInterfaceInfo
*intf
;
8472 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8473 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
8474 UpdateInterfaceProtocols(m
, intf
);
8478 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
8481 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
8482 " making it active", set
->InterfaceID
, set
->ifname
, &set
->ip
);
8483 if (intf
->InterfaceActive
)
8484 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set
->ifname
, &set
->ip
);
8485 intf
->InterfaceActive
= mDNStrue
;
8486 UpdateInterfaceProtocols(m
, intf
);
8488 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
8490 // See if another representative *of the same type* exists. If not, we mave have gone from
8491 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
8492 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
8493 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
8495 if (!intf
) revalidate
= mDNStrue
;
8505 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
8506 " marking questions etc. dormant", set
->InterfaceID
, set
->ifname
, &set
->ip
);
8508 if (set
->McastTxRx
&& flapping
)
8509 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
8511 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
8512 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
8513 for (q
= m
->Questions
; q
; q
=q
->next
)
8515 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
8516 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
8518 q
->FlappingInterface2
= q
->FlappingInterface1
;
8519 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
8523 // 2. Flush any cache records received on this interface
8524 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
8525 FORALL_CACHERECORDS(slot
, cg
, rr
)
8526 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
8528 // If this interface is deemed flapping,
8529 // postpone deleting the cache records in case the interface comes back again
8530 if (set
->McastTxRx
&& flapping
)
8532 // For a flapping interface we want these record to go away after 30 seconds
8533 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
8534 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
8535 // if the interface does come back, any relevant questions will be reactivated anyway
8536 rr
->UnansweredQueries
= MaxUnansweredQueries
;
8539 mDNS_PurgeCacheResourceRecord(m
, rr
);
8542 // 3. Any DNS servers specific to this interface are now unusable
8543 for (s
= m
->DNSServers
; s
; s
= s
->next
)
8544 if (s
->interface
== set
->InterfaceID
)
8546 s
->interface
= mDNSInterface_Any
;
8547 s
->teststate
= DNSServer_Disabled
;
8552 // If we were advertising on this interface, deregister those address and reverse-lookup records now
8553 if (set
->Advertise
) DeadvertiseInterface(m
, set
);
8555 // If we have any cache records received on this interface that went away, then re-verify them.
8556 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
8557 // giving the false impression that there's an active representative of this interface when there really isn't.
8558 // Don't need to do this when shutting down, because *all* interfaces are about to go away
8559 if (revalidate
&& !m
->ShutdownTime
)
8564 FORALL_CACHERECORDS(slot
, cg
, rr
)
8565 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
8566 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
8569 CheckSuppressUnusableQuestions(m
);
8571 mDNS_UpdateAllowSleep(m
);
8576 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
8578 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
8579 (void)m
; // Unused parameter
8583 char *msg
= "Unknown result";
8584 if (result
== mStatus_NoError
) msg
= "Name Registered";
8585 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
8586 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
8587 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
8591 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
8592 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
8594 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
8595 if (result
== mStatus_NameConflict
)
8597 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
8598 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
8602 if (result
== mStatus_MemFree
)
8604 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
8605 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
8606 // every record is finished cleaning up.
8608 ExtraResourceRecord
*e
= sr
->Extras
;
8610 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8611 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8612 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8613 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8614 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8618 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
8622 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
8623 // then we can now report the NameConflict to the client
8624 if (sr
->Conflict
) result
= mStatus_NameConflict
;
8628 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered": "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
8629 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
8630 // function is allowed to do anything, including deregistering this service and freeing its memory.
8631 if (sr
->ServiceCallback
)
8632 sr
->ServiceCallback(m
, sr
, result
);
8635 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
8637 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
8638 if (sr
->ServiceCallback
)
8639 sr
->ServiceCallback(m
, sr
, result
);
8643 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
8644 // Type is service type (e.g. "_ipp._tcp.")
8645 // Domain is fully qualified domain name (i.e. ending with a null label)
8646 // We always register a TXT, even if it is empty (so that clients are not
8647 // left waiting forever looking for a nonexistent record.)
8648 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
8649 // then the default host name (m->MulticastHostname) is automatically used
8650 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
8651 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
8652 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
8653 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
8654 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
8655 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
)
8660 sr
->ServiceCallback
= Callback
;
8661 sr
->ServiceContext
= Context
;
8662 sr
->Conflict
= mDNSfalse
;
8664 sr
->Extras
= mDNSNULL
;
8665 sr
->NumSubTypes
= NumSubTypes
;
8666 sr
->SubTypes
= SubTypes
;
8668 // Initialize the AuthRecord objects to sane values
8669 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
8670 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, ServiceCallback
, sr
);
8671 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
8672 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
8673 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
8675 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
8676 if (mDNSIPPortIsZero(port
))
8677 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, mDNSInterface_Any
, NSSCallback
, sr
));
8679 // If the client is registering an oversized TXT record,
8680 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
8681 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
8682 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
8684 // Set up the record names
8685 // For now we only create an advisory record for the main type, not for subtypes
8686 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
8687 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
8688 return(mStatus_BadParamErr
);
8689 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8690 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8691 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
8693 // 1. Set up the ADV record rdata to advertise our service type
8694 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
8696 // 2. Set up the PTR record rdata to point to our service name
8697 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
8698 // Note: uDNS registration code assumes that Additional1 points to the SRV record
8699 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
8700 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
8701 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
8703 // 2a. Set up any subtype PTRs to point to our service name
8704 // If the client is using subtypes, it is the client's responsibility to have
8705 // already set the first label of the record name to the subtype being registered
8706 for (i
=0; i
<NumSubTypes
; i
++)
8709 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
8710 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
8711 AppendDomainName(&st
, type
);
8712 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, ServiceCallback
, sr
);
8713 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8714 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
8715 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
8716 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
8719 // 3. Set up the SRV record rdata.
8720 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
8721 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
8722 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
8724 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
8725 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
8726 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
8728 // 4. Set up the TXT record rdata,
8729 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
8730 // Note: uDNS registration code assumes that DependentOn points to the SRV record
8731 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
8732 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
8734 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
8735 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
8736 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
8738 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
8741 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
8742 // that if the SRV cannot find a target, rest of the records that belong to this service
8743 // will not be activated.
8744 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
8745 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
8746 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
8747 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
8748 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
8749 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
8750 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
8751 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
8752 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
8753 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
8757 if (err
) mDNS_DeregisterService(m
, sr
);
8761 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
8762 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
)
8764 ExtraResourceRecord
**e
;
8767 extra
->next
= mDNSNULL
;
8768 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
8769 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, ServiceCallback
, sr
);
8770 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
8774 while (*e
) e
= &(*e
)->next
;
8776 if (ttl
== 0) ttl
= kStandardTTL
;
8778 extra
->r
.DependentOn
= &sr
->RR_SRV
;
8780 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
8781 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
8783 status
= mDNS_Register_internal(m
, &extra
->r
);
8784 if (status
== mStatus_NoError
) *e
= extra
;
8790 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
8791 mDNSRecordCallback MemFreeCallback
, void *Context
)
8793 ExtraResourceRecord
**e
;
8798 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
8801 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
8802 status
= mStatus_BadReferenceErr
;
8806 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
8807 extra
->r
.RecordCallback
= MemFreeCallback
;
8808 extra
->r
.RecordContext
= Context
;
8810 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
8816 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
8818 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
8819 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
8820 domainlabel name1
, name2
;
8821 domainname type
, domain
;
8822 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
8823 ExtraResourceRecord
*extras
= sr
->Extras
;
8826 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
8830 IncrementLabelSuffix(&name2
, mDNStrue
);
8834 if (SameDomainName(&domain
, &localdomain
))
8835 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
8836 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
8838 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
8839 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
8840 sr
->SubTypes
, sr
->NumSubTypes
,
8841 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
);
8843 // mDNS_RegisterService() just reset sr->Extras to NULL.
8844 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
8845 // through the old list of extra records, and re-add them to our freshly created service registration
8846 while (!err
&& extras
)
8848 ExtraResourceRecord
*e
= extras
;
8849 extras
= extras
->next
;
8850 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
);
8856 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
8857 // which may change the record list and/or question list.
8858 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8859 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
8861 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
8862 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
8864 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
8866 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
8867 return(mStatus_BadReferenceErr
);
8869 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
8871 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
8872 // Avoid race condition:
8873 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
8874 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
8875 // If the client happens to deregister the service in the middle of that process, then
8876 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
8877 // instead of incorrectly promoting it to mStatus_NameConflict.
8878 // This race condition is exposed particularly when the conformance test generates
8879 // a whole batch of simultaneous conflicts across a range of services all advertised
8880 // using the same system default name, and if we don't take this precaution then
8881 // we end up incrementing m->nicelabel multiple times instead of just once.
8882 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
8883 sr
->Conflict
= mDNSfalse
;
8884 return(mStatus_NoError
);
8890 ExtraResourceRecord
*e
;
8894 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
8895 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
8896 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
8897 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
8899 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
8901 // We deregister all of the extra records, but we leave the sr->Extras list intact
8902 // in case the client wants to do a RenameAndReregister and reinstate the registration
8905 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
8909 for (i
=0; i
<sr
->NumSubTypes
; i
++)
8910 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
8912 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
8918 // Create a registration that asserts that no such service exists with this name.
8919 // This can be useful where there is a given function is available through several protocols.
8920 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
8921 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
8922 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
8923 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
8924 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
8925 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
8926 const domainname
*const host
,
8927 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
)
8929 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, Callback
, Context
);
8930 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
8931 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
8932 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
8933 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
8934 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
8935 else rr
->AutoTarget
= Target_AutoHost
;
8936 return(mDNS_Register(m
, rr
));
8939 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
8940 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
8942 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, mDNSNULL
, mDNSNULL
);
8943 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
8944 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
8945 return(mDNS_Register(m
, rr
));
8948 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
8951 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
8955 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
8958 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
8962 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
8967 for (i
=0; i
<10; i
++)
8969 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
8970 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
8973 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
8978 // ***************************************************************************
8979 #if COMPILER_LIKES_PRAGMA_MARK
8981 #pragma mark - Sleep Proxy Server
8984 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
8986 // If we see an ARP from a machine we think is sleeping, then either
8987 // (i) the machine has woken, or
8988 // (ii) it's just a stray old packet from before the machine slept
8989 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
8990 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
8991 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
8992 // 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*
8993 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
8994 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
8996 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
8997 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
8999 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
9000 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
9001 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
9002 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
9003 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
9004 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
9005 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
9006 InitializeLastAPTime(m
, rr
);
9009 rr
->AnnounceCount
= InitialAnnounceCount
;
9010 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
9011 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
9012 SetNextAnnounceProbeTime(m
, rr
);
9016 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
9018 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
9020 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
9026 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
9027 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
9028 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
9029 // The times we might need to react to an ARP Announcement are:
9030 // (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
9031 // (ii) if it's a conflicting Announcement from another host
9032 // -- and we check for these in Pass 2 below.
9033 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
9035 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9036 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9037 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
9039 static const char msg1
[] = "ARP Req from owner -- re-probing";
9040 static const char msg2
[] = "Ignoring ARP Request from ";
9041 static const char msg3
[] = "Creating Local ARP Cache entry ";
9042 static const char msg4
[] = "Answering ARP Request from ";
9043 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
9044 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
9045 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
9046 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
9047 intf
->ifname
, msg
, &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9048 if (msg
== msg1
) RestartARPProbing(m
, rr
);
9049 else if (msg
== msg3
) mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
9050 else if (msg
== msg4
) SendARP(m
, 2, rr
, &arp
->tpa
, &arp
->sha
, &arp
->spa
, &arp
->sha
);
9055 // 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.
9056 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
9057 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
9058 // 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.
9059 // If we see an apparently conflicting ARP, we check the sender hardware address:
9060 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
9061 // 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.
9062 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
9063 debugf("ARP from self for %.4a", &arp
->tpa
);
9066 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
9067 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9068 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9069 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
))
9071 RestartARPProbing(m
, rr
);
9072 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
9073 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
9074 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
9075 &arp
->sha
, &arp
->spa
, &arp
->tpa
, ARDisplayString(m
, rr
));
9078 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
9079 &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9080 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
9089 // Option 1 is Source Link Layer Address Option
9090 // Option 2 is Target Link Layer Address Option
9091 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
9093 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
9094 while (options < end)
9096 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
9097 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
9098 options += options[1] * 8;
9104 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
9105 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
9108 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
9113 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
9114 if (ndp
->type
== NDP_Sol
)
9116 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
9118 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9119 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9120 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
9122 static const char msg1
[] = "NDP Req from owner -- re-probing";
9123 static const char msg2
[] = "Ignoring NDP Request from ";
9124 static const char msg3
[] = "Creating Local NDP Cache entry ";
9125 static const char msg4
[] = "Answering NDP Request from ";
9126 static const char msg5
[] = "Answering NDP Probe from ";
9127 const char *const msg
= sha
&& mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
9128 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
9129 sha
&& mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
9130 spa
&& mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
9131 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
9132 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9133 if (msg
== msg1
) RestartARPProbing(m
, rr
);
9134 else if (msg
== msg3
)
9136 if (!(m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
))
9137 mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
9139 else if (msg
== msg4
) SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
9140 else if (msg
== msg5
) SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
9144 // 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.
9145 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
9146 debugf("NDP from self for %.16a", &ndp
->target
);
9149 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
9150 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
9151 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
9152 // Hence it is the NDP target address we care about, not the actual packet source address.
9153 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
9154 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
9155 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9156 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9157 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
))
9159 RestartARPProbing(m
, rr
);
9160 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
9161 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
9162 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
9165 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
9166 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
9167 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
9175 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
9176 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
9178 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
9179 mDNSBool wake
= mDNSfalse
;
9183 #define XX wake ? "Received" : "Ignoring", end-p
9184 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
9188 #define SSH_AsNumber 22
9189 static const mDNSIPPort SSH
= { { SSH_AsNumber
>> 8, SSH_AsNumber
& 0xFF } };
9192 // (a) RST is not set, AND
9193 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
9194 wake
= (!(t
->tcp
.flags
& 4) && (t
->tcp
.flags
& 3) != 1);
9196 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
9197 // except for ssh connections, where we'll wake for plain data packets too
9198 if (!mDNSSameIPPort(port
, SSH
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
9200 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
9201 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
9202 (t
->tcp
.flags
& 2) ? " SYN" : "",
9203 (t
->tcp
.flags
& 1) ? " FIN" : "",
9204 (t
->tcp
.flags
& 4) ? " RST" : "");
9209 #define ARD_AsNumber 3283
9210 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
9211 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
9212 if (udplen
>= sizeof(UDPHeader
))
9214 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
9217 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
9218 if (mDNSSameIPPort(port
, IPSECPort
))
9220 // Specifically ignore NAT keepalive packets
9221 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
9224 // Skip over the Non-ESP Marker if present
9225 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
9226 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
9227 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
9228 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
9229 if ((ike
->Version
& 0x10) == 0x10)
9231 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
9232 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
9233 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
9234 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
9239 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
9240 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
9241 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
9242 // UDP header (8 bytes)
9243 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
9244 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
9246 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
9251 case 0x3A: if (&t
->bytes
[len
] <= end
)
9253 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
9254 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
9255 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
9259 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
9265 AuthRecord
*rr
, *r2
;
9268 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
9269 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
9270 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9271 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
9273 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
9274 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
9275 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
9276 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
9277 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
9278 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
9280 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
9283 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
9284 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
9285 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
9288 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
9289 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
9295 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
9297 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
9298 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
9299 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
9300 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
9301 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
9303 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
9304 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
9305 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
9306 // since it points to a an address 14 bytes before pkt.
9307 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
9308 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
9310 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
9312 // Is ARP? Length must be at least 14 + 28 = 42 bytes
9313 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
9314 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
9315 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
9316 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
9318 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
9319 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
, &pkt
->v4
.dst
);
9320 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
9321 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
9322 if (end
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
9323 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
, 0);
9325 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
9326 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
9328 const mDNSu8
*const trans
= p
+ 54;
9329 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
, &pkt
->v6
.dst
);
9330 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
9331 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
9332 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
9333 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
9334 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
9338 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
9340 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d %#s",
9341 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, &m
->nicelabel
);
9344 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
9346 if (result
== mStatus_NameConflict
)
9347 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
9348 else if (result
== mStatus_MemFree
)
9354 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
9358 ConstructSleepProxyServerName(m
, &name
);
9359 mDNS_RegisterService(m
, srs
,
9360 &name
, &SleepProxyServiceType
, &localdomain
,
9361 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
9362 (mDNSu8
*)"", 1, // TXT data, length
9363 mDNSNULL
, 0, // Subtypes (none)
9364 mDNSInterface_Any
, // Interface ID
9365 SleepProxyServerCallback
, mDNSNULL
); // Callback and context
9367 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
9372 // Called with lock held
9373 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
)
9375 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
9376 mDNS_DropLockBeforeCallback();
9378 // If turning off SPS, close our socket
9379 // (Do this first, BEFORE calling mDNS_DeregisterService below)
9380 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
9382 // If turning off, or changing type, deregister old name
9383 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
9384 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
9386 // Record our new SPS parameters
9388 m
->SPSPortability
= port
;
9389 m
->SPSMarginalPower
= marginalpower
;
9390 m
->SPSTotalPower
= totpower
;
9392 // If turning on, open socket and advertise service
9397 m
->SPSSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
9398 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
9400 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
9402 else if (m
->SPSState
)
9404 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
9405 m
->NextScheduledSPS
= m
->timenow
;
9408 mDNS_ReclaimLockAfterCallback();
9411 // ***************************************************************************
9412 #if COMPILER_LIKES_PRAGMA_MARK
9414 #pragma mark - Startup and Shutdown
9417 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
9419 if (storage
&& numrecords
)
9422 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
9423 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
9424 storage
[numrecords
-1].next
= m
->rrcache_free
;
9425 m
->rrcache_free
= storage
;
9426 m
->rrcache_size
+= numrecords
;
9430 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
9433 mDNS_GrowCache_internal(m
, storage
, numrecords
);
9437 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
9438 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
9439 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
9445 if (!rrcachestorage
) rrcachesize
= 0;
9449 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
9450 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
9451 m
->DivertMulticastAdvertisements
= mDNSfalse
;
9452 m
->mDNSPlatformStatus
= mStatus_Waiting
;
9453 m
->UnicastPort4
= zeroIPPort
;
9454 m
->UnicastPort6
= zeroIPPort
;
9455 m
->PrimaryMAC
= zeroEthAddr
;
9456 m
->MainCallback
= Callback
;
9457 m
->MainContext
= Context
;
9458 m
->rec
.r
.resrec
.RecordType
= 0;
9460 // For debugging: To catch and report locking failures
9462 m
->mDNS_reentrancy
= 0;
9463 m
->ShutdownTime
= 0;
9464 m
->lock_rrcache
= 0;
9465 m
->lock_Questions
= 0;
9466 m
->lock_Records
= 0;
9468 // Task Scheduling variables
9469 result
= mDNSPlatformTimeInit();
9470 if (result
!= mStatus_NoError
) return(result
);
9471 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
9472 timenow
= mDNS_TimeNow_NoLock(m
);
9474 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
9475 m
->timenow_last
= timenow
;
9476 m
->NextScheduledEvent
= timenow
;
9477 m
->SuppressSending
= timenow
;
9478 m
->NextCacheCheck
= timenow
+ 0x78000000;
9479 m
->NextScheduledQuery
= timenow
+ 0x78000000;
9480 m
->NextScheduledProbe
= timenow
+ 0x78000000;
9481 m
->NextScheduledResponse
= timenow
+ 0x78000000;
9482 m
->NextScheduledNATOp
= timenow
+ 0x78000000;
9483 m
->NextScheduledSPS
= timenow
+ 0x78000000;
9484 m
->RandomQueryDelay
= 0;
9485 m
->RandomReconfirmDelay
= 0;
9487 m
->LocalRemoveEvents
= mDNSfalse
;
9488 m
->SleepState
= SleepState_Awake
;
9490 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
9491 m
->SentSleepProxyRegistration
= mDNSfalse
;
9492 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
9496 // These fields only required for mDNS Searcher...
9497 m
->Questions
= mDNSNULL
;
9498 m
->NewQuestions
= mDNSNULL
;
9499 m
->CurrentQuestion
= mDNSNULL
;
9500 m
->LocalOnlyQuestions
= mDNSNULL
;
9501 m
->NewLocalOnlyQuestions
= mDNSNULL
;
9502 m
->rrcache_size
= 0;
9503 m
->rrcache_totalused
= 0;
9504 m
->rrcache_active
= 0;
9505 m
->rrcache_report
= 10;
9506 m
->rrcache_free
= mDNSNULL
;
9508 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
9510 m
->rrcache_hash
[slot
] = mDNSNULL
;
9511 m
->rrcache_nextcheck
[slot
] = timenow
+ 0x78000000;;
9514 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
9516 // Fields below only required for mDNS Responder...
9517 m
->hostlabel
.c
[0] = 0;
9518 m
->nicelabel
.c
[0] = 0;
9519 m
->MulticastHostname
.c
[0] = 0;
9520 m
->HIHardware
.c
[0] = 0;
9521 m
->HISoftware
.c
[0] = 0;
9522 m
->ResourceRecords
= mDNSNULL
;
9523 m
->DuplicateRecords
= mDNSNULL
;
9524 m
->NewLocalRecords
= mDNSNULL
;
9525 m
->CurrentRecord
= mDNSNULL
;
9526 m
->HostInterfaces
= mDNSNULL
;
9527 m
->ProbeFailTime
= 0;
9528 m
->NumFailedProbes
= 0;
9529 m
->SuppressProbes
= 0;
9531 #ifndef UNICAST_DISABLED
9532 m
->NextuDNSEvent
= timenow
+ 0x78000000;
9533 m
->NextSRVUpdate
= timenow
+ 0x78000000;
9535 m
->DNSServers
= mDNSNULL
;
9537 m
->Router
= zeroAddr
;
9538 m
->AdvertisedV4
= zeroAddr
;
9539 m
->AdvertisedV6
= zeroAddr
;
9541 m
->AuthInfoList
= mDNSNULL
;
9543 m
->ReverseMap
.ThisQInterval
= -1;
9544 m
->StaticHostname
.c
[0] = 0;
9546 m
->Hostnames
= mDNSNULL
;
9547 m
->AutoTunnelHostAddr
.b
[0] = 0;
9548 m
->AutoTunnelHostAddrActive
= mDNSfalse
;
9549 m
->AutoTunnelLabel
.c
[0] = 0;
9551 m
->RegisterSearchDomains
= mDNSfalse
;
9552 m
->RegisterAutoTunnel6
= mDNStrue
;
9554 // NAT traversal fields
9555 m
->NATTraversals
= mDNSNULL
;
9556 m
->CurrentNATTraversal
= mDNSNULL
;
9557 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
9558 m
->retryGetAddr
= timenow
+ 0x78000000; // absolute time when we retry
9559 m
->ExternalAddress
= zerov4Addr
;
9561 m
->NATMcastRecvskt
= mDNSNULL
;
9562 m
->LastNATupseconds
= 0;
9563 m
->LastNATReplyLocalTime
= timenow
;
9564 m
->LastNATMapResultCode
= NATErr_None
;
9566 m
->UPnPInterfaceID
= 0;
9567 m
->SSDPSocket
= mDNSNULL
;
9568 m
->SSDPWANPPPConnection
= mDNSfalse
;
9569 m
->UPnPRouterPort
= zeroIPPort
;
9570 m
->UPnPSOAPPort
= zeroIPPort
;
9571 m
->UPnPRouterURL
= mDNSNULL
;
9572 m
->UPnPWANPPPConnection
= mDNSfalse
;
9573 m
->UPnPSOAPURL
= mDNSNULL
;
9574 m
->UPnPRouterAddressString
= mDNSNULL
;
9575 m
->UPnPSOAPAddressString
= mDNSNULL
;
9577 m
->SPSPortability
= 0;
9578 m
->SPSMarginalPower
= 0;
9579 m
->SPSTotalPower
= 0;
9581 m
->SPSProxyListChanged
= mDNSNULL
;
9582 m
->SPSSocket
= mDNSNULL
;
9583 m
->SPSBrowseCallback
= mDNSNULL
;
9584 m
->ProxyRecords
= 0;
9588 #if APPLE_OSX_mDNSResponder
9589 m
->TunnelClients
= mDNSNULL
;
9592 CHECK_WCF_FUNCTION(WCFConnectionNew
)
9594 m
->WCF
= WCFConnectionNew();
9595 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
9601 result
= mDNSPlatformInit(m
);
9603 #ifndef UNICAST_DISABLED
9604 // It's better to do this *after* the platform layer has set up the
9605 // interface list and security credentials
9606 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
9612 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
9614 if (m
->SPSState
== 1)
9616 domainlabel name
, newname
;
9617 domainname type
, domain
;
9618 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
9619 ConstructSleepProxyServerName(m
, &newname
);
9620 if (!SameDomainLabelCS(name
.c
, newname
.c
))
9622 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
9623 // When SleepProxyServerCallback gets the mStatus_MemFree message,
9624 // it will reregister the service under the new name
9626 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
9630 if (m
->MainCallback
)
9631 m
->MainCallback(m
, mStatus_ConfigChanged
);
9634 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
9637 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
9638 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
9641 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
, const DNSServer
* const ptr
, mDNSBool lameduck
)
9643 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
9644 cr
->resrec
.rrtype
== kDNSType_A
||
9645 cr
->resrec
.rrtype
== kDNSType_AAAA
||
9646 cr
->resrec
.rrtype
== kDNSType_SRV
;
9650 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
9651 purge
? "purging" : "reconfirming",
9652 lameduck
? "lame duck" : "new",
9653 ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
, CRDisplayString(m
, cr
));
9657 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
9658 mDNS_PurgeCacheResourceRecord(m
, cr
);
9662 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
9663 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
9667 mDNSlocal
void CacheRecordResetDNSServer(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
9669 const mDNSu32 slot
= HashSlot(&q
->qname
);
9670 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
9672 mDNSBool found
= mDNSfalse
;
9673 mDNSBool foundNew
= mDNSfalse
;
9674 DNSServer
*old
= q
->qDNSServer
;
9675 mDNSBool newQuestion
= IsQuestionNew(m
, q
);
9678 // This function is called when the DNSServer is updated to the new question. There may already be
9679 // some cache entries matching the old DNSServer and/or new DNSServer. There are four cases. In the
9680 // following table, "Yes" denotes that a cache entry was found for old/new DNSServer.
9682 // old DNSServer new DNSServer
9689 // Case 1: There are cache entries for both old and new DNSServer. We handle this case by simply
9690 // expiring the old Cache entries, deliver a RMV event (if an ADD event was delivered before)
9691 // followed by the ADD event of the cache entries corresponding to the new server. This
9692 // case happens when we pick a DNSServer, issue a query and get a valid response and create
9693 // cache entries after which it stops responding. Another query (non-duplicate) picks a different
9694 // DNSServer and creates identical cache entries (perhaps through records in Additional records).
9695 // Now if the first one expires and tries to pick the new DNSServer (the original DNSServer
9696 // is not responding) we will find cache entries corresponding to both DNSServers.
9698 // Case 2: There are no cache entries for the old DNSServer but there are some for the new DNSServer.
9699 // This means we should deliver an ADD event. Normally ADD events are delivered by
9700 // AnswerNewQuestion if it is a new question. So, we check to see if it is a new question
9701 // and if so, leave it to AnswerNewQuestion to deliver it. Otherwise, we use
9702 // AnswerQuestionsForDNSServerChanges to deliver the ADD event. This case happens when a
9703 // question picks a DNS server for which AnswerNewQuestion could not deliver an answer even
9704 // though there were potential cache entries but DNSServer did not match. Now when we
9705 // pick a new DNSServer, those cache entries may answer this question.
9707 // Case 3: There are the cache entries for the old DNSServer but none for the new. We just move
9708 // the old cache entries to point to the new DNSServer and the caller is expected to
9709 // do a purge or reconfirm to delete or validate the RDATA. We don't need to do anything
9710 // special for delivering ADD events, as it should have been done/will be done by
9711 // AnswerNewQuestion. This case happens when we picked a DNSServer, sent the query and
9712 // got a response and the cache is expired now and we are reissuing the question but the
9713 // original DNSServer does not respond.
9715 // Case 4: There are no cache entries either for the old or for the new DNSServer. There is nothing
9716 // much we can do here.
9718 // Case 2 and 3 are the most common while case 4 is possible when no DNSServers are working. Case 1
9719 // is relatively less likely to happen in practice
9721 // Temporarily set the DNSServer to look for the matching records for the new DNSServer.
9722 q
->qDNSServer
= new;
9723 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
9725 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
9727 LogInfo("CacheRecordResetDNSServer: Found cache record %##s for new DNSServer address: %#a", rp
->resrec
.name
->c
,
9728 (rp
->resrec
.rDNSServer
!= mDNSNULL
? &rp
->resrec
.rDNSServer
->addr
: mDNSNULL
));
9729 foundNew
= mDNStrue
;
9733 q
->qDNSServer
= old
;
9735 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
9737 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
9743 LogInfo("CacheRecordResetDNSServer: Flushing Resourcerecord %##s, before:%#a, after:%#a", rp
->resrec
.name
->c
,
9744 (rp
->resrec
.rDNSServer
!= mDNSNULL
? &rp
->resrec
.rDNSServer
->addr
: mDNSNULL
),
9745 (new != mDNSNULL
? &new->addr
: mDNSNULL
));
9746 mDNS_PurgeCacheResourceRecord(m
, rp
);
9749 // "q" is not a duplicate question. If it is a newQuestion, then the CRActiveQuestion can't be
9750 // possibly set as it is set only when we deliver the ADD event to the question.
9751 if (rp
->CRActiveQuestion
!= mDNSNULL
)
9753 LogMsg("CacheRecordResetDNSServer: ERROR!!: CRActiveQuestion %p set, current question %p, name %##s", rp
->CRActiveQuestion
, q
, q
->qname
.c
);
9754 rp
->CRActiveQuestion
= mDNSNULL
;
9756 // if this is a new question, then we never delivered an ADD yet, so don't deliver the RMV.
9760 LogInfo("CacheRecordResetDNSServer: resetting cache record %##s DNSServer address before:%#a,"
9761 " after:%#a, CRActiveQuestion %p", rp
->resrec
.name
->c
, (rp
->resrec
.rDNSServer
!= mDNSNULL
?
9762 &rp
->resrec
.rDNSServer
->addr
: mDNSNULL
), (new != mDNSNULL
? &new->addr
: mDNSNULL
),
9763 rp
->CRActiveQuestion
);
9764 // Though we set it to the new DNS server, the caller is *assumed* to do either a purge
9765 // or reconfirm or send out questions to the "new" server to verify whether the cached
9767 rp
->resrec
.rDNSServer
= new;
9771 // Case 1 and Case 2
9772 if ((found
&& foundNew
) || (!found
&& foundNew
))
9775 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9776 else if (QuerySuppressed(q
))
9777 LogInfo("CacheRecordResetDNSServer: deliverAddEvents not set for suppressed question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9780 LogInfo("CacheRecordResetDNSServer: deliverAddEvents set for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9781 q
->deliverAddEvents
= mDNStrue
;
9782 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9783 if (qptr
->DuplicateOf
== q
) qptr
->deliverAddEvents
= mDNStrue
;
9788 // Case 3 and Case 4
9792 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
9796 // 1. Whenever we change the DNS server, we change the message identifier also so that response
9797 // from the old server is not accepted as a response from the new server but only messages
9798 // from the new server are accepted as valid responses. We do it irrespective of whether "new"
9799 // is NULL or not. It is possible that we send two queries, no responses, pick a new DNS server
9800 // which is NULL and now the response comes back and will try to penalize the DNS server which
9801 // is NULL. By setting the messageID here, we will not accept that as a valid response.
9803 q
->TargetQID
= mDNS_NewMessageID(m
);
9805 // 2. Move the old cache records to point them at the new DNSServer so that we can deliver the ADD/RMV events
9806 // appropriately. At any point in time, we want all the cache records point only to one DNSServer for a given
9807 // question. "DNSServer" here is the DNSServer object and not the DNS server itself. It is possible to
9808 // have the same DNS server address in two objects, one scoped and another not scoped. But, the cache is per
9809 // DNSServer object. By maintaining the question and the cache entries point to the same DNSServer
9810 // always, the cache maintenance and delivery of ADD/RMV events becomes simpler.
9812 // CacheRecordResetDNSServer should be called only once for the non-duplicate question as once the cache
9813 // entries are moved to point to the new DNSServer, we don't need to call it for the duplicate question
9814 // and it is wrong to call for the duplicate question as it's decision to mark deliverAddevents will be
9818 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
9820 CacheRecordResetDNSServer(m
, q
, new);
9822 // 3. Make sure all the duplicate questions point to the same DNSServer so that delivery
9823 // of events for all of them are consistent. Duplicates for a question are always inserted
9824 // after in the list.
9825 q
->qDNSServer
= new;
9826 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9828 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
9832 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
9840 DNSServer
*ptr
, **p
= &m
->DNSServers
;
9841 const DNSServer
*oldServers
= m
->DNSServers
;
9844 debugf("uDNS_SetupDNSConfig: entry");
9846 if (m
->RegisterSearchDomains
) uDNS_RegisterSearchDomains(m
);
9850 // Let the platform layer get the current DNS information
9851 // The m->RegisterSearchDomains boolean is so that we lazily get the search domain list only on-demand
9852 // (no need to hit the network with domain enumeration queries until we actually need that information).
9853 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
9855 ptr
->penaltyTime
= 0;
9856 ptr
->flags
|= DNSServer_FlagDelete
;
9859 mDNSPlatformSetDNSConfig(m
, mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
);
9861 // Mark the records to be flushed that match a new resolver. We need to do this before
9862 // we walk the questions below where we change the DNSServer pointer of the cache
9864 FORALL_CACHERECORDS(slot
, cg
, cr
)
9866 if (cr
->resrec
.InterfaceID
) continue;
9868 // We just mark them for purge or reconfirm. We can't affect the DNSServer pointer
9869 // here as the code below that calls CacheRecordResetDNSServer relies on this
9871 // The new DNSServer may be a scoped or non-scoped one. We use the active question's
9872 // InterfaceID for looking up the right DNS server
9873 ptr
= GetServerForName(m
, cr
->resrec
.name
, cr
->CRActiveQuestion
? cr
->CRActiveQuestion
->InterfaceID
: mDNSNULL
);
9875 // Purge or Reconfirm if this cache entry would use the new DNS server
9876 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
9878 // As the DNSServers for this cache record is not the same anymore, we don't
9879 // want any new questions to pick this old value
9880 if (cr
->CRActiveQuestion
== mDNSNULL
)
9882 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s", CRDisplayString(m
, cr
));
9883 mDNS_PurgeCacheResourceRecord(m
, cr
);
9886 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNSfalse
);
9889 // Update our qDNSServer pointers before we go and free the DNSServer object memory
9890 for (q
= m
->Questions
; q
; q
=q
->next
)
9891 if (!mDNSOpaque16IsZero(q
->TargetQID
))
9895 if (q
->DuplicateOf
) continue;
9896 SetValidDNSServers(m
, q
);
9897 q
->triedAllServersOnce
= 0;
9898 s
= GetServerForQuestion(m
, q
);
9902 // If DNS Server for this question has changed, reactivate it
9903 debugf("uDNS_SetupDNSConfig: Updating DNS Server from %p %#a:%d (%##s) to %p %#a:%d (%##s) for %##s (%s)",
9904 t
, t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), t
? t
->domain
.c
: (mDNSu8
*)"",
9905 s
, s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), s
? s
->domain
.c
: (mDNSu8
*)"",
9906 q
->qname
.c
, DNSTypeName(q
->qtype
));
9908 // After we reset the DNSServer pointer on the cache records here, three things could happen:
9910 // 1) The query gets sent out and when the actual response comes back later it is possible
9911 // that the response has the same RDATA, in which case we update our cache entry.
9912 // If the response is different, then the entry will expire and a new entry gets added.
9913 // For the latter case to generate a RMV followed by ADD events, we need to reset the DNS
9914 // server here to match the question and the cache record.
9916 // 2) We might have marked the cache entries for purge above and for us to be able to generate the RMV
9917 // events for the questions, the DNSServer on the question should match the Cache Record
9919 // 3) We might have marked the cache entries for reconfirm above, for which we send the query out which is
9920 // the same as the first case above.
9922 DNSServerChangeForQuestion(m
, q
, s
);
9923 q
->unansweredQueries
= 0;
9924 // We still need to pick a new DNSServer for the questions that have been
9925 // suppressed, but it is wrong to activate the query as DNS server change
9926 // could not possibly change the status of SuppressUnusable questions
9927 if (!QuerySuppressed(q
))
9929 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9930 ActivateUnicastQuery(m
, q
, mDNStrue
);
9931 // ActivateUnicastQuery is called for duplicate questions also as it does something
9932 // special for AutoTunnel questions
9933 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9935 if (qptr
->DuplicateOf
== q
) ActivateUnicastQuery(m
, qptr
, mDNStrue
);
9941 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
9942 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), q
->DuplicateOf
, q
->SuppressUnusable
);
9943 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
9944 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
9950 if (((*p
)->flags
& DNSServer_FlagDelete
) != 0)
9952 // Scan our cache, looking for uDNS records that we would have queried this server for.
9953 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
9954 // different DNS servers can give different answers to the same question.
9956 FORALL_CACHERECORDS(slot
, cg
, cr
)
9958 if (cr
->resrec
.InterfaceID
) continue;
9959 if (cr
->resrec
.rDNSServer
== ptr
)
9961 // If we don't have an active question for this cache record, neither Purge can
9962 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
9963 // pointer on the record NULL so that we don't point to freed memory (We might dereference
9964 // DNSServer pointers from resource record for logging purposes).
9966 // If there is an active question, point to its DNSServer as long as it does not point to the
9967 // freed one. We already went through the questions above and made them point at either the
9968 // new server or NULL if there is no server and also affected the cache entries that match
9969 // this question. Hence, whenever we hit a resource record with a DNSServer that is just
9970 // about to be deleted, we should never have an active question. The code below just tries to
9971 // be careful logging messages if we ever hit this case.
9973 if (cr
->CRActiveQuestion
)
9975 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
9976 if (qptr
->qDNSServer
== mDNSNULL
)
9977 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) with DNSServer Address NULL, Server to be deleted %#a",
9978 CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), &ptr
->addr
);
9980 LogMsg("uDNS_SetupDNSConfig: Cache Record %s match: Active question %##s (%s) DNSServer Address %#a, Server to be deleted %#a",
9981 CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), &qptr
->qDNSServer
->addr
, &ptr
->addr
);
9983 if (qptr
->qDNSServer
== ptr
)
9985 qptr
->validDNSServers
= zeroOpaque64
;
9986 qptr
->qDNSServer
= mDNSNULL
;
9987 cr
->resrec
.rDNSServer
= mDNSNULL
;
9991 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
9996 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
9997 cr
->resrec
.name
, &cr
->resrec
.rDNSServer
->addr
, &ptr
->addr
);
9998 cr
->resrec
.rDNSServer
= mDNSNULL
;
10001 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNStrue
);
10005 debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
);
10006 mDNSPlatformMemFree(ptr
);
10007 NumUnicastDNSServers
--;
10011 (*p
)->flags
&= ~DNSServer_FlagNew
;
10016 // 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).
10017 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
10018 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
10019 // 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.
10020 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
10023 FORALL_CACHERECORDS(slot
, cg
, cr
) if (!cr
->resrec
.InterfaceID
) { mDNS_PurgeCacheResourceRecord(m
, cr
); count
++; }
10024 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
10025 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
10027 // Force anything that needs to get zone data to get that information again
10028 RestartRecordGetZoneData(m
);
10031 // Did our FQDN change?
10032 if (!SameDomainName(&fqdn
, &m
->FQDN
))
10034 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
10036 AssignDomainName(&m
->FQDN
, &fqdn
);
10040 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
10041 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
10047 // handle router and primary interface changes
10048 v4
= v6
= r
= zeroAddr
;
10049 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
10051 if (mDNSPlatformGetPrimaryInterface(m
, &v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
10053 mDNS_SetPrimaryInterfaceInfo(m
,
10054 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
10055 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
10056 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
10060 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
10061 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
10064 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers
);
10065 return mStatus_NoError
;
10068 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
10070 m
->mDNSPlatformStatus
= result
;
10071 if (m
->MainCallback
)
10074 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
10075 m
->MainCallback(m
, mStatus_NoError
);
10076 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
10081 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
10083 m
->CurrentRecord
= start
;
10084 while (m
->CurrentRecord
)
10086 AuthRecord
*rr
= m
->CurrentRecord
;
10087 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
10088 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
10089 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
10090 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
10091 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
10092 else if (rr
->AnnounceCount
> 1)
10094 rr
->AnnounceCount
= 1;
10095 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
10097 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10098 // new records could have been added to the end of the list as a result of that call.
10099 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
10100 m
->CurrentRecord
= rr
->next
;
10104 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
10106 NetworkInterfaceInfo
*intf
;
10111 LogInfo("mDNS_StartExit");
10112 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
10114 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0);
10116 #if APPLE_OSX_mDNSResponder
10118 CHECK_WCF_FUNCTION(WCFConnectionDealloc
)
10120 if (m
->WCF
) WCFConnectionDealloc((WCFConnection
*)m
->WCF
);
10125 #ifndef UNICAST_DISABLED
10129 // Don't need to do SleepRecordRegistrations() here
10130 // because we deregister all records and services later in this routine
10131 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
10133 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
10134 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
10135 // and we may crash because the list still contains dangling pointers.
10136 for (s
= SearchList
; s
; s
= s
->next
)
10137 while (s
->AuthRecs
)
10139 ARListElem
*dereg
= s
->AuthRecs
;
10140 s
->AuthRecs
= s
->AuthRecs
->next
;
10141 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
10146 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10147 if (intf
->Advertise
)
10148 DeadvertiseInterface(m
, intf
);
10150 // Shut down all our active NAT Traversals
10151 while (m
->NATTraversals
)
10153 NATTraversalInfo
*t
= m
->NATTraversals
;
10154 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
10156 // After stopping the NAT Traversal, we zero out the fields.
10157 // This has particularly important implications for our AutoTunnel records --
10158 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
10159 // handlers to just turn around and attempt to re-register those same records.
10160 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
10162 t
->ExternalAddress
= zerov4Addr
;
10163 t
->ExternalPort
= zeroIPPort
;
10164 t
->RequestedPort
= zeroIPPort
;
10166 t
->Result
= mStatus_NoError
;
10169 // Make sure there are nothing but deregistering records remaining in the list
10170 if (m
->CurrentRecord
)
10171 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
10173 // We're in the process of shutting down, so queries, etc. are no longer available.
10174 // Consequently, determining certain information, e.g. the uDNS update server's IP
10175 // address, will not be possible. The records on the main list are more likely to
10176 // already contain such information, so we deregister the duplicate records first.
10177 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
10178 DeregLoop(m
, m
->DuplicateRecords
);
10179 LogInfo("mDNS_StartExit: Deregistering resource records");
10180 DeregLoop(m
, m
->ResourceRecords
);
10182 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
10183 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
10184 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
10186 m
->NextScheduledResponse
= m
->timenow
;
10187 m
->SuppressSending
= 0;
10190 if (m
->ResourceRecords
) LogInfo("mDNS_StartExit: Sending final record deregistrations");
10191 else LogInfo("mDNS_StartExit: No deregistering records remain");
10193 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
10194 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
10196 // If any deregistering records remain, send their deregistration announcements before we exit
10197 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
10201 LogInfo("mDNS_StartExit: done");
10204 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
10206 mDNSu32 rrcache_active
= 0;
10207 mDNSu32 rrcache_totalused
= 0;
10211 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
10212 mDNSPlatformClose(m
);
10214 rrcache_totalused
= m
->rrcache_totalused
;
10215 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
10217 while (m
->rrcache_hash
[slot
])
10219 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
10220 while (cg
->members
)
10222 CacheRecord
*cr
= cg
->members
;
10223 cg
->members
= cg
->members
->next
;
10224 if (cr
->CRActiveQuestion
) rrcache_active
++;
10225 ReleaseCacheRecord(m
, cr
);
10227 cg
->rrcache_tail
= &cg
->members
;
10228 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
10231 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
10232 if (rrcache_active
!= m
->rrcache_active
)
10233 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active
, m
->rrcache_active
);
10235 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
10236 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
10238 LogInfo("mDNS_FinalExit: done");