1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2012 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 #include "DNSCommon.h" // Defines general DNS untility routines
27 #include "uDNS.h" // Defines entry points into unicast-specific routines
31 // Disable certain benign warnings with Microsoft compilers
32 #if (defined(_MSC_VER))
33 // Disable "conditional expression is constant" warning for debug macros.
34 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
35 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
36 #pragma warning(disable:4127)
38 // Disable "assignment within conditional expression".
39 // Other compilers understand the convention that if you place the assignment expression within an extra pair
40 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
41 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
42 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
43 #pragma warning(disable:4706)
46 #if APPLE_OSX_mDNSResponder
48 #include <WebFilterDNS/WebFilterDNS.h>
51 WCFConnection
*WCFConnectionNew(void) __attribute__((weak_import
));
52 void WCFConnectionDealloc(WCFConnection
* c
) __attribute__((weak_import
));
54 // Do we really need to define a macro for "if"?
55 #define CHECK_WCF_FUNCTION(X) if (X)
61 #endif // APPLE_OSX_mDNSResponder
63 // Forward declarations
64 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
);
65 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
);
66 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
);
67 mDNSlocal mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
68 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
69 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
);
70 mDNSlocal
void mDNS_CheckForCachedNSECS(mDNS
*const m
, DNSQuestion
*q
);
71 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
);
72 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSu32
*seq
,
73 mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
);
75 #define mDNS_KeepaliveRecord(rr) ((rr)->rrtype == kDNSType_NULL && SameDomainLabel(SecondLabel((rr)->name)->c, (mDNSu8 *)"\x0A_keepalive"))
77 // ***************************************************************************
78 #if COMPILER_LIKES_PRAGMA_MARK
79 #pragma mark - Program Constants
85 // Any records bigger than this are considered 'large' records
86 #define SmallRecordLimit 1024
88 #define kMaxUpdateCredits 10
89 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
91 mDNSexport
const char *const mDNS_DomainTypeNames
[] =
93 "b._dns-sd._udp.", // Browse
94 "db._dns-sd._udp.", // Default Browse
95 "lb._dns-sd._udp.", // Automatic Browse
96 "r._dns-sd._udp.", // Registration
97 "dr._dns-sd._udp." // Default Registration
100 #ifdef UNICAST_DISABLED
101 #define uDNS_IsActiveQuery(q, u) mDNSfalse
104 // ***************************************************************************
105 #if COMPILER_LIKES_PRAGMA_MARK
107 #pragma mark - General Utility Functions
110 // If there is a authoritative LocalOnly record that answers questions of type A, AAAA and CNAME
111 // this returns true. Main use is to handle /etc/hosts records.
112 #define LORecordAnswersAddressType(rr) ((rr)->ARType == AuthRecordLocalOnly && \
113 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
114 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
115 (rr)->resrec.rrtype == kDNSType_CNAME))
117 #define FollowCNAME(q, rr, AddRecord) (AddRecord && (q)->qtype != kDNSType_CNAME && \
118 (rr)->RecordType != kDNSRecordTypePacketNegative && \
119 (rr)->rrtype == kDNSType_CNAME)
121 mDNSlocal
void SetNextQueryStopTime(mDNS
*const m
, const DNSQuestion
*const q
)
123 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
124 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
127 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1) *(long*)0 = 0;
130 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
131 m
->NextScheduledStopTime
= q
->StopTime
;
134 mDNSexport
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
136 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
137 LogMsg("SetNextQueryTime: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
140 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1) *(long*)0 = 0;
143 if (ActiveQuestion(q
))
145 // Depending on whether this is a multicast or unicast question we want to set either:
146 // m->NextScheduledQuery = NextQSendTime(q) or
147 // m->NextuDNSEvent = NextQSendTime(q)
148 mDNSs32
*const timer
= mDNSOpaque16IsZero(q
->TargetQID
) ? &m
->NextScheduledQuery
: &m
->NextuDNSEvent
;
149 if (*timer
- NextQSendTime(q
) > 0)
150 *timer
= NextQSendTime(q
);
154 mDNSlocal
void ReleaseAuthEntity(AuthHash
*r
, AuthEntity
*e
)
156 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
158 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
160 e
->next
= r
->rrauth_free
;
162 r
->rrauth_totalused
--;
165 mDNSlocal
void ReleaseAuthGroup(AuthHash
*r
, AuthGroup
**cp
)
167 AuthEntity
*e
= (AuthEntity
*)(*cp
);
168 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp
)->name
->c
);
169 if ((*cp
)->rrauth_tail
!= &(*cp
)->members
)
170 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
171 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
172 (*cp
)->name
= mDNSNULL
;
173 *cp
= (*cp
)->next
; // Cut record from list
174 ReleaseAuthEntity(r
, e
);
177 mDNSlocal AuthEntity
*GetAuthEntity(AuthHash
*r
, const AuthGroup
*const PreserveAG
)
179 AuthEntity
*e
= mDNSNULL
;
181 if (r
->rrauth_lock
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
186 // We allocate just one AuthEntity at a time because we need to be able
187 // free them all individually which normally happens when we parse /etc/hosts into
188 // AuthHash where we add the "new" entries and discard (free) the already added
189 // entries. If we allocate as chunks, we can't free them individually.
190 AuthEntity
*storage
= mDNSPlatformMemAllocate(sizeof(AuthEntity
));
191 storage
->next
= mDNSNULL
;
192 r
->rrauth_free
= storage
;
195 // If we still have no free records, recycle all the records we can.
196 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
199 mDNSu32 oldtotalused
= r
->rrauth_totalused
;
201 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
203 AuthGroup
**cp
= &r
->rrauth_hash
[slot
];
206 if ((*cp
)->members
|| (*cp
)==PreserveAG
) cp
=&(*cp
)->next
;
207 else ReleaseAuthGroup(r
, cp
);
210 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
211 oldtotalused
- r
->rrauth_totalused
, oldtotalused
, r
->rrauth_totalused
);
214 if (r
->rrauth_free
) // If there are records in the free list, take one
217 r
->rrauth_free
= e
->next
;
218 if (++r
->rrauth_totalused
>= r
->rrauth_report
)
220 LogInfo("RR Auth now using %ld objects", r
->rrauth_totalused
);
221 if (r
->rrauth_report
< 100) r
->rrauth_report
+= 10;
222 else if (r
->rrauth_report
< 1000) r
->rrauth_report
+= 100;
223 else r
->rrauth_report
+= 1000;
225 mDNSPlatformMemZero(e
, sizeof(*e
));
233 mDNSexport AuthGroup
*AuthGroupForName(AuthHash
*r
, const mDNSu32 slot
, const mDNSu32 namehash
, const domainname
*const name
)
236 for (ag
= r
->rrauth_hash
[slot
]; ag
; ag
=ag
->next
)
237 if (ag
->namehash
== namehash
&& SameDomainName(ag
->name
, name
))
242 mDNSexport AuthGroup
*AuthGroupForRecord(AuthHash
*r
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
244 return(AuthGroupForName(r
, slot
, rr
->namehash
, rr
->name
));
247 mDNSlocal AuthGroup
*GetAuthGroup(AuthHash
*r
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
249 mDNSu16 namelen
= DomainNameLength(rr
->name
);
250 AuthGroup
*ag
= (AuthGroup
*)GetAuthEntity(r
, mDNSNULL
);
251 if (!ag
) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
252 ag
->next
= r
->rrauth_hash
[slot
];
253 ag
->namehash
= rr
->namehash
;
254 ag
->members
= mDNSNULL
;
255 ag
->rrauth_tail
= &ag
->members
;
256 ag
->NewLocalOnlyRecords
= mDNSNULL
;
257 if (namelen
> sizeof(ag
->namestorage
))
258 ag
->name
= mDNSPlatformMemAllocate(namelen
);
260 ag
->name
= (domainname
*)ag
->namestorage
;
263 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
264 ReleaseAuthEntity(r
, (AuthEntity
*)ag
);
267 AssignDomainName(ag
->name
, rr
->name
);
269 if (AuthGroupForRecord(r
, slot
, rr
)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr
->name
->c
);
270 r
->rrauth_hash
[slot
] = ag
;
271 if (AuthGroupForRecord(r
, slot
, rr
) != ag
) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr
->name
->c
);
276 // Returns the AuthGroup in which the AuthRecord was inserted
277 mDNSexport AuthGroup
*InsertAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
280 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
281 ag
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
282 if (!ag
) ag
= GetAuthGroup(r
, slot
, &rr
->resrec
); // If we don't have a AuthGroup for this name, make one now
285 LogInfo("InsertAuthRecord: inserting auth record %s from table", ARDisplayString(m
, rr
));
286 *(ag
->rrauth_tail
) = rr
; // Append this record to tail of cache slot list
287 ag
->rrauth_tail
= &(rr
->next
); // Advance tail pointer
292 mDNSexport AuthGroup
*RemoveAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
297 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
299 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
300 if (!a
) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m
, rr
)); return mDNSNULL
; }
301 rp
= &(*ag
)->members
;
308 // We don't break here, so that we can set the tail below without tracking "prev" pointers
310 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m
, rr
));
311 *rp
= (*rp
)->next
; // Cut record from list
314 // TBD: If there are no more members, release authgroup ?
315 (*ag
)->rrauth_tail
= rp
;
319 mDNSexport CacheGroup
*CacheGroupForName(const mDNS
*const m
, const mDNSu32 slot
, const mDNSu32 namehash
, const domainname
*const name
)
322 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
323 if (cg
->namehash
== namehash
&& SameDomainName(cg
->name
, name
))
328 mDNSlocal CacheGroup
*CacheGroupForRecord(const mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
330 return(CacheGroupForName(m
, slot
, rr
->namehash
, rr
->name
));
333 mDNSexport mDNSBool
mDNS_AddressIsLocalSubnet(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, const mDNSAddr
*addr
)
335 NetworkInterfaceInfo
*intf
;
337 if (addr
->type
== mDNSAddrType_IPv4
)
339 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
340 if (mDNSv4AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
341 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
342 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
343 if (((intf
->ip
.ip
.v4
.NotAnInteger
^ addr
->ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0)
347 if (addr
->type
== mDNSAddrType_IPv6
)
349 if (mDNSv6AddressIsLinkLocal(&addr
->ip
.v6
)) return(mDNStrue
);
350 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
351 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
352 if ((((intf
->ip
.ip
.v6
.l
[0] ^ addr
->ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
353 (((intf
->ip
.ip
.v6
.l
[1] ^ addr
->ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
354 (((intf
->ip
.ip
.v6
.l
[2] ^ addr
->ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
355 (((intf
->ip
.ip
.v6
.l
[3] ^ addr
->ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0))
362 mDNSlocal NetworkInterfaceInfo
*FirstInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
364 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
365 while (intf
&& intf
->InterfaceID
!= InterfaceID
) intf
= intf
->next
;
369 mDNSexport
char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
371 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
372 return(intf
? intf
->ifname
: mDNSNULL
);
375 // Caller should hold the lock
376 mDNSlocal
void GenerateNegativeResponse(mDNS
*const m
)
379 if (!m
->CurrentQuestion
) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
380 q
= m
->CurrentQuestion
;
381 LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
383 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, mDNSNULL
);
384 // We need to force the response through in the following cases
386 // a) SuppressUnusable questions that are suppressed
387 // b) Append search domains and retry the question
389 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
390 // through we use "QC_forceresponse".
391 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_forceresponse
);
392 if (m
->CurrentQuestion
== q
) { q
->ThisQInterval
= 0; } // Deactivate this question
393 // Don't touch the question after this
394 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
397 mDNSexport
void AnswerQuestionByFollowingCNAME(mDNS
*const m
, DNSQuestion
*q
, ResourceRecord
*rr
)
399 const mDNSBool selfref
= SameDomainName(&q
->qname
, &rr
->rdata
->u
.name
);
400 if (q
->CNAMEReferrals
>= 10 || selfref
)
401 LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
402 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CNAMEReferrals
, selfref
? " (Self-Referential)" : "", RRDisplayString(m
, rr
));
405 const mDNSu32 c
= q
->CNAMEReferrals
+ 1; // Stash a copy of the new q->CNAMEReferrals value
407 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
408 // themselves. Without that check we can get into a case where we have two duplicate questions,
409 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
410 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
411 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
412 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
413 // for either of them. This is not a problem for CNAME loops of two or more records because in
414 // those cases the newly re-appended question A has a different target name and therefore cannot be
415 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
417 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
418 // and track CNAMEs coming and going, we should really create a subordinate query here,
419 // which we would subsequently cancel and retract if the CNAME referral record were removed.
420 // In reality this is such a corner case we'll ignore it until someone actually needs it.
422 LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
423 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CNAMEReferrals
, RRDisplayString(m
, rr
));
425 mDNS_StopQuery_internal(m
, q
); // Stop old query
426 AssignDomainName(&q
->qname
, &rr
->rdata
->u
.name
); // Update qname
427 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
428 // If a unicast query results in a CNAME that points to a .local, we need to re-try
429 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
430 // to try this as unicast query even though it is a .local name
431 if (!mDNSOpaque16IsZero(q
->TargetQID
) && IsLocalDomain(&q
->qname
))
433 LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
434 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), RRDisplayString(m
, rr
));
435 q
->InterfaceID
= mDNSInterface_Unicast
;
437 mDNS_StartQuery_internal(m
, q
); // start new query
438 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
439 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
440 q
->CNAMEReferrals
= c
;
444 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
445 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
446 mDNSlocal
void AnswerLocalQuestionWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
448 DNSQuestion
*q
= m
->CurrentQuestion
;
449 mDNSBool followcname
;
453 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m
, rr
));
457 followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
459 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
460 if (!(rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
))
462 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
463 AddRecord
? "Add" : "Rmv", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
467 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
468 if (AddRecord
) rr
->AnsweredLocalQ
= mDNStrue
;
469 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
470 if (q
->QuestionCallback
&& !q
->NoAnswer
)
472 q
->CurrentAnswers
+= AddRecord
? 1 : -1;
473 if (LORecordAnswersAddressType(rr
))
475 if (!followcname
|| q
->ReturnIntermed
)
477 // Don't send this packet on the wire as we answered from /etc/hosts
478 q
->ThisQInterval
= 0;
479 q
->LOAddressAnswers
+= AddRecord
? 1 : -1;
480 // We can't possibly validate the entries in /etc/hosts. Hence, we
481 // report it as insecure.
482 if (q
->ValidationRequired
)
484 q
->ValidationStatus
= DNSSEC_Insecure
;
485 q
->ValidationState
= DNSSECValDone
;
487 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
489 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
490 // The callback above could have caused the question to stop. Detect that
491 // using m->CurrentQuestion
492 if (followcname
&& m
->CurrentQuestion
== q
)
493 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
498 if (q
->ValidationRequired
)
500 q
->ValidationStatus
= DNSSEC_Insecure
;
501 q
->ValidationState
= DNSSECValDone
;
503 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
506 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
509 mDNSlocal
void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
511 if (m
->CurrentQuestion
)
512 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
513 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
514 m
->CurrentQuestion
= m
->Questions
;
515 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
518 DNSQuestion
*q
= m
->CurrentQuestion
;
520 answered
= ResourceRecordAnswersQuestion(&rr
->resrec
, q
);
522 answered
= LocalOnlyRecordAnswersQuestion(rr
, q
);
524 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, AddRecord
); // MUST NOT dereference q again
525 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
526 m
->CurrentQuestion
= q
->next
;
528 m
->CurrentQuestion
= mDNSNULL
;
531 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
532 // delivers the appropriate add/remove events to listening questions:
533 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
534 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
535 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
536 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
537 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
539 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
540 // and by mDNS_Deregister_internal()
542 mDNSlocal
void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
544 if (m
->CurrentQuestion
)
545 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
546 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
548 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
549 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
552 DNSQuestion
*q
= m
->CurrentQuestion
;
553 // We are called with both LocalOnly/P2P record or a regular AuthRecord
555 answered
= ResourceRecordAnswersQuestion(&rr
->resrec
, q
);
557 answered
= LocalOnlyRecordAnswersQuestion(rr
, q
);
559 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, AddRecord
); // MUST NOT dereference q again
560 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
561 m
->CurrentQuestion
= q
->next
;
564 m
->CurrentQuestion
= mDNSNULL
;
566 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
567 if (rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
)
568 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m
, rr
, AddRecord
);
572 // ***************************************************************************
573 #if COMPILER_LIKES_PRAGMA_MARK
575 #pragma mark - Resource Record Utility Functions
578 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
580 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask) && \
581 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
582 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
583 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
585 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
586 (ResourceRecordIsValidAnswer(RR) && \
587 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
589 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
590 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
592 #define InitialAnnounceCount ((mDNSu8)8)
594 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
595 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
596 // and then if the machine fails to wake, 3 goodbye packets).
597 #define GoodbyeCount ((mDNSu8)3)
598 #define WakeupCount ((mDNSu8)18)
600 // Number of wakeups we send if WakeOnResolve is set in the question
601 #define InitialWakeOnResolveCount ((mDNSu8)3)
603 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
604 // This means that because the announce interval is doubled after sending the first packet, the first
605 // observed on-the-wire inter-packet interval between announcements is actually one second.
606 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
607 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
608 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
609 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
611 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
612 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
613 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
615 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
616 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
617 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
618 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
620 #define MaxUnansweredQueries 4
622 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
623 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
624 // TTL and rdata may differ.
625 // This is used for cache flush management:
626 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
627 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
629 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
631 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
633 mDNSlocal mDNSBool
SameResourceRecordNameClassInterface(const AuthRecord
*const r1
, const AuthRecord
*const r2
)
635 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
636 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
637 if (r1
->resrec
.InterfaceID
&&
638 r2
->resrec
.InterfaceID
&&
639 r1
->resrec
.InterfaceID
!= r2
->resrec
.InterfaceID
) return(mDNSfalse
);
641 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
&&
642 r1
->resrec
.namehash
== r2
->resrec
.namehash
&&
643 SameDomainName(r1
->resrec
.name
, r2
->resrec
.name
));
646 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
647 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
648 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
649 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
650 // so a response of any type should match, even if it is not actually the type the client plans to use.
652 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
653 // and require the rrtypes to match for the rdata to be considered potentially conflicting
654 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
656 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
657 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
658 if (pktrr
->resrec
.InterfaceID
&&
659 authrr
->resrec
.InterfaceID
&&
660 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
661 if (!(authrr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) || authrr
->WakeUp
.HMAC
.l
[0])
662 if (pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
664 pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&&
665 pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&&
666 SameDomainName(pktrr
->resrec
.name
, authrr
->resrec
.name
));
669 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
670 // This is the information that the requester believes to be correct.
671 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
672 // This is the information that we believe to be correct.
673 // We've already determined that we plan to give this answer on this interface
674 // (either the record is non-specific, or it is specific to this interface)
675 // so now we just need to check the name, type, class, rdata and TTL.
676 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
678 // If RR signature is different, or data is different, then don't suppress our answer
679 if (!IdenticalResourceRecord(&ka
->resrec
, &rr
->resrec
)) return(mDNSfalse
);
681 // If the requester's indicated TTL is less than half the real TTL,
682 // we need to give our answer before the requester's copy expires.
683 // If the requester's indicated TTL is at least half the real TTL,
684 // then we can suppress our answer this time.
685 // If the requester's indicated TTL is greater than the TTL we believe,
686 // then that's okay, and we don't need to do anything about it.
687 // (If two responders on the network are offering the same information,
688 // that's okay, and if they are offering the information with different TTLs,
689 // the one offering the lower TTL should defer to the one offering the higher TTL.)
690 return (mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
693 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
695 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
697 if ((rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
> mDNSPlatformOneSecond
* 10)
699 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr
->ProbeCount
, (rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
, ARDisplayString(m
, rr
));
700 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m
->SuppressProbes
, m
->timenow
, m
->SuppressProbes
- m
->timenow
);
702 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
703 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
704 // Some defensive code:
705 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
706 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
707 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
708 if (m
->NextScheduledProbe
- m
->timenow
< 0)
709 m
->NextScheduledProbe
= m
->timenow
;
711 else if (rr
->AnnounceCount
&& (ResourceRecordIsValidAnswer(rr
) || rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
))
713 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
714 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
718 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
720 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
721 rr
->ThisAPInterval
= rr
->AddressProxy
.type
? mDNSPlatformOneSecond
: DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
723 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
724 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
725 // records that are going to probe, then we delay its first announcement so that it will
726 // go out synchronized with the first announcement for the other records that *are* probing.
727 // This is a minor performance tweak that helps keep groups of related records synchronized together.
728 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
729 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
730 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
731 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
732 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
736 // If we have no probe suppression time set, or it is in the past, set it now
737 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
739 // To allow us to aggregate probes when a group of services are registered together,
740 // the first probe is delayed 1/4 second. This means the common-case behaviour is:
741 // 1/4 second wait; probe
742 // 1/4 second wait; probe
743 // 1/4 second wait; probe
744 // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
745 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
747 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
748 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
749 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledProbe
);
750 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
751 m
->SuppressProbes
= m
->timenow
;
753 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
754 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
755 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledQuery
);
756 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
757 m
->SuppressProbes
= m
->timenow
;
759 // except... don't expect to be able to send before the m->SuppressSending timer fires
760 if (m
->SuppressSending
&& m
->SuppressProbes
- m
->SuppressSending
< 0)
761 m
->SuppressProbes
= NonZeroTime(m
->SuppressSending
);
763 if (m
->SuppressProbes
- m
->timenow
> mDNSPlatformOneSecond
* 8)
765 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
766 m
->SuppressProbes
- m
->timenow
,
767 m
->NextScheduledProbe
- m
->timenow
,
768 m
->NextScheduledQuery
- m
->timenow
,
770 m
->SuppressSending
- m
->timenow
);
771 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
774 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
776 else if (m
->SuppressProbes
&& m
->SuppressProbes
- m
->timenow
>= 0)
777 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
+ DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
779 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
781 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
782 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
783 // After three probes one second apart with no answer, we conclude the client is now sleeping
784 // and we can begin broadcasting our announcements to take over ownership of that IP address.
785 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
786 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
787 if (rr
->AddressProxy
.type
) rr
->LastAPTime
= m
->timenow
;
789 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
790 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
791 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
792 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
793 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
794 if (m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
795 if (rr
->WakeUp
.HMAC
.l
[0] && rr
->resrec
.rrtype
== kDNSType_AAAA
)
796 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
+ mDNSPlatformOneSecond
* 10;
798 // Set LastMCTime to now, to inhibit multicast responses
799 // (no need to send additional multicast responses when we're announcing anyway)
800 rr
->LastMCTime
= m
->timenow
;
801 rr
->LastMCInterface
= mDNSInterfaceMark
;
803 SetNextAnnounceProbeTime(m
, rr
);
806 mDNSlocal
const domainname
*SetUnicastTargetToHostName(mDNS
*const m
, AuthRecord
*rr
)
808 const domainname
*target
;
811 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
812 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
813 // with the port number in our advertised SRV record automatically tracking the external mapped port.
814 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
815 if (!AuthInfo
|| !AuthInfo
->AutoTunnel
) rr
->AutoTarget
= Target_AutoHostAndNATMAP
;
818 target
= GetServiceTarget(m
, rr
);
819 if (!target
|| target
->c
[0] == 0)
821 // defer registration until we've got a target
822 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m
, rr
));
823 rr
->state
= regState_NoTarget
;
828 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target
->c
, ARDisplayString(m
,rr
));
833 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
834 // Eventually we should unify this with GetServiceTarget() in uDNS.c
835 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
837 domainname
*const target
= GetRRDomainNameTarget(&rr
->resrec
);
838 const domainname
*newname
= &m
->MulticastHostname
;
840 if (!target
) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr
->resrec
.rrtype
));
842 if (!(rr
->ForceMCast
|| rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
|| IsLocalDomain(&rr
->namestorage
)))
844 const domainname
*const n
= SetUnicastTargetToHostName(m
, rr
);
846 else { target
->c
[0] = 0; SetNewRData(&rr
->resrec
, mDNSNULL
, 0); return; }
849 if (target
&& SameDomainName(target
, newname
))
850 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
->c
, target
->c
);
852 if (target
&& !SameDomainName(target
, newname
))
854 AssignDomainName(target
, newname
);
855 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
857 // If we're in the middle of probing this record, we need to start again,
858 // because changing its rdata may change the outcome of the tie-breaker.
859 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
860 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
862 // If we've announced this record, we really should send a goodbye packet for the old rdata before
863 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
864 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
865 if (rr
->RequireGoodbye
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
866 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
867 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
869 rr
->AnnounceCount
= InitialAnnounceCount
;
870 rr
->RequireGoodbye
= mDNSfalse
;
871 InitializeLastAPTime(m
, rr
);
875 mDNSlocal
void AcknowledgeRecord(mDNS
*const m
, AuthRecord
*const rr
)
877 if (rr
->RecordCallback
)
879 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
880 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
881 rr
->Acknowledged
= mDNStrue
;
882 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
883 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
884 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
888 mDNSexport
void ActivateUnicastRegistration(mDNS
*const m
, AuthRecord
*const rr
)
890 // Make sure that we don't activate the SRV record and associated service records, if it is in
891 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
892 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
893 // the target becomes available, the records will be reregistered.
894 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
896 AuthRecord
*srvRR
= mDNSNULL
;
897 if (rr
->resrec
.rrtype
== kDNSType_PTR
)
898 srvRR
= rr
->Additional1
;
899 else if (rr
->resrec
.rrtype
== kDNSType_TXT
)
900 srvRR
= rr
->DependentOn
;
903 if (srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
905 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
909 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
910 ARDisplayString(m
, srvRR
), srvRR
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
911 rr
->state
= srvRR
->state
;
916 if (rr
->state
== regState_NoTarget
)
918 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m
, rr
));
921 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
922 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
923 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
924 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
925 // 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.
926 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
928 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m
, rr
), rr
->state
);
929 rr
->state
= regState_DeregPending
;
933 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m
, rr
), rr
->state
);
934 rr
->state
= regState_Pending
;
937 rr
->AnnounceCount
= 0;
938 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
939 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
940 rr
->expire
= 0; // Forget about all the leases, start fresh
941 rr
->uselease
= mDNStrue
;
942 rr
->updateid
= zeroID
;
943 rr
->SRVChanged
= mDNSfalse
;
944 rr
->updateError
= mStatus_NoError
;
945 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
946 // The records might already be registered with the server and hence could have NAT state.
947 if (rr
->NATinfo
.clientContext
)
949 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
950 rr
->NATinfo
.clientContext
= mDNSNULL
;
952 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
953 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
954 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
955 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
958 // Two records qualify to be local duplicates if:
959 // (a) the RecordTypes are the same, or
960 // (b) one is Unique and the other Verified
961 // (c) either is in the process of deregistering
962 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
963 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
964 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
966 #define RecordIsLocalDuplicate(A,B) \
967 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
969 mDNSlocal AuthRecord
*CheckAuthIdenticalRecord(AuthHash
*r
, AuthRecord
*rr
)
974 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
976 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
977 if (!a
) return mDNSNULL
;
978 rp
= &(*ag
)->members
;
981 if (!RecordIsLocalDuplicate(*rp
, rr
))
985 if ((*rp
)->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
987 (*rp
)->AnnounceCount
= 0;
996 mDNSlocal mDNSBool
CheckAuthRecordConflict(AuthHash
*r
, AuthRecord
*rr
)
1001 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1003 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
1004 if (!a
) return mDNSfalse
;
1005 rp
= &(*ag
)->members
;
1008 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
1009 const AuthRecord
*s2
= (*rp
)->RRSet
? (*rp
)->RRSet
: *rp
;
1010 if (s1
!= s2
&& SameResourceRecordSignature((*rp
), rr
) && !IdenticalSameNameRecord(&(*rp
)->resrec
, &rr
->resrec
))
1018 // checks to see if "rr" is already present
1019 mDNSlocal AuthRecord
*CheckAuthSameRecord(AuthHash
*r
, AuthRecord
*rr
)
1022 AuthGroup
**ag
= &a
;
1024 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1026 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
1027 if (!a
) return mDNSNULL
;
1028 rp
= &(*ag
)->members
;
1041 // Exported so uDNS.c can call this
1042 mDNSexport mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
1044 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
1046 AuthRecord
**p
= &m
->ResourceRecords
;
1047 AuthRecord
**d
= &m
->DuplicateRecords
;
1049 if ((mDNSs32
)rr
->resrec
.rroriginalttl
<= 0)
1050 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr
->resrec
.rroriginalttl
, ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1052 if (!rr
->resrec
.RecordType
)
1053 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1055 if (m
->ShutdownTime
)
1056 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m
, rr
)); return(mStatus_ServiceNotRunning
); }
1058 if (m
->DivertMulticastAdvertisements
&& !AuthRecord_uDNS(rr
))
1060 mDNSInterfaceID previousID
= rr
->resrec
.InterfaceID
;
1061 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1063 rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
1064 rr
->ARType
= AuthRecordLocalOnly
;
1066 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
1068 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1069 if (intf
&& !intf
->Advertise
) { rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
; rr
->ARType
= AuthRecordLocalOnly
; }
1071 if (rr
->resrec
.InterfaceID
!= previousID
)
1072 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m
, rr
));
1075 if (RRLocalOnly(rr
))
1077 if (CheckAuthSameRecord(&m
->rrauth
, rr
))
1079 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1080 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1081 return(mStatus_AlreadyRegistered
);
1086 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1089 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1090 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1091 return(mStatus_AlreadyRegistered
);
1095 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
1098 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1099 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1100 return(mStatus_AlreadyRegistered
);
1103 if (rr
->DependentOn
)
1105 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1106 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1109 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1110 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1111 return(mStatus_Invalid
);
1113 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
)))
1115 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1116 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
1117 return(mStatus_Invalid
);
1121 // If this resource record is referencing a specific interface, make sure it exists.
1122 // Skip checks for LocalOnly and P2P as they are not valid InterfaceIDs. Also, for scoped
1123 // entries in /etc/hosts skip that check as that interface may not be valid at this time.
1124 if (rr
->resrec
.InterfaceID
&& rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
)
1126 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1129 debugf("mDNS_Register_internal: Bogus InterfaceID %p in resource record", rr
->resrec
.InterfaceID
);
1130 return(mStatus_BadReferenceErr
);
1134 rr
->next
= mDNSNULL
;
1136 // Field Group 1: The actual information pertaining to this resource record
1137 // Set up by client prior to call
1139 // Field Group 2: Persistent metadata for Authoritative Records
1140 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1141 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1142 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1143 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1144 // rr->Callback = already set in mDNS_SetupResourceRecord
1145 // rr->Context = already set in mDNS_SetupResourceRecord
1146 // rr->RecordType = already set in mDNS_SetupResourceRecord
1147 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1148 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1149 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1150 if (rr
->AutoTarget
&& target
) target
->c
[0] = 0;
1152 // Field Group 3: Transient state for Authoritative Records
1153 rr
->Acknowledged
= mDNSfalse
;
1154 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1155 rr
->AnnounceCount
= InitialAnnounceCount
;
1156 rr
->RequireGoodbye
= mDNSfalse
;
1157 rr
->AnsweredLocalQ
= mDNSfalse
;
1158 rr
->IncludeInProbe
= mDNSfalse
;
1159 rr
->ImmedUnicast
= mDNSfalse
;
1160 rr
->SendNSECNow
= mDNSNULL
;
1161 rr
->ImmedAnswer
= mDNSNULL
;
1162 rr
->ImmedAdditional
= mDNSNULL
;
1163 rr
->SendRNow
= mDNSNULL
;
1164 rr
->v4Requester
= zerov4Addr
;
1165 rr
->v6Requester
= zerov6Addr
;
1166 rr
->NextResponse
= mDNSNULL
;
1167 rr
->NR_AnswerTo
= mDNSNULL
;
1168 rr
->NR_AdditionalTo
= mDNSNULL
;
1169 if (!rr
->AutoTarget
) InitializeLastAPTime(m
, rr
);
1170 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1171 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1172 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1173 rr
->NewRData
= mDNSNULL
;
1174 rr
->newrdlength
= 0;
1175 rr
->UpdateCallback
= mDNSNULL
;
1176 rr
->UpdateCredits
= kMaxUpdateCredits
;
1177 rr
->NextUpdateCredit
= 0;
1178 rr
->UpdateBlocked
= 0;
1180 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1181 if (rr
->WakeUp
.HMAC
.l
[0] && !rr
->AddressProxy
.type
) rr
->AnnounceCount
= 2;
1183 // Field Group 4: Transient uDNS state for Authoritative Records
1184 rr
->state
= regState_Zero
;
1188 rr
->updateid
= zeroID
;
1189 rr
->updateIntID
= zeroOpaque64
;
1190 rr
->zone
= rr
->resrec
.name
;
1195 rr
->InFlightRData
= 0;
1196 rr
->InFlightRDLen
= 0;
1197 rr
->QueuedRData
= 0;
1198 rr
->QueuedRDLen
= 0;
1199 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1200 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1201 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1202 // times with different values if the external NAT port changes during the lifetime of the service registration.
1203 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1205 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1206 // rr->resrec.name->c = MUST be set by client
1207 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1208 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1209 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1210 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1212 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1213 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1214 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1215 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rr
->resrec
.rdlength
== 0) { rr
->resrec
.rdlength
= 1; rr
->resrec
.rdata
->u
.txt
.c
[0] = 0; }
1219 SetTargetToHostName(m
, rr
); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1220 #ifndef UNICAST_DISABLED
1221 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1222 // 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.
1223 if (rr
->state
== regState_NoTarget
)
1225 // Initialize the target so that we don't crash while logging etc.
1226 domainname
*tar
= GetRRDomainNameTarget(&rr
->resrec
);
1227 if (tar
) tar
->c
[0] = 0;
1228 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m
, rr
));
1234 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
1235 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
1238 if (!ValidateDomainName(rr
->resrec
.name
))
1239 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1241 // Don't do this until *after* we've set rr->resrec.rdlength
1242 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
1243 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1245 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
1246 rr
->resrec
.rdatahash
= target
? DomainNameHashValue(target
) : RDataHashValue(&rr
->resrec
);
1248 if (RRLocalOnly(rr
))
1250 // If this is supposed to be unique, make sure we don't have any name conflicts.
1251 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1252 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1253 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1254 // Hence, just bail out.
1255 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1257 if (CheckAuthRecordConflict(&m
->rrauth
, rr
))
1259 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m
, rr
), rr
, rr
->resrec
.InterfaceID
);
1260 return mStatus_NameConflict
;
1265 // For uDNS records, we don't support duplicate checks at this time.
1266 #ifndef UNICAST_DISABLED
1267 if (AuthRecord_uDNS(rr
))
1269 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1270 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1271 // 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.
1272 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1273 while (*p
) p
=&(*p
)->next
;
1275 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1277 rr
->AnnounceCount
= 0;
1278 if (rr
->state
!= regState_NoTarget
) ActivateUnicastRegistration(m
, rr
);
1279 return(mStatus_NoError
); // <--- Note: For unicast records, code currently bails out at this point
1283 // Now that we've finished building our new record, make sure it's not identical to one we already have
1284 if (RRLocalOnly(rr
))
1287 rr
->AnnounceCount
= 0;
1288 r
= CheckAuthIdenticalRecord(&m
->rrauth
, rr
);
1292 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1293 if (RecordIsLocalDuplicate(r
, rr
))
1295 if (r
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) r
->AnnounceCount
= 0;
1302 debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m
,rr
));
1304 // If the previous copy of this record is already verified unique,
1305 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1306 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1307 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1308 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
1313 debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m
,rr
));
1314 if (RRLocalOnly(rr
))
1317 ag
= InsertAuthRecord(m
, &m
->rrauth
, rr
);
1318 if (ag
&& !ag
->NewLocalOnlyRecords
) {
1319 m
->NewLocalOnlyRecords
= mDNStrue
;
1320 ag
->NewLocalOnlyRecords
= rr
;
1322 // No probing for LocalOnly records, Acknowledge them right away
1323 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1324 AcknowledgeRecord(m
, rr
);
1325 return(mStatus_NoError
);
1329 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1334 if (!AuthRecord_uDNS(rr
)) // This check is superfluous, given that for unicast records we (currently) bail out above
1336 // For records that are not going to probe, acknowledge them right away
1337 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
1338 AcknowledgeRecord(m
, rr
);
1340 // Adding a record may affect whether or not we should sleep
1341 mDNS_UpdateAllowSleep(m
);
1344 return(mStatus_NoError
);
1347 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
1349 m
->ProbeFailTime
= m
->timenow
;
1350 m
->NumFailedProbes
++;
1351 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1352 // If a bunch of hosts have all been configured with the same name, then they'll all
1353 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1354 // up to name-10. After that they'll start adding random increments in the range 1-100,
1355 // so they're more likely to branch out in the available namespace and settle on a set of
1356 // unique names quickly. If after five more tries the host is still conflicting, then we
1357 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1358 if (m
->NumFailedProbes
>= 15)
1360 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
1361 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1362 m
->NumFailedProbes
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1366 mDNSlocal
void CompleteRDataUpdate(mDNS
*const m
, AuthRecord
*const rr
)
1368 RData
*OldRData
= rr
->resrec
.rdata
;
1369 mDNSu16 OldRDLen
= rr
->resrec
.rdlength
;
1370 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
1371 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
1372 if (rr
->UpdateCallback
)
1373 rr
->UpdateCallback(m
, rr
, OldRData
, OldRDLen
); // ... and let the client know
1376 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1377 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1378 // Exported so uDNS.c can call this
1379 mDNSexport mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
1382 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
1383 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
1384 mDNSBool dupList
= mDNSfalse
;
1386 if (RRLocalOnly(rr
))
1389 AuthGroup
**ag
= &a
;
1391 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1393 a
= AuthGroupForRecord(&m
->rrauth
, slot
, &rr
->resrec
);
1394 if (!a
) return mDNSfalse
;
1395 rp
= &(*ag
)->members
;
1396 while (*rp
&& *rp
!= rr
) rp
=&(*rp
)->next
;
1401 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1406 // We found our record on the main list. See if there are any duplicates that need special handling.
1407 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
1409 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1410 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1411 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
) if (RecordIsLocalDuplicate(r2
, rr
)) r2
->ProbeCount
= 0xFF;
1415 // Before we delete the record (and potentially send a goodbye packet)
1416 // first see if we have a record on the duplicate list ready to take over from it.
1417 AuthRecord
**d
= &m
->DuplicateRecords
;
1418 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
1421 AuthRecord
*dup
= *d
;
1422 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1423 dup
, rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1424 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
1425 if (RRLocalOnly(rr
))
1427 dup
->next
= mDNSNULL
;
1428 if (!InsertAuthRecord(m
, &m
->rrauth
, dup
)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m
, dup
));
1432 dup
->next
= rr
->next
; // And then...
1433 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
1435 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
1436 dup
->ProbeCount
= rr
->ProbeCount
;
1437 dup
->AnnounceCount
= rr
->AnnounceCount
;
1438 dup
->RequireGoodbye
= rr
->RequireGoodbye
;
1439 dup
->AnsweredLocalQ
= rr
->AnsweredLocalQ
;
1440 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
1441 dup
->ImmedUnicast
= rr
->ImmedUnicast
;
1442 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
1443 dup
->v4Requester
= rr
->v4Requester
;
1444 dup
->v6Requester
= rr
->v6Requester
;
1445 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
1446 dup
->LastAPTime
= rr
->LastAPTime
;
1447 dup
->LastMCTime
= rr
->LastMCTime
;
1448 dup
->LastMCInterface
= rr
->LastMCInterface
;
1449 dup
->Private
= rr
->Private
;
1450 dup
->state
= rr
->state
;
1451 rr
->RequireGoodbye
= mDNSfalse
;
1452 rr
->AnsweredLocalQ
= mDNSfalse
;
1458 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1459 p
= &m
->DuplicateRecords
;
1460 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1461 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1464 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1465 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1466 // also that have been marked above in this function. In that case, we come here and if we don't
1467 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1468 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1470 rr
->WakeUp
.HMAC
= zeroEthAddr
;
1471 rr
->RequireGoodbye
= mDNSfalse
;
1474 if (*p
) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1475 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1480 // No need to log an error message if we already know this is a potentially repeated deregistration
1481 if (drt
!= mDNS_Dereg_repeat
)
1482 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr
, ARDisplayString(m
,rr
));
1483 return(mStatus_BadReferenceErr
);
1486 // If this is a shared record and we've announced it at least once,
1487 // we need to retract that announcement before we delete the record
1489 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1490 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1491 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1492 // mechanism to cope with the client callback modifying the question list while that's happening.
1493 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1494 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1495 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1496 // records, thereby invoking yet more callbacks, without limit.
1497 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1498 // actual goodbye packets.
1500 #ifndef UNICAST_DISABLED
1501 if (AuthRecord_uDNS(rr
))
1503 if (rr
->RequireGoodbye
)
1505 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1506 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1507 m
->LocalRemoveEvents
= mDNStrue
;
1508 uDNS_DeregisterRecord(m
, rr
);
1509 // At this point unconditionally we bail out
1510 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1511 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1512 // process and will complete asynchronously. Either way we don't need to do anything more here.
1513 return(mStatus_NoError
);
1515 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1516 // from the server. In that case, if the records have been part of a group update, clear the
1517 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1518 rr
->updateid
= zeroID
;
1520 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1521 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1522 // This happens today when we turn on/off interface where we get multiple network transitions
1523 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1524 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1525 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1526 // NAT state here takes care of the case where we did not send goodbyes at all.
1527 if (rr
->NATinfo
.clientContext
)
1529 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1530 rr
->NATinfo
.clientContext
= mDNSNULL
;
1532 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1533 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1535 #endif // UNICAST_DISABLED
1537 if (RecordType
== kDNSRecordTypeUnregistered
)
1538 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m
, rr
));
1539 else if (RecordType
== kDNSRecordTypeDeregistering
)
1541 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m
, rr
));
1542 return(mStatus_BadReferenceErr
);
1545 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1546 // We may want to consider changing this code so that we generate local-only question "rmv"
1547 // events (and maybe goodbye packets too) for unique records as well as for shared records
1548 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1549 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1550 // clause will execute here and the record will be cut from the list.
1551 if (rr
->WakeUp
.HMAC
.l
[0] ||
1552 (RecordType
== kDNSRecordTypeShared
&& (rr
->RequireGoodbye
|| rr
->AnsweredLocalQ
)))
1554 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m
, rr
));
1555 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1556 rr
->resrec
.rroriginalttl
= 0;
1557 rr
->AnnounceCount
= rr
->WakeUp
.HMAC
.l
[0] ? WakeupCount
: (drt
== mDNS_Dereg_rapid
) ? 1 : GoodbyeCount
;
1558 rr
->ThisAPInterval
= mDNSPlatformOneSecond
* 2;
1559 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1560 m
->LocalRemoveEvents
= mDNStrue
;
1561 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
1562 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
1566 if (!dupList
&& RRLocalOnly(rr
))
1568 AuthGroup
*ag
= RemoveAuthRecord(m
, &m
->rrauth
, rr
);
1569 if (ag
->NewLocalOnlyRecords
== rr
) ag
->NewLocalOnlyRecords
= rr
->next
;
1573 *p
= rr
->next
; // Cut this record from the list
1574 if (m
->NewLocalRecords
== rr
) m
->NewLocalRecords
= rr
->next
;
1576 // If someone is about to look at this, bump the pointer forward
1577 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
1578 rr
->next
= mDNSNULL
;
1580 // Should we generate local remove events here?
1581 // i.e. something like:
1582 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1584 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m
, rr
));
1585 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
1587 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
1588 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1589 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1591 // If we have an update queued up which never executed, give the client a chance to free that memory
1592 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
1595 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1596 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1597 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1598 // so any attempt to touch rr after this is likely to lead to a crash.
1599 if (drt
!= mDNS_Dereg_conflict
)
1601 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1602 LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m
, rr
));
1603 if (rr
->RecordCallback
)
1604 rr
->RecordCallback(m
, rr
, mStatus_MemFree
); // MUST NOT touch rr after this
1605 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1609 RecordProbeFailure(m
, rr
);
1610 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1611 if (rr
->RecordCallback
)
1612 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
); // MUST NOT touch rr after this
1613 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1614 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1615 // Note that with all the client callbacks going on, by the time we get here all the
1616 // records we marked may have been explicitly deregistered by the client anyway.
1617 r2
= m
->DuplicateRecords
;
1620 if (r2
->ProbeCount
!= 0xFF)
1626 mDNS_Deregister_internal(m
, r2
, mDNS_Dereg_conflict
);
1627 // As this is a duplicate record, it will be unlinked from the list
1629 r2
= m
->DuplicateRecords
;
1634 mDNS_UpdateAllowSleep(m
);
1635 return(mStatus_NoError
);
1638 // ***************************************************************************
1639 #if COMPILER_LIKES_PRAGMA_MARK
1641 #pragma mark - Packet Sending Functions
1644 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
1646 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
1649 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1650 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1651 // The referenced record will definitely be acceptable (by recursive application of this rule)
1652 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
1653 rr
->NR_AdditionalTo
= add
;
1654 *nrpp
= &rr
->NextResponse
;
1656 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1659 mDNSlocal
void AddAdditionalsToResponseList(mDNS
*const m
, AuthRecord
*ResponseRecords
, AuthRecord
***nrpp
, const mDNSInterfaceID InterfaceID
)
1661 AuthRecord
*rr
, *rr2
;
1662 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
1664 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1665 // later in the "for" loop, and we will follow further "additional" links then.)
1666 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
1667 AddRecordToResponseList(nrpp
, rr
->Additional1
, rr
);
1669 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
1670 AddRecordToResponseList(nrpp
, rr
->Additional2
, rr
);
1672 // For SRV records, automatically add the Address record(s) for the target host
1673 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
1675 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
1676 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
1677 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
1678 rr
->resrec
.rdatahash
== rr2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
1679 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, rr2
->resrec
.name
))
1680 AddRecordToResponseList(nrpp
, rr2
, rr
);
1682 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
)) // For A or AAAA, put counterpart as additional
1684 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
1685 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
1686 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
1687 rr
->resrec
.namehash
== rr2
->resrec
.namehash
&& // ... and have the same name
1688 SameDomainName(rr
->resrec
.name
, rr2
->resrec
.name
))
1689 AddRecordToResponseList(nrpp
, rr2
, rr
);
1691 else if (rr
->resrec
.rrtype
== kDNSType_PTR
) // For service PTR, see if we want to add DeviceInfo record
1693 if (ResourceRecordIsValidInterfaceAnswer(&m
->DeviceInfo
, InterfaceID
) &&
1694 SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
1695 AddRecordToResponseList(nrpp
, &m
->DeviceInfo
, rr
);
1700 mDNSlocal
void SendDelayedUnicastResponse(mDNS
*const m
, const mDNSAddr
*const dest
, const mDNSInterfaceID InterfaceID
)
1703 AuthRecord
*ResponseRecords
= mDNSNULL
;
1704 AuthRecord
**nrp
= &ResponseRecords
;
1705 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
1707 // Make a list of all our records that need to be unicast to this destination
1708 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1710 // If we find we can no longer unicast this answer, clear ImmedUnicast
1711 if (rr
->ImmedAnswer
== mDNSInterfaceMark
||
1712 mDNSSameIPv4Address(rr
->v4Requester
, onesIPv4Addr
) ||
1713 mDNSSameIPv6Address(rr
->v6Requester
, onesIPv6Addr
) )
1714 rr
->ImmedUnicast
= mDNSfalse
;
1716 if (rr
->ImmedUnicast
&& rr
->ImmedAnswer
== InterfaceID
)
1718 if ((dest
->type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->v4Requester
, dest
->ip
.v4
)) ||
1719 (dest
->type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->v6Requester
, dest
->ip
.v6
)))
1721 rr
->ImmedAnswer
= mDNSNULL
; // Clear the state fields
1722 rr
->ImmedUnicast
= mDNSfalse
;
1723 rr
->v4Requester
= zerov4Addr
;
1724 rr
->v6Requester
= zerov6Addr
;
1726 // Only sent records registered for P2P over P2P interfaces
1727 if (intf
&& !mDNSPlatformValidRecordForInterface(rr
, intf
))
1729 LogInfo("SendDelayedUnicastResponse: Not sending %s, on %s", ARDisplayString(m
, rr
), InterfaceNameForID(m
, InterfaceID
));
1733 if (rr
->NextResponse
== mDNSNULL
&& nrp
!= &rr
->NextResponse
) // rr->NR_AnswerTo
1734 { rr
->NR_AnswerTo
= (mDNSu8
*)~0; *nrp
= rr
; nrp
= &rr
->NextResponse
; }
1739 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
1741 while (ResponseRecords
)
1743 mDNSu8
*responseptr
= m
->omsg
.data
;
1745 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
1747 // Put answers in the packet
1748 while (ResponseRecords
&& ResponseRecords
->NR_AnswerTo
)
1750 rr
= ResponseRecords
;
1751 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1752 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
1753 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
);
1754 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
1755 if (!newptr
&& m
->omsg
.h
.numAnswers
) break; // If packet full, send it now
1756 if (newptr
) responseptr
= newptr
;
1757 ResponseRecords
= rr
->NextResponse
;
1758 rr
->NextResponse
= mDNSNULL
;
1759 rr
->NR_AnswerTo
= mDNSNULL
;
1760 rr
->NR_AdditionalTo
= mDNSNULL
;
1761 rr
->RequireGoodbye
= mDNStrue
;
1764 // Add additionals, if there's space
1765 while (ResponseRecords
&& !ResponseRecords
->NR_AnswerTo
)
1767 rr
= ResponseRecords
;
1768 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1769 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
1770 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
1771 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
1773 if (newptr
) responseptr
= newptr
;
1774 if (newptr
&& m
->omsg
.h
.numAnswers
) rr
->RequireGoodbye
= mDNStrue
;
1775 else if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
->ImmedAnswer
= mDNSInterfaceMark
;
1776 ResponseRecords
= rr
->NextResponse
;
1777 rr
->NextResponse
= mDNSNULL
;
1778 rr
->NR_AnswerTo
= mDNSNULL
;
1779 rr
->NR_AdditionalTo
= mDNSNULL
;
1782 if (m
->omsg
.h
.numAnswers
)
1783 mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, InterfaceID
, mDNSNULL
, dest
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
1787 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
1788 // and the client's mStatus_MemFree callback will have been invoked
1789 mDNSexport
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
1791 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m
, rr
));
1792 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
1793 // it should go ahead and immediately dispose of this registration
1794 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
1795 rr
->RequireGoodbye
= mDNSfalse
;
1796 rr
->WakeUp
.HMAC
= zeroEthAddr
;
1797 if (rr
->AnsweredLocalQ
) { AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
); rr
->AnsweredLocalQ
= mDNSfalse
; }
1798 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
); // Don't touch rr after this
1801 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
1802 // any deregistering records that remain in the m->ResourceRecords list.
1803 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
1804 // which may change the record list and/or question list.
1805 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1806 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
1808 if (m
->CurrentRecord
)
1809 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
1810 m
->CurrentRecord
= m
->ResourceRecords
;
1812 while (m
->CurrentRecord
)
1814 AuthRecord
*rr
= m
->CurrentRecord
;
1815 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1816 CompleteDeregistration(m
, rr
); // Don't touch rr after this
1818 m
->CurrentRecord
= rr
->next
;
1822 mDNSlocal mStatus
GetLabelDecimalValue(const mDNSu8
*const src
, mDNSu8
*dst
)
1825 if (src
[0] < 1 || src
[0] > 3) return(mStatus_Invalid
);
1826 for (i
=1; i
<=src
[0]; i
++)
1828 if (src
[i
] < '0' || src
[i
] > '9') return(mStatus_Invalid
);
1829 val
= val
* 10 + src
[i
] - '0';
1831 if (val
> 255) return(mStatus_Invalid
);
1833 return(mStatus_NoError
);
1836 mDNSlocal mStatus
GetIPv4FromName(mDNSAddr
*const a
, const domainname
*const name
)
1838 int skip
= CountLabels(name
) - 6;
1839 if (skip
< 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name
); return mStatus_Invalid
; }
1840 if (GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+3)->c
, &a
->ip
.v4
.b
[0]) ||
1841 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+2)->c
, &a
->ip
.v4
.b
[1]) ||
1842 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+1)->c
, &a
->ip
.v4
.b
[2]) ||
1843 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+0)->c
, &a
->ip
.v4
.b
[3])) return mStatus_Invalid
;
1844 a
->type
= mDNSAddrType_IPv4
;
1845 return(mStatus_NoError
);
1848 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
1849 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
1850 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
1852 mDNSlocal mStatus
GetIPv6FromName(mDNSAddr
*const a
, const domainname
*const name
)
1855 const domainname
*n
;
1857 int skip
= CountLabels(name
) - 34;
1858 if (skip
< 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name
); return mStatus_Invalid
; }
1860 n
= SkipLeadingLabels(name
, skip
);
1861 for (i
=0; i
<16; i
++)
1863 if (n
->c
[0] != 1) return mStatus_Invalid
;
1864 l
= HexVal(n
->c
[1]);
1865 n
= (const domainname
*)(n
->c
+ 2);
1867 if (n
->c
[0] != 1) return mStatus_Invalid
;
1868 h
= HexVal(n
->c
[1]);
1869 n
= (const domainname
*)(n
->c
+ 2);
1871 if (l
<0 || h
<0) return mStatus_Invalid
;
1872 a
->ip
.v6
.b
[15-i
] = (mDNSu8
)((h
<< 4) | l
);
1875 a
->type
= mDNSAddrType_IPv6
;
1876 return(mStatus_NoError
);
1879 mDNSlocal mDNSs32
ReverseMapDomainType(const domainname
*const name
)
1881 int skip
= CountLabels(name
) - 2;
1884 const domainname
*suffix
= SkipLeadingLabels(name
, skip
);
1885 if (SameDomainName(suffix
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4
;
1886 if (SameDomainName(suffix
, (const domainname
*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6
;
1888 return(mDNSAddrType_None
);
1891 mDNSlocal
void SendARP(mDNS
*const m
, const mDNSu8 op
, const AuthRecord
*const rr
,
1892 const mDNSv4Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const dst
)
1895 mDNSu8
*ptr
= m
->omsg
.data
;
1896 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1897 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
1899 // 0x00 Destination address
1900 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
1902 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1903 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
1905 // 0x0C ARP Ethertype (0x0806)
1906 *ptr
++ = 0x08; *ptr
++ = 0x06;
1909 *ptr
++ = 0x00; *ptr
++ = 0x01; // Hardware address space; Ethernet = 1
1910 *ptr
++ = 0x08; *ptr
++ = 0x00; // Protocol address space; IP = 0x0800
1911 *ptr
++ = 6; // Hardware address length
1912 *ptr
++ = 4; // Protocol address length
1913 *ptr
++ = 0x00; *ptr
++ = op
; // opcode; Request = 1, Response = 2
1915 // 0x16 Sender hardware address (our MAC address)
1916 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[i
];
1918 // 0x1C Sender protocol address
1919 for (i
=0; i
<4; i
++) *ptr
++ = spa
->b
[i
];
1921 // 0x20 Target hardware address
1922 for (i
=0; i
<6; i
++) *ptr
++ = tha
->b
[i
];
1924 // 0x26 Target protocol address
1925 for (i
=0; i
<4; i
++) *ptr
++ = tpa
->b
[i
];
1927 // 0x2A Total ARP Packet length 42 bytes
1928 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
1931 mDNSlocal mDNSu16
CheckSum(const void *const data
, mDNSs32 length
, mDNSu32 sum
)
1933 const mDNSu16
*ptr
= data
;
1934 while (length
> 0) { length
-= 2; sum
+= *ptr
++; }
1935 sum
= (sum
& 0xFFFF) + (sum
>> 16);
1936 sum
= (sum
& 0xFFFF) + (sum
>> 16);
1937 return(sum
!= 0xFFFF ? sum
: 0);
1940 mDNSlocal mDNSu16
IPv6CheckSum(const mDNSv6Addr
*const src
, const mDNSv6Addr
*const dst
, const mDNSu8 protocol
, const void *const data
, const mDNSu32 length
)
1942 IPv6PseudoHeader ph
;
1945 ph
.len
.b
[0] = length
>> 24;
1946 ph
.len
.b
[1] = length
>> 16;
1947 ph
.len
.b
[2] = length
>> 8;
1948 ph
.len
.b
[3] = length
;
1952 ph
.pro
.b
[3] = protocol
;
1953 return CheckSum(&ph
, sizeof(ph
), CheckSum(data
, length
, 0));
1956 mDNSlocal
void SendNDP(mDNS
*const m
, const mDNSu8 op
, const mDNSu8 flags
, const AuthRecord
*const rr
,
1957 const mDNSv6Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv6Addr
*const tpa
, const mDNSEthAddr
*const dst
)
1960 mDNSOpaque16 checksum
;
1961 mDNSu8
*ptr
= m
->omsg
.data
;
1962 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
1963 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
1964 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
1965 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] } };
1966 const mDNSv6Addr
*const v6dst
= (op
== NDP_Sol
) ? &mc
: tpa
;
1967 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1968 if (!intf
) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
1970 // 0x00 Destination address
1971 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
1972 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
1973 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
1974 // link with a pointless link-layer multicast.
1975 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
1976 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
1980 // *ptr++ = tpa->b[0xD];
1981 // *ptr++ = tpa->b[0xE];
1982 // *ptr++ = tpa->b[0xF];
1984 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
1985 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
1987 // 0x0C IPv6 Ethertype (0x86DD)
1988 *ptr
++ = 0x86; *ptr
++ = 0xDD;
1991 *ptr
++ = 0x60; *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00; // Version, Traffic Class, Flow Label
1992 *ptr
++ = 0x00; *ptr
++ = 0x20; // Length
1993 *ptr
++ = 0x3A; // Protocol == ICMPv6
1994 *ptr
++ = 0xFF; // Hop Limit
1996 // 0x16 Sender IPv6 address
1997 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
1999 // 0x26 Destination IPv6 address
2000 for (i
=0; i
<16; i
++) *ptr
++ = v6dst
->b
[i
];
2003 *ptr
++ = op
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2004 *ptr
++ = 0x00; // Code
2005 *ptr
++ = 0x00; *ptr
++ = 0x00; // Checksum placeholder (0x38, 0x39)
2007 *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00;
2009 if (op
== NDP_Sol
) // Neighbor Solicitation. The NDP "target" is the address we seek.
2012 for (i
=0; i
<16; i
++) *ptr
++ = tpa
->b
[i
];
2013 // 0x4E Source Link-layer Address
2014 // <http://www.ietf.org/rfc/rfc2461.txt>
2015 // MUST NOT be included when the source IP address is the unspecified address.
2016 // Otherwise, on link layers that have addresses this option MUST be included
2017 // in multicast solicitations and SHOULD be included in unicast solicitations.
2018 if (!mDNSIPv6AddressIsZero(*spa
))
2020 *ptr
++ = NDP_SrcLL
; // Option Type 1 == Source Link-layer Address
2021 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2022 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2025 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2028 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2029 // 0x4E Target Link-layer Address
2030 *ptr
++ = NDP_TgtLL
; // Option Type 2 == Target Link-layer Address
2031 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2032 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2035 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2036 m
->omsg
.data
[0x13] = ptr
- &m
->omsg
.data
[0x36]; // Compute actual length
2037 checksum
.NotAnInteger
= ~IPv6CheckSum(spa
, v6dst
, 0x3A, &m
->omsg
.data
[0x36], m
->omsg
.data
[0x13]);
2038 m
->omsg
.data
[0x38] = checksum
.b
[0];
2039 m
->omsg
.data
[0x39] = checksum
.b
[1];
2041 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2044 mDNSlocal
void SetupOwnerOpt(const mDNS
*const m
, const NetworkInterfaceInfo
*const intf
, rdataOPT
*const owner
)
2046 owner
->u
.owner
.vers
= 0;
2047 owner
->u
.owner
.seq
= m
->SleepSeqNum
;
2048 owner
->u
.owner
.HMAC
= m
->PrimaryMAC
;
2049 owner
->u
.owner
.IMAC
= intf
->MAC
;
2050 owner
->u
.owner
.password
= zeroEthAddr
;
2052 // Don't try to compute the optlen until *after* we've set up the data fields
2053 // 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
2054 owner
->opt
= kDNSOpt_Owner
;
2055 owner
->optlen
= DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) - 4;
2058 mDNSlocal
void GrantUpdateCredit(AuthRecord
*rr
)
2060 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
2061 else rr
->NextUpdateCredit
= NonZeroTime(rr
->NextUpdateCredit
+ kUpdateCreditRefreshInterval
);
2064 // Note about acceleration of announcements to facilitate automatic coalescing of
2065 // multiple independent threads of announcements into a single synchronized thread:
2066 // The announcements in the packet may be at different stages of maturity;
2067 // One-second interval, two-second interval, four-second interval, and so on.
2068 // After we've put in all the announcements that are due, we then consider
2069 // whether there are other nearly-due announcements that are worth accelerating.
2070 // To be eligible for acceleration, a record MUST NOT be older (further along
2071 // its timeline) than the most mature record we've already put in the packet.
2072 // In other words, younger records can have their timelines accelerated to catch up
2073 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2074 // Older records cannot have their timelines accelerated; this would just widen
2075 // the gap between them and their younger bretheren and get them even more out of sync.
2077 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2078 // the record list and/or question list.
2079 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2080 mDNSlocal
void SendResponses(mDNS
*const m
)
2083 AuthRecord
*rr
, *r2
;
2084 mDNSs32 maxExistingAnnounceInterval
= 0;
2085 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2087 m
->NextScheduledResponse
= m
->timenow
+ 0x78000000;
2089 if (m
->SleepState
== SleepState_Transferring
) RetrySPSRegistrations(m
);
2091 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2092 if (rr
->ImmedUnicast
)
2094 mDNSAddr v4
= { mDNSAddrType_IPv4
, {{{0}}} };
2095 mDNSAddr v6
= { mDNSAddrType_IPv6
, {{{0}}} };
2096 v4
.ip
.v4
= rr
->v4Requester
;
2097 v6
.ip
.v6
= rr
->v6Requester
;
2098 if (!mDNSIPv4AddressIsZero(rr
->v4Requester
)) SendDelayedUnicastResponse(m
, &v4
, rr
->ImmedAnswer
);
2099 if (!mDNSIPv6AddressIsZero(rr
->v6Requester
)) SendDelayedUnicastResponse(m
, &v6
, rr
->ImmedAnswer
);
2100 if (rr
->ImmedUnicast
)
2102 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m
, rr
));
2103 rr
->ImmedUnicast
= mDNSfalse
;
2108 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2111 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2112 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2114 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
2115 if (TimeToAnnounceThisRecord(rr
, m
->timenow
))
2117 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2119 if (!rr
->WakeUp
.HMAC
.l
[0])
2121 if (rr
->AnnounceCount
) rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send goodbye packet on all interfaces
2125 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr
->AnnounceCount
-3, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
2126 SendWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.IMAC
, &rr
->WakeUp
.password
);
2127 for (r2
= rr
; r2
; r2
=r2
->next
)
2128 if (r2
->AnnounceCount
&& r2
->resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.IMAC
, &rr
->WakeUp
.IMAC
))
2130 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2131 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2132 if (r2
->AddressProxy
.type
== mDNSAddrType_IPv6
&& r2
->AnnounceCount
== WakeupCount
)
2134 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2135 r2
->AnnounceCount
-3, &r2
->WakeUp
.HMAC
, &r2
->WakeUp
.IMAC
, ARDisplayString(m
,r2
));
2136 SendNDP(m
, NDP_Adv
, NDP_Override
, r2
, &r2
->AddressProxy
.ip
.v6
, &r2
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2138 r2
->LastAPTime
= m
->timenow
;
2139 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2140 if (--r2
->AnnounceCount
<= GoodbyeCount
) r2
->WakeUp
.HMAC
= zeroEthAddr
;
2144 else if (ResourceRecordIsValidAnswer(rr
))
2146 if (rr
->AddressProxy
.type
)
2148 rr
->AnnounceCount
--;
2149 rr
->ThisAPInterval
*= 2;
2150 rr
->LastAPTime
= m
->timenow
;
2151 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv4
)
2153 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2154 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2155 SendARP(m
, 1, rr
, &rr
->AddressProxy
.ip
.v4
, &zeroEthAddr
, &rr
->AddressProxy
.ip
.v4
, &onesEthAddr
);
2157 else if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
2159 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2160 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2161 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2166 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2167 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
2168 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
2169 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
2175 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2176 // Eligible records that are more than half-way to their announcement time are accelerated
2177 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2178 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
2179 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
2180 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
2181 !rr
->AddressProxy
.type
&& // Don't include ARP Annoucements when considering which records to accelerate
2182 ResourceRecordIsValidAnswer(rr
)))
2183 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2185 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2186 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2187 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2188 // then all that means is that it won't get sent -- which would not be the end of the world.
2189 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2191 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
2192 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
2193 if (RRTypeIsAddressType(r2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2194 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
2195 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
2196 rr
->resrec
.rdatahash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2197 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, r2
->resrec
.name
) &&
2198 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
2199 r2
->ImmedAdditional
= r2
->resrec
.InterfaceID
; // ... then mark this address record for sending too
2200 // We also make sure we send the DeviceInfo TXT record too, if necessary
2201 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2202 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2203 if (rr
->ImmedAnswer
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->resrec
.rrtype
== kDNSType_PTR
)
2204 if (ResourceRecordIsValidAnswer(&m
->DeviceInfo
) && SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2206 if (!m
->DeviceInfo
.ImmedAnswer
) m
->DeviceInfo
.ImmedAnswer
= rr
->ImmedAnswer
;
2207 else m
->DeviceInfo
.ImmedAnswer
= mDNSInterfaceMark
;
2211 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2212 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2213 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2214 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2215 // -- 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
2216 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2217 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2218 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2220 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
2222 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2223 if (ResourceRecordIsValidAnswer(r2
))
2224 if (r2
->ImmedAnswer
!= mDNSInterfaceMark
&&
2225 r2
->ImmedAnswer
!= rr
->ImmedAnswer
&& SameResourceRecordSignature(r2
, rr
))
2226 r2
->ImmedAnswer
= !r2
->ImmedAnswer
? rr
->ImmedAnswer
: mDNSInterfaceMark
;
2228 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
2230 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2231 if (ResourceRecordIsValidAnswer(r2
))
2232 if (r2
->ImmedAdditional
!= rr
->ImmedAdditional
&& SameResourceRecordSignature(r2
, rr
))
2233 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
2237 // Now set SendRNow state appropriately
2238 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2240 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
2242 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
2243 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
2244 rr
->LastMCTime
= m
->timenow
;
2245 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2246 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2247 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
2249 rr
->AnnounceCount
--;
2250 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
2251 rr
->ThisAPInterval
*= 2;
2252 rr
->LastAPTime
= m
->timenow
;
2253 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
2256 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
2258 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
2259 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
2260 rr
->LastMCTime
= m
->timenow
;
2261 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2263 SetNextAnnounceProbeTime(m
, rr
);
2264 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2268 // *** 2. Loop through interface list, sending records as appropriate
2273 const int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
2275 int numAnnounce
= 0;
2277 mDNSu8
*responseptr
= m
->omsg
.data
;
2279 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2281 // First Pass. Look for:
2282 // 1. Deregistering records that need to send their goodbye packet
2283 // 2. Updated records that need to retract their old data
2284 // 3. Answers and announcements we need to send
2285 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2288 // Skip this interface if the record InterfaceID is *Any and the record is not
2289 // appropriate for the interface type.
2290 if ((rr
->SendRNow
== intf
->InterfaceID
) &&
2291 ((rr
->resrec
.InterfaceID
== mDNSInterface_Any
) && !mDNSPlatformValidRecordForInterface(rr
, intf
)))
2293 LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m
, rr
), InterfaceNameForID(m
, rr
->SendRNow
));
2294 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2296 else if (rr
->SendRNow
== intf
->InterfaceID
)
2298 RData
*OldRData
= rr
->resrec
.rdata
;
2299 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
2300 mDNSu8 active
= (mDNSu8
)
2301 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
2302 (m
->SleepState
!= SleepState_Sleeping
|| intf
->SPSAddr
[0].type
|| intf
->SPSAddr
[1].type
|| intf
->SPSAddr
[2].type
));
2304 if (rr
->NewRData
&& active
)
2306 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2307 if (ResourceRecordIsValidAnswer(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
2309 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, 0);
2310 if (newptr
) { responseptr
= newptr
; numDereg
++; rr
->RequireGoodbye
= mDNSfalse
; }
2311 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
2313 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
2316 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2317 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2318 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, active
? rr
->resrec
.rroriginalttl
: 0);
2319 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2322 responseptr
= newptr
;
2323 rr
->RequireGoodbye
= active
;
2324 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) numDereg
++;
2325 else if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++;else numAnswer
++;
2328 if (rr
->NewRData
&& active
)
2329 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
2331 // The first time through (pktcount==0), if this record is verified unique
2332 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2333 if (!pktcount
&& active
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2334 rr
->SendNSECNow
= mDNSInterfaceMark
;
2336 if (newptr
) // If succeeded in sending, advance to next interface
2338 // If sending on all interfaces, go to next interface; else we're finished now
2339 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
2340 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2342 rr
->SendRNow
= mDNSNULL
;
2347 // Second Pass. Add additional records, if there's space.
2348 newptr
= responseptr
;
2349 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2350 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
2351 if (ResourceRecordIsValidAnswer(rr
))
2353 // If we have at least one answer already in the packet, then plan to add additionals too
2354 mDNSBool SendAdditional
= (m
->omsg
.h
.numAnswers
> 0);
2356 // If we're not planning to send any additionals, but this record is a unique one, then
2357 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2358 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2359 if (!SendAdditional
&& (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
2361 const AuthRecord
*a
;
2362 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
2363 if (a
->LastMCTime
== m
->timenow
&&
2364 a
->LastMCInterface
== intf
->InterfaceID
&&
2365 SameResourceRecordSignature(a
, rr
)) { SendAdditional
= mDNStrue
; break; }
2367 if (!SendAdditional
) // If we don't want to send this after all,
2368 rr
->ImmedAdditional
= mDNSNULL
; // then cancel its ImmedAdditional field
2369 else if (newptr
) // Else, try to add it if we can
2371 // The first time through (pktcount==0), if this record is verified unique
2372 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2373 if (!pktcount
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2374 rr
->SendNSECNow
= mDNSInterfaceMark
;
2376 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2377 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2378 newptr
= PutRR_OS(newptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2379 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2382 responseptr
= newptr
;
2383 rr
->ImmedAdditional
= mDNSNULL
;
2384 rr
->RequireGoodbye
= mDNStrue
;
2385 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2386 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2387 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2388 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2389 rr
->LastMCTime
= m
->timenow
;
2390 rr
->LastMCInterface
= intf
->InterfaceID
;
2395 // Third Pass. Add NSEC records, if there's space.
2396 // When we're generating an NSEC record in response to a specify query for that type
2397 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2398 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2399 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2400 if (rr
->SendNSECNow
== mDNSInterfaceMark
|| rr
->SendNSECNow
== intf
->InterfaceID
)
2405 mDNS_SetupResourceRecord(&nsec
, mDNSNULL
, mDNSInterface_Any
, kDNSType_NSEC
, rr
->resrec
.rroriginalttl
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2406 nsec
.resrec
.rrclass
|= kDNSClass_UniqueRRSet
;
2407 AssignDomainName(&nsec
.namestorage
, rr
->resrec
.name
);
2408 ptr
= nsec
.rdatastorage
.u
.data
;
2409 len
= DomainNameLength(rr
->resrec
.name
);
2410 // We have a nxt name followed by window number, window length and a window bitmap
2411 nsec
.resrec
.rdlength
= len
+ 2 + NSEC_MCAST_WINDOW_SIZE
;
2412 if (nsec
.resrec
.rdlength
<= StandardAuthRDSize
)
2414 mDNSPlatformMemZero(ptr
, nsec
.resrec
.rdlength
);
2415 AssignDomainName((domainname
*)ptr
, rr
->resrec
.name
);
2417 *ptr
++ = 0; // window number
2418 *ptr
++ = NSEC_MCAST_WINDOW_SIZE
; // window length
2419 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2420 if (ResourceRecordIsValidAnswer(r2
) && SameResourceRecordNameClassInterface(r2
, rr
))
2422 if (r2
->resrec
.rrtype
>= kDNSQType_ANY
) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m
, r2
)); break; }
2423 else ptr
[r2
->resrec
.rrtype
>> 3] |= 128 >> (r2
->resrec
.rrtype
& 7);
2425 newptr
= responseptr
;
2426 if (!r2
) // If we successfully built our NSEC record, add it to the packet now
2428 newptr
= PutRR_OS(responseptr
, &m
->omsg
.h
.numAdditionals
, &nsec
.resrec
);
2429 if (newptr
) responseptr
= newptr
;
2432 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec
.resrec
.rdlength
);
2434 // If we successfully put the NSEC record, clear the SendNSECNow flag
2435 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2436 if (newptr
|| rr
->SendNSECNow
== mDNSInterfaceMark
)
2438 rr
->SendNSECNow
= mDNSNULL
;
2439 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2440 for (r2
= rr
->next
; r2
; r2
=r2
->next
)
2441 if (SameResourceRecordNameClassInterface(r2
, rr
))
2442 if (r2
->SendNSECNow
== mDNSInterfaceMark
|| r2
->SendNSECNow
== intf
->InterfaceID
)
2443 r2
->SendNSECNow
= mDNSNULL
;
2447 if (m
->omsg
.h
.numAnswers
|| m
->omsg
.h
.numAdditionals
)
2449 // If we have data to send, add OWNER option if necessary, then send packet
2451 if (OwnerRecordSpace
)
2454 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2455 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
2456 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
2457 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
2458 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
2459 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
);
2460 if (newptr
) { responseptr
= newptr
; LogSPS("SendResponses put %s", ARDisplayString(m
, &opt
)); }
2461 else if (m
->omsg
.h
.numAnswers
+ m
->omsg
.h
.numAuthorities
+ m
->omsg
.h
.numAdditionals
== 1)
2462 LogSPS("SendResponses: No space in packet for Owner OPT record (%d/%d/%d/%d) %s",
2463 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
2465 LogMsg("SendResponses: How did we fail to have space for Owner OPT record (%d/%d/%d/%d) %s",
2466 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
2469 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2470 numDereg
, numDereg
== 1 ? "" : "s",
2471 numAnnounce
, numAnnounce
== 1 ? "" : "s",
2472 numAnswer
, numAnswer
== 1 ? "" : "s",
2473 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
2475 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
2476 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
2477 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
2478 if (++pktcount
>= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
2479 // There might be more things to send on this interface, so go around one more time and try again.
2481 else // Nothing more to send on this interface; go to next
2483 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
2484 #if MDNS_DEBUGMSGS && 0
2485 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2486 debugf(msg
, intf
, next
);
2489 pktcount
= 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2494 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2497 if (m
->CurrentRecord
)
2498 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2499 m
->CurrentRecord
= m
->ResourceRecords
;
2500 while (m
->CurrentRecord
)
2502 rr
= m
->CurrentRecord
;
2503 m
->CurrentRecord
= rr
->next
;
2507 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
)
2508 LogMsg("SendResponses: No active interface %p to send: %p %02X %s", rr
->SendRNow
, rr
->resrec
.InterfaceID
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
2509 rr
->SendRNow
= mDNSNULL
;
2512 if (rr
->ImmedAnswer
|| rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2514 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
2516 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->AnnounceCount
== 0)
2518 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
2519 if (!AuthRecord_uDNS(rr
)) CompleteDeregistration(m
, rr
); // Don't touch rr after this
2523 rr
->ImmedAnswer
= mDNSNULL
;
2524 rr
->ImmedUnicast
= mDNSfalse
;
2525 rr
->v4Requester
= zerov4Addr
;
2526 rr
->v6Requester
= zerov6Addr
;
2530 verbosedebugf("SendResponses: Next in %ld ticks", m
->NextScheduledResponse
- m
->timenow
);
2533 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2534 // so we want to be lazy about how frequently we do it.
2535 // 1. If a cache record is currently referenced by *no* active questions,
2536 // then we don't mind expiring it up to a minute late (who will know?)
2537 // 2. Else, if a cache record is due for some of its final expiration queries,
2538 // we'll allow them to be late by up to 2% of the TTL
2539 // 3. Else, if a cache record has completed all its final expiration queries without success,
2540 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2541 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2542 // so allow at most 1/10 second lateness
2543 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2544 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2545 #define CacheCheckGracePeriod(RR) ( \
2546 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
2547 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
2548 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
2549 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
2551 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2553 mDNSexport
void ScheduleNextCacheCheckTime(mDNS
*const m
, const mDNSu32 slot
, const mDNSs32 event
)
2555 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
2556 m
->rrcache_nextcheck
[slot
] = event
;
2557 if (m
->NextCacheCheck
- event
> 0)
2558 m
->NextCacheCheck
= event
;
2561 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2563 // rr->resrec.rroriginalttl
2564 // rr->UnansweredQueries
2565 // rr->CRActiveQuestion
2566 mDNSexport
void SetNextCacheCheckTimeForRecord(mDNS
*const m
, CacheRecord
*const rr
)
2568 rr
->NextRequiredQuery
= RRExpireTime(rr
);
2570 // If we have an active question, then see if we want to schedule a refresher query for this record.
2571 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2572 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
2574 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
2575 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
2576 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2577 (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
,rr
));
2580 ScheduleNextCacheCheckTime(m
, HashSlot(rr
->resrec
.name
), NextCacheCheckEvent(rr
));
2583 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
2584 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
2585 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
2586 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 30)
2588 mDNSlocal mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
2590 if (interval
< kMinimumReconfirmTime
)
2591 interval
= kMinimumReconfirmTime
;
2592 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
2593 interval
= 0x10000000;
2595 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2596 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
2598 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2599 // For all the reconfirmations in a given batch, we want to use the same random value
2600 // so that the reconfirmation questions can be grouped into a single query packet
2601 if (!m
->RandomReconfirmDelay
) m
->RandomReconfirmDelay
= 1 + mDNSRandom(0x3FFFFFFF);
2602 interval
+= m
->RandomReconfirmDelay
% ((interval
/3) + 1);
2603 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
2604 rr
->resrec
.rroriginalttl
= (interval
* 4 + mDNSPlatformOneSecond
- 1) / mDNSPlatformOneSecond
;
2605 SetNextCacheCheckTimeForRecord(m
, rr
);
2607 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2608 RRExpireTime(rr
) - m
->timenow
, CRDisplayString(m
, rr
), rr
->CRActiveQuestion
);
2609 return(mStatus_NoError
);
2612 #define MaxQuestionInterval (3600 * mDNSPlatformOneSecond)
2614 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2615 // It also appends to the list of known answer records that need to be included,
2616 // and updates the forcast for the size of the known answer section.
2617 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, DNSMessage
*query
, mDNSu8
**queryptr
, DNSQuestion
*q
,
2618 CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
2620 mDNSBool ucast
= (q
->LargeAnswers
|| q
->RequestUnicast
) && m
->CanReceiveUnicastOn5353
;
2621 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
2622 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
2623 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
- *answerforecast
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
2626 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
2631 mDNSu32 forecast
= *answerforecast
;
2632 const mDNSu32 slot
= HashSlot(&q
->qname
);
2633 const CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
2635 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
2637 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
2638 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
2639 !(rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && // which is a shared (i.e. not unique) record type
2640 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not already in the known answer list
2641 rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
2642 SameNameRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
2643 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
> // and its half-way-to-expiry time is at least 1 second away
2644 mDNSPlatformOneSecond
) // (also ensures we never include goodbye records with TTL=1)
2646 // We don't want to include unique records in the Known Answer section. The Known Answer section
2647 // is intended to suppress floods of shared-record replies from many other devices on the network.
2648 // That concept really does not apply to unique records, and indeed if we do send a query for
2649 // which we have a unique record already in our cache, then including that unique record as a
2650 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
2652 *ka
= rr
; // Link this record into our known answer chain
2653 ka
= &rr
->NextInKAList
;
2654 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2655 forecast
+= 12 + rr
->resrec
.rdestimate
;
2656 // If we're trying to put more than one question in this packet, and it doesn't fit
2657 // then undo that last question and try again next time
2658 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
2660 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d",
2661 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
);
2662 query
->h
.numQuestions
--;
2663 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
2664 while (*ka
) { CacheRecord
*c
= *ka
; *ka
= mDNSNULL
; ka
= &c
->NextInKAList
; }
2665 return(mDNSfalse
); // Return false, so we'll try again in the next packet
2669 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
2670 *queryptr
= newptr
; // Update the packet pointer
2671 *answerforecast
= forecast
; // Update the forecast
2672 *kalistptrptr
= ka
; // Update the known answer list pointer
2673 if (ucast
) q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
2675 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // For every resource record in our cache,
2676 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
2677 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not in the known answer list
2678 SameNameRecordAnswersQuestion(&rr
->resrec
, q
)) // which answers our question
2680 rr
->UnansweredQueries
++; // indicate that we're expecting a response
2681 rr
->LastUnansweredTime
= m
->timenow
;
2682 SetNextCacheCheckTimeForRecord(m
, rr
);
2689 // When we have a query looking for a specified name, but there appear to be no answers with
2690 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
2691 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
2692 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
2693 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
2694 // A typical reconfirmation scenario might go like this:
2695 // Depth 0: Name "myhost.local" has no address records
2696 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
2697 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
2698 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
2699 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
2700 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
2701 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const int depth
)
2706 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth
, name
->c
);
2707 FORALL_CACHERECORDS(slot
, cg
, cr
)
2709 domainname
*crtarget
= GetRRDomainNameTarget(&cr
->resrec
);
2710 if (crtarget
&& cr
->resrec
.rdatahash
== namehash
&& SameDomainName(crtarget
, name
))
2712 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth
, CRDisplayString(m
, cr
));
2713 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
2715 ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, depth
+1);
2720 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
2721 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
2722 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
2723 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
2724 mDNSlocal
const CacheRecord
*CacheHasAddressTypeForName(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
2726 CacheGroup
*const cg
= CacheGroupForName(m
, HashSlot(name
), namehash
, name
);
2727 const CacheRecord
*cr
= cg
? cg
->members
: mDNSNULL
;
2728 while (cr
&& !RRTypeIsAddressType(cr
->resrec
.rrtype
)) cr
=cr
->next
;
2732 mDNSlocal
const CacheRecord
*FindSPSInCache1(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*const c0
, const CacheRecord
*const c1
)
2734 CacheGroup
*const cg
= CacheGroupForName(m
, HashSlot(&q
->qname
), q
->qnamehash
, &q
->qname
);
2735 const CacheRecord
*cr
, *bestcr
= mDNSNULL
;
2736 mDNSu32 bestmetric
= 1000000;
2737 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
2738 if (cr
->resrec
.rrtype
== kDNSType_PTR
&& cr
->resrec
.rdlength
>= 6) // If record is PTR type, with long enough name,
2739 if (cr
!= c0
&& cr
!= c1
) // that's not one we've seen before,
2740 if (SameNameRecordAnswersQuestion(&cr
->resrec
, q
)) // and answers our browse query,
2741 if (!IdenticalSameNameRecord(&cr
->resrec
, &m
->SPSRecords
.RR_PTR
.resrec
)) // and is not our own advertised service...
2743 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
2744 if (bestmetric
> metric
) { bestmetric
= metric
; bestcr
= cr
; }
2749 mDNSlocal
void CheckAndSwapSPS(const CacheRecord
*sps1
, const CacheRecord
*sps2
)
2751 const CacheRecord
*swap_sps
;
2752 mDNSu32 metric1
, metric2
;
2754 if (!sps1
|| !sps2
) return;
2755 metric1
= SPSMetric(sps1
->resrec
.rdata
->u
.name
.c
);
2756 metric2
= SPSMetric(sps2
->resrec
.rdata
->u
.name
.c
);
2757 if (!SPSFeatures(sps1
->resrec
.rdata
->u
.name
.c
) && SPSFeatures(sps2
->resrec
.rdata
->u
.name
.c
) && (metric2
>= metric1
))
2765 mDNSlocal
void ReorderSPSByFeature(const CacheRecord
*sps
[3])
2767 CheckAndSwapSPS(sps
[0], sps
[1]);
2768 CheckAndSwapSPS(sps
[0], sps
[2]);
2769 CheckAndSwapSPS(sps
[1], sps
[2]);
2773 // Finds the three best Sleep Proxies we currently have in our cache
2774 mDNSexport
void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3])
2776 sps
[0] = FindSPSInCache1(m
, q
, mDNSNULL
, mDNSNULL
);
2777 sps
[1] = !sps
[0] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], mDNSNULL
);
2778 sps
[2] = !sps
[1] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], sps
[1]);
2780 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
2781 // only if they have equally good metric and support features.
2782 ReorderSPSByFeature(sps
);
2785 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
2786 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
2789 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
2792 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
2795 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
2798 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
2801 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
2802 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
2803 for (i
=0; i
<DupSuppressInfoSize
; i
++)
2804 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
2806 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
2807 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
2808 if (v4
&& v6
) return(mDNStrue
);
2813 mDNSlocal
int RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
2817 // See if we have this one in our list somewhere already
2818 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
2820 // If not, find a slot we can re-use
2821 if (i
>= DupSuppressInfoSize
)
2824 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
2825 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
2829 // Record the info about this query we saw
2831 ds
[i
].InterfaceID
= InterfaceID
;
2837 mDNSlocal
void mDNSSendWakeOnResolve(mDNS
*const m
, DNSQuestion
*q
)
2840 mDNSInterfaceID InterfaceID
= q
->InterfaceID
;
2841 domainname
*d
= &q
->qname
;
2843 // We can't send magic packets without knowing which interface to send it on.
2844 if (InterfaceID
== mDNSInterface_Any
|| InterfaceID
== mDNSInterface_LocalOnly
|| InterfaceID
== mDNSInterface_P2P
)
2846 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID
, q
->qname
.c
);
2850 // Split MAC@IPAddress and pass them separately
2854 for (i
= 1; i
< len
; i
++)
2858 char EthAddr
[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
2859 char IPAddr
[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
2862 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q
->qname
.c
, cnt
);
2865 if ((i
- 1) > (int) (sizeof(EthAddr
) - 1))
2867 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q
->qname
.c
, i
- 1);
2870 if ((len
- i
) > (int)(sizeof(IPAddr
) - 1))
2872 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q
->qname
.c
, len
- i
);
2875 mDNSPlatformMemCopy(EthAddr
, &d
->c
[1], i
- 1);
2877 mDNSPlatformMemCopy(IPAddr
, &d
->c
[i
+ 1], len
- i
);
2878 IPAddr
[len
- i
] = 0;
2879 mDNSPlatformSendWakeupPacket(m
, InterfaceID
, EthAddr
, IPAddr
, InitialWakeOnResolveCount
- q
->WakeOnResolveCount
);
2882 else if (d
->c
[i
] == ':')
2885 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q
->qname
.c
);
2889 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
2891 // If more than 90% of the way to the query time, we should unconditionally accelerate it
2892 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
2895 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
2896 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
2898 // We forecast: qname (n) type (2) class (2)
2899 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
2900 const mDNSu32 slot
= HashSlot(&q
->qname
);
2901 const CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
2902 const CacheRecord
*rr
;
2903 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
2904 if (rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
2905 SameNameRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
2906 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
2907 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0) // and we'll ask at least once again before NextRequiredQuery
2909 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
2910 forecast
+= 12 + rr
->resrec
.rdestimate
;
2911 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
2919 // How Standard Queries are generated:
2920 // 1. The Question Section contains the question
2921 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
2923 // How Probe Queries are generated:
2924 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
2925 // if some other host is already using *any* records with this name, we want to know about it.
2926 // 2. The Authority Section contains the proposed values we intend to use for one or more
2927 // of our records with that name (analogous to the Update section of DNS Update packets)
2928 // because if some other host is probing at the same time, we each want to know what the other is
2929 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
2931 mDNSlocal
void SendQueries(mDNS
*const m
)
2939 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
2940 mDNSs32 maxExistingQuestionInterval
= 0;
2941 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2942 CacheRecord
*KnownAnswerList
= mDNSNULL
;
2944 // 1. If time for a query, work out what we need to do
2946 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
2947 // to their NextRequiredQuery to be worth batching them together with this one
2948 FORALL_CACHERECORDS(slot
, cg
, cr
)
2950 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
2952 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
2954 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
2955 q
= cr
->CRActiveQuestion
;
2956 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(cr
)/20, cr
->resrec
.InterfaceID
);
2957 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
2958 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
2961 q
->SendQNow
= mDNSInterfaceMark
; // If targeted query, mark it
2963 else if (!mDNSOpaque16IsZero(q
->TargetQID
))
2965 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
2966 cr
->UnansweredQueries
++;
2968 else if (q
->SendQNow
== mDNSNULL
)
2970 q
->SendQNow
= cr
->resrec
.InterfaceID
;
2972 else if (q
->SendQNow
!= cr
->resrec
.InterfaceID
)
2974 q
->SendQNow
= mDNSInterfaceMark
;
2980 // Scan our list of questions to see which:
2981 // *WideArea* queries need to be sent
2982 // *unicast* queries need to be sent
2983 // *multicast* queries we're definitely going to send
2984 if (m
->CurrentQuestion
)
2985 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
2986 m
->CurrentQuestion
= m
->Questions
;
2987 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
2989 q
= m
->CurrentQuestion
;
2990 if (q
->Target
.type
&& (q
->SendQNow
|| TimeToSendThisQuestion(q
, m
->timenow
)))
2992 mDNSu8
*qptr
= m
->omsg
.data
;
2993 const mDNSu8
*const limit
= m
->omsg
.data
+ sizeof(m
->omsg
.data
);
2995 // 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
2996 if (!q
->LocalSocket
) q
->LocalSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
2999 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, QueryFlags
);
3000 qptr
= putQuestion(&m
->omsg
, qptr
, limit
, &q
->qname
, q
->qtype
, q
->qclass
);
3001 mDNSSendDNSMessage(m
, &m
->omsg
, qptr
, mDNSInterface_Any
, q
->LocalSocket
, &q
->Target
, q
->TargetPort
, mDNSNULL
, mDNSNULL
, q
->UseBrackgroundTrafficClass
);
3002 q
->ThisQInterval
*= QuestionIntervalStep
;
3004 if (q
->ThisQInterval
> MaxQuestionInterval
)
3005 q
->ThisQInterval
= MaxQuestionInterval
;
3006 q
->LastQTime
= m
->timenow
;
3007 q
->LastQTxTime
= m
->timenow
;
3008 q
->RecentAnswerPkts
= 0;
3009 q
->SendQNow
= mDNSNULL
;
3010 q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
3012 else if (mDNSOpaque16IsZero(q
->TargetQID
) && !q
->Target
.type
&& TimeToSendThisQuestion(q
, m
->timenow
))
3014 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3015 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3016 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3017 maxExistingQuestionInterval
= q
->ThisQInterval
;
3019 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3020 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3021 // m->CurrentQuestion point to the right question
3022 if (q
== m
->CurrentQuestion
) m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3024 while (m
->CurrentQuestion
)
3026 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3027 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3029 m
->CurrentQuestion
= mDNSNULL
;
3031 // Scan our list of questions
3032 // (a) to see if there are any more that are worth accelerating, and
3033 // (b) to update the state variables for *all* the questions we're going to send
3034 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3035 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3036 // 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.
3037 m
->NextScheduledQuery
= m
->timenow
+ 0x78000000;
3038 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3040 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
||
3041 (!q
->Target
.type
&& ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
))))
3043 // If at least halfway to next query time, advance to next interval
3044 // If less than halfway to next query time, then
3045 // treat this as logically a repeat of the last transmission, without advancing the interval
3046 if (m
->timenow
- (q
->LastQTime
+ (q
->ThisQInterval
/2)) >= 0)
3048 //LogInfo("Accelerating %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3049 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3050 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3051 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
/ InitialQuestionInterval
, q
->RequestUnicast
);
3052 q
->ThisQInterval
*= QuestionIntervalStep
;
3053 if (q
->ThisQInterval
> MaxQuestionInterval
)
3054 q
->ThisQInterval
= MaxQuestionInterval
;
3055 else if (q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* QuestionIntervalStep3
&& !q
->RequestUnicast
&&
3056 !(RRTypeIsAddressType(q
->qtype
) && CacheHasAddressTypeForName(m
, &q
->qname
, q
->qnamehash
)))
3058 // Generally don't need to log this.
3059 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3060 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3061 // and when there simply happen to be no instances of the service the client is looking
3062 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3063 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3064 q
->qname
.c
, DNSTypeName(q
->qtype
));
3065 // Sending third query, and no answers yet; time to begin doubting the source
3066 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
3070 // Mark for sending. (If no active interfaces, then don't even try.)
3071 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3074 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3075 q
->LastQTime
= m
->timenow
;
3078 // If we recorded a duplicate suppression for this question less than half an interval ago,
3079 // then we consider it recent enough that we don't need to do an identical query ourselves.
3080 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3082 q
->LastQTxTime
= m
->timenow
;
3083 q
->RecentAnswerPkts
= 0;
3084 if (q
->RequestUnicast
) q
->RequestUnicast
--;
3086 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3087 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3088 SetNextQueryTime(m
,q
);
3091 // 2. Scan our authoritative RR list to see what probes we might need to send
3093 m
->NextScheduledProbe
= m
->timenow
+ 0x78000000;
3095 if (m
->CurrentRecord
)
3096 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3097 m
->CurrentRecord
= m
->ResourceRecords
;
3098 while (m
->CurrentRecord
)
3100 ar
= m
->CurrentRecord
;
3101 m
->CurrentRecord
= ar
->next
;
3102 if (!AuthRecord_uDNS(ar
) && ar
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3104 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3105 if (m
->timenow
- (ar
->LastAPTime
+ ar
->ThisAPInterval
) < 0)
3107 SetNextAnnounceProbeTime(m
, ar
);
3109 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3110 else if (ar
->ProbeCount
)
3112 if (ar
->AddressProxy
.type
== mDNSAddrType_IPv4
)
3114 LogSPS("SendQueries ARP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3115 SendARP(m
, 1, ar
, &zerov4Addr
, &zeroEthAddr
, &ar
->AddressProxy
.ip
.v4
, &ar
->WakeUp
.IMAC
);
3117 else if (ar
->AddressProxy
.type
== mDNSAddrType_IPv6
)
3119 LogSPS("SendQueries NDP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3120 // IPv6 source = zero
3121 // No target hardware address
3122 // IPv6 target address is address we're probing
3123 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3124 SendNDP(m
, NDP_Sol
, 0, ar
, &zerov6Addr
, mDNSNULL
, &ar
->AddressProxy
.ip
.v6
, &ar
->WakeUp
.IMAC
);
3126 // Mark for sending. (If no active interfaces, then don't even try.)
3127 ar
->SendRNow
= (!intf
|| ar
->WakeUp
.HMAC
.l
[0]) ? mDNSNULL
: ar
->resrec
.InterfaceID
? ar
->resrec
.InterfaceID
: intf
->InterfaceID
;
3128 ar
->LastAPTime
= m
->timenow
;
3129 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3130 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3131 if (ar
->ProbeCount
> DefaultProbeCountForTypeUnique
)
3132 ar
->ProbeCount
= DefaultProbeCountForTypeUnique
;
3134 SetNextAnnounceProbeTime(m
, ar
);
3135 if (ar
->ProbeCount
== 0)
3137 // If this is the last probe for this record, then see if we have any matching records
3138 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3140 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3141 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, ar
))
3143 // ... then acknowledge this record to the client.
3144 // We do this optimistically, just as we're about to send the third probe.
3145 // This helps clients that both advertise and browse, and want to filter themselves
3146 // from the browse results list, because it helps ensure that the registration
3147 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3148 // A potential downside is that we could deliver a registration confirmation and then find out
3149 // moments later that there's a name conflict, but applications have to be prepared to handle
3150 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3151 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
);
3154 // else, if it has now finished probing, move it to state Verified,
3155 // and update m->NextScheduledResponse so it will be announced
3158 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
); // Defensive, just in case it got missed somehow
3159 ar
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3160 ar
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3161 ar
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3162 SetNextAnnounceProbeTime(m
, ar
);
3166 m
->CurrentRecord
= m
->DuplicateRecords
;
3167 while (m
->CurrentRecord
)
3169 ar
= m
->CurrentRecord
;
3170 m
->CurrentRecord
= ar
->next
;
3171 if (ar
->resrec
.RecordType
== kDNSRecordTypeUnique
&& ar
->ProbeCount
== 0 && !ar
->Acknowledged
)
3172 AcknowledgeRecord(m
, ar
);
3175 // 3. Now we know which queries and probes we're sending,
3176 // go through our interface list sending the appropriate queries on each interface
3179 const int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
3180 mDNSu8
*queryptr
= m
->omsg
.data
;
3181 mDNSBool useBackgroundTrafficClass
= mDNSfalse
; // set if we should use background traffic class
3183 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, QueryFlags
);
3184 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3185 if (!KnownAnswerList
)
3187 // Start a new known-answer list
3188 CacheRecord
**kalistptr
= &KnownAnswerList
;
3189 mDNSu32 answerforecast
= OwnerRecordSpace
; // We start by assuming we'll need at least enough space to put the Owner Option
3191 // Put query questions in this packet
3192 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3194 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
== intf
->InterfaceID
))
3196 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3197 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3198 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- m
->omsg
.data
, queryptr
+ answerforecast
- m
->omsg
.data
);
3200 // If interface is P2P type, verify that query should be sent over it.
3201 if (!mDNSPlatformValidQuestionForInterface(q
, intf
))
3203 LogInfo("SendQueries: Not sending (%s) %##s on %s", DNSTypeName(q
->qtype
), q
->qname
.c
, InterfaceNameForID(m
, intf
->InterfaceID
));
3204 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3206 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3207 else if (SuppressOnThisInterface(q
->DupSuppress
, intf
) ||
3208 BuildQuestion(m
, &m
->omsg
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3210 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3211 if (q
->WakeOnResolveCount
)
3213 mDNSSendWakeOnResolve(m
, q
);
3214 q
->WakeOnResolveCount
--;
3217 // use brackground traffic class if any included question requires it
3218 if (q
->UseBrackgroundTrafficClass
)
3220 useBackgroundTrafficClass
= mDNStrue
;
3226 // Put probe questions in this packet
3227 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3228 if (ar
->SendRNow
== intf
->InterfaceID
)
3230 mDNSBool ucast
= (ar
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1) && m
->CanReceiveUnicastOn5353
;
3231 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3232 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.numQuestions
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3233 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3234 mDNSu32 forecast
= answerforecast
+ 12 + ar
->resrec
.rdestimate
;
3235 mDNSu8
*newptr
= putQuestion(&m
->omsg
, queryptr
, limit
- forecast
, ar
->resrec
.name
, kDNSQType_ANY
, (mDNSu16
)(ar
->resrec
.rrclass
| ucbit
));
3239 answerforecast
= forecast
;
3240 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3241 ar
->IncludeInProbe
= mDNStrue
;
3242 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d",
3243 ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
), ar
->ProbeCount
);
3248 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3249 while (KnownAnswerList
)
3251 CacheRecord
*ka
= KnownAnswerList
;
3252 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- ka
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3253 mDNSu8
*newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAnswers
,
3254 &ka
->resrec
, ka
->resrec
.rroriginalttl
- SecsSinceRcvd
, m
->omsg
.data
+ NormalMaxDNSMessageData
- OwnerRecordSpace
);
3257 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3258 ka
->resrec
.name
->c
, DNSTypeName(ka
->resrec
.rrtype
), queryptr
- m
->omsg
.data
, newptr
- m
->omsg
.data
);
3260 KnownAnswerList
= ka
->NextInKAList
;
3261 ka
->NextInKAList
= mDNSNULL
;
3265 // If we ran out of space and we have more than one question in the packet, that's an error --
3266 // we shouldn't have put more than one question if there was a risk of us running out of space.
3267 if (m
->omsg
.h
.numQuestions
> 1)
3268 LogMsg("SendQueries: Put %d answers; No more space for known answers", m
->omsg
.h
.numAnswers
);
3269 m
->omsg
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
3274 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3275 if (ar
->IncludeInProbe
)
3277 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, &ar
->resrec
);
3278 ar
->IncludeInProbe
= mDNSfalse
;
3279 if (newptr
) queryptr
= newptr
;
3280 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m
,ar
));
3283 if (queryptr
> m
->omsg
.data
)
3285 if (OwnerRecordSpace
)
3288 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3289 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3290 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
3291 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3292 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3293 LogSPS("SendQueries putting %s", ARDisplayString(m
, &opt
));
3294 queryptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAdditionals
,
3295 &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
3297 LogMsg("SendQueries: How did we fail to have space for the OPT record (%d/%d/%d/%d) %s",
3298 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3299 if (queryptr
> m
->omsg
.data
+ NormalMaxDNSMessageData
)
3300 if (m
->omsg
.h
.numQuestions
!= 1 || m
->omsg
.h
.numAnswers
!= 0 || m
->omsg
.h
.numAuthorities
!= 1 || m
->omsg
.h
.numAdditionals
!= 1)
3301 LogMsg("SendQueries: Why did we generate oversized packet with OPT record %p %p %p (%d/%d/%d/%d) %s",
3302 m
->omsg
.data
, m
->omsg
.data
+ NormalMaxDNSMessageData
, queryptr
,
3303 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3306 if ((m
->omsg
.h
.flags
.b
[0] & kDNSFlag0_TC
) && m
->omsg
.h
.numQuestions
> 1)
3307 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m
->omsg
.h
.numQuestions
);
3308 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3309 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
3310 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
3311 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAuthorities
== 1 ? "" : "s", intf
->InterfaceID
);
3312 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, useBackgroundTrafficClass
);
3313 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, useBackgroundTrafficClass
);
3314 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
3315 if (++pktcount
>= 1000)
3316 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
3317 // There might be more records left in the known answer list, or more questions to send
3318 // on this interface, so go around one more time and try again.
3320 else // Nothing more to send on this interface; go to next
3322 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3323 #if MDNS_DEBUGMSGS && 0
3324 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3325 debugf(msg
, intf
, next
);
3331 // 4. Final housekeeping
3333 // 4a. Debugging check: Make sure we announced all our records
3334 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3337 if (ar
->ARType
!= AuthRecordLocalOnly
&& ar
->ARType
!= AuthRecordP2P
)
3338 LogMsg("SendQueries: No active interface %p to send probe: %p %s", ar
->SendRNow
, ar
->resrec
.InterfaceID
, ARDisplayString(m
, ar
));
3339 ar
->SendRNow
= mDNSNULL
;
3342 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3343 // that their interface which went away might come back again, the logic will want to send queries
3344 // for those records, but we can't because their interface isn't here any more, so to keep the
3345 // state machine ticking over we just pretend we did so.
3346 // If the interface does not come back in time, the cache record will expire naturally
3347 FORALL_CACHERECORDS(slot
, cg
, cr
)
3349 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
3351 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
3353 cr
->UnansweredQueries
++;
3354 cr
->CRActiveQuestion
->SendQNow
= mDNSNULL
;
3355 SetNextCacheCheckTimeForRecord(m
, cr
);
3360 // 4c. Debugging check: Make sure we sent all our planned questions
3361 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3362 // we legitimately couldn't send because the interface is no longer available
3363 for (q
= m
->Questions
; q
; q
=q
->next
)
3367 for (x
= m
->NewQuestions
; x
; x
=x
->next
) if (x
== q
) break; // Check if this question is a NewQuestion
3368 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
));
3369 q
->SendQNow
= mDNSNULL
;
3373 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
)
3376 mDNSu8
*ptr
= m
->omsg
.data
;
3377 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
3378 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID
); return; }
3380 // 0x00 Destination address
3381 for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
3383 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3384 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
3386 // 0x0C Ethertype (0x0842)
3390 // 0x0E Wakeup sync sequence
3391 for (i
=0; i
<6; i
++) *ptr
++ = 0xFF;
3394 for (j
=0; j
<16; j
++) for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
3397 for (i
=0; i
<6; i
++) *ptr
++ = password
->b
[i
];
3399 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
3401 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3402 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3403 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3404 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3405 // So, we send one of each, unicast first, then broadcast second.
3406 for (i
=0; i
<6; i
++) m
->omsg
.data
[i
] = 0xFF;
3407 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
3410 // ***************************************************************************
3411 #if COMPILER_LIKES_PRAGMA_MARK
3413 #pragma mark - RR List Management & Task Management
3416 // Whenever a question is answered, reset its state so that we don't query
3417 // the network repeatedly. This happens first time when we answer the question and
3418 // and later when we refresh the cache.
3419 mDNSlocal
void ResetQuestionState(mDNS
*const m
, DNSQuestion
*q
)
3421 q
->LastQTime
= m
->timenow
;
3422 q
->LastQTxTime
= m
->timenow
;
3423 q
->RecentAnswerPkts
= 0;
3424 q
->ThisQInterval
= MaxQuestionInterval
;
3425 q
->RequestUnicast
= mDNSfalse
;
3426 // Reset unansweredQueries so that we don't penalize this server later when we
3427 // start sending queries when the cache expires.
3428 q
->unansweredQueries
= 0;
3429 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3432 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3433 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3434 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3435 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3436 mDNSexport
void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
)
3438 DNSQuestion
*const q
= m
->CurrentQuestion
;
3439 mDNSBool followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
3441 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3442 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", rr
->resrec
.rroriginalttl
, CRDisplayString(m
, rr
));
3444 // When the response for the question was validated, the entire rrset was validated. If we deliver
3445 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
3446 // in the future, we will do the revalidation again.
3448 // Also, if we deliver an ADD for a negative cache record and it has no NSECS, the ValidationStatus needs
3449 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
3450 // negative response which can happen e.g., when disconnecting from network. As we don't deliver RMVs for
3451 // negative responses that were delivered before, we need to do it on the next ADD of a negative cache
3452 // record. This ADD could be the result of a timeout, no DNS servers etc. If we don't reset the state, we
3453 // will deliver this as a secure response.
3454 if (q
->ValidationRequired
&& ((AddRecord
== QC_rmv
) ||
3455 (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
&& !rr
->nsec
)))
3457 q
->ValidationStatus
= 0;
3458 q
->ValidationState
= DNSSECValRequired
;
3461 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3462 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3463 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3464 // we check to see if that query already has a unique local answer.
3465 if (q
->LOAddressAnswers
)
3467 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3468 "LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
),
3469 q
->LOAddressAnswers
);
3473 if (QuerySuppressed(q
))
3475 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
3476 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3477 // that are timing out, which we know are answered with Negative cache record when timing out.
3478 if (!q
->TimeoutQuestion
|| rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| (m
->timenow
- q
->StopTime
< 0))
3482 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3483 // may be called twice, once when the record is received, and again when it's time to notify local clients.
3484 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3486 rr
->LastUsed
= m
->timenow
;
3487 if (AddRecord
== QC_add
&& !q
->DuplicateOf
&& rr
->CRActiveQuestion
!= q
)
3489 if (!rr
->CRActiveQuestion
) m
->rrcache_active
++; // If not previously active, increment rrcache_active count
3490 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3491 rr
->CRActiveQuestion
, q
, CRDisplayString(m
,rr
), q
->CurrentAnswers
);
3492 rr
->CRActiveQuestion
= q
; // We know q is non-null
3493 SetNextCacheCheckTimeForRecord(m
, rr
);
3497 // (a) a no-cache add, where we've already done at least one 'QM' query, or
3498 // (b) a normal add, where we have at least one unique-type answer,
3499 // then there's no need to keep polling the network.
3500 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3501 // We do this for mDNS questions and uDNS one-shot questions, but not for
3502 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3503 if ((AddRecord
== QC_addnocache
&& !q
->RequestUnicast
) ||
3504 (AddRecord
== QC_add
&& (q
->ExpectUnique
|| (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))))
3505 if (ActiveQuestion(q
) && (mDNSOpaque16IsZero(q
->TargetQID
) || !q
->LongLived
))
3507 ResetQuestionState(m
, q
);
3510 if (rr
->DelayDelivery
) return; // We'll come back later when CacheRecordDeferredAdd() calls us
3512 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
3513 // for the purpose of retrying search domains
3514 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
|| (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
)))
3515 if (!AddRecord
|| (AddRecord
!= QC_forceresponse
&& !q
->ReturnIntermed
)) return;
3517 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
3518 if (q
->QuestionCallback
&& !q
->NoAnswer
&& (!followcname
|| q
->ReturnIntermed
))
3520 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3521 if (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
))
3524 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->qDNSServer
);
3525 q
->QuestionCallback(m
, q
, &neg
.resrec
, AddRecord
);
3528 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
3529 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3531 // If this is an "Add" operation and this question needs validation, validate the response.
3532 // In the case of negative responses, extra care should be taken. Negative cache records are
3533 // used for many purposes. For example,
3535 // 1) Suppressing questions (SuppressUnusable)
3536 // 2) Timeout questions
3537 // 3) The name does not exist
3538 // 4) No DNS servers are available and we need a quick response for the application
3540 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" in that case.
3541 // For (3), it is possible that we don't get nsecs back but we still need to call VerifySignature so
3542 // that we can deliver the appropriate DNSSEC result. There is no point in verifying signature for (4)
3543 // and hence the explicit check for q->qDNSServer.
3545 // Note: It is important that we avoid (4) here because once the state is set to DNSSECValInProgress,
3546 // we won't verify the signature when it is really needed. For example, start a query (which is answered
3547 // securely), disconnect from the network. (3) would happen now and if we start the verification, we
3548 // move DNSSECValInProgress but never have a chance to go back to DNSSECValRequired as we don't deliver
3549 // RMVs for negative response that was added before.
3551 if (m
->CurrentQuestion
== q
&& (AddRecord
== QC_add
) && !q
->ValidatingResponse
&&
3552 q
->ValidationState
== DNSSECValRequired
&& q
->qDNSServer
)
3554 q
->ValidationState
= DNSSECValInProgress
;
3555 // Treat it as callback call as that's what dnssec code expects
3556 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
3557 VerifySignature(m
, mDNSNULL
, q
);
3558 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
3562 // Note: Proceed with caution here because client callback function is allowed to do anything,
3563 // including starting/stopping queries, registering/deregistering records, etc.
3565 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
3566 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
3567 // first before following it
3568 if (!DNSSECQuestion(q
) && followcname
&& m
->CurrentQuestion
== q
)
3569 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
3572 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*rr
)
3574 rr
->DelayDelivery
= 0;
3575 if (m
->CurrentQuestion
)
3576 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
3577 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3578 m
->CurrentQuestion
= m
->Questions
;
3579 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3581 DNSQuestion
*q
= m
->CurrentQuestion
;
3582 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3583 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
3584 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3585 m
->CurrentQuestion
= q
->next
;
3587 m
->CurrentQuestion
= mDNSNULL
;
3590 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSu32 slot
)
3592 const mDNSs32 threshhold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
3593 const mDNSs32 start
= m
->timenow
- 0x10000000;
3594 mDNSs32 delay
= start
;
3595 CacheGroup
*cg
= CacheGroupForName(m
, slot
, namehash
, name
);
3596 const CacheRecord
*rr
;
3597 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
3598 if (threshhold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
3599 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
3600 delay
= RRExpireTime(rr
);
3601 if (delay
- start
> 0) return(NonZeroTime(delay
));
3605 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
3606 // If new questions are created as a result of invoking client callbacks, they will be added to
3607 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3608 // rr is a new CacheRecord just received into our cache
3609 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3610 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3611 // which may change the record list and/or question list.
3612 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3613 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
3617 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
3618 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
3619 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3621 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3623 // If this question is one that's actively sending queries, and it's received ten answers within one
3624 // second of sending the last query packet, then that indicates some radical network topology change,
3625 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
3626 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
3627 // because we will anyway send another query within a few seconds. The first reset query is sent out
3628 // randomized over the next four seconds to reduce possible synchronization between machines.
3629 if (q
->LastAnswerPktNum
!= m
->PktNum
)
3631 q
->LastAnswerPktNum
= m
->PktNum
;
3632 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
3633 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
3635 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
3636 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
3637 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
3638 q
->ThisQInterval
= InitialQuestionInterval
;
3639 SetNextQueryTime(m
,q
);
3642 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr
, rr
->resrec
.name
->c
,
3643 DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
, rr
->resrec
.rDNSServer
?
3644 &rr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(rr
->resrec
.rDNSServer
?
3645 rr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
3646 q
->CurrentAnswers
++;
3647 q
->unansweredQueries
= 0;
3648 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
3649 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
3650 if (q
->CurrentAnswers
> 4000)
3652 static int msgcount
= 0;
3653 if (msgcount
++ < 10)
3654 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
3655 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
3656 rr
->resrec
.rroriginalttl
= 0;
3657 rr
->UnansweredQueries
= MaxUnansweredQueries
;
3662 if (!rr
->DelayDelivery
)
3664 if (m
->CurrentQuestion
)
3665 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3666 m
->CurrentQuestion
= m
->Questions
;
3667 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3669 q
= m
->CurrentQuestion
;
3670 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3671 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
3672 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3673 m
->CurrentQuestion
= q
->next
;
3675 m
->CurrentQuestion
= mDNSNULL
;
3678 SetNextCacheCheckTimeForRecord(m
, rr
);
3681 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
3682 // If new questions are created as a result of invoking client callbacks, they will be added to
3683 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3684 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
3685 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
3686 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
3687 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
3688 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3689 // which may change the record list and/or question list.
3690 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3691 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*rr
)
3693 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
3694 if (m
->CurrentQuestion
)
3695 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3696 m
->CurrentQuestion
= m
->Questions
;
3697 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
3698 // since we're not caching the record and we'll get no opportunity to do this later
3699 while (m
->CurrentQuestion
)
3701 DNSQuestion
*q
= m
->CurrentQuestion
;
3702 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3703 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
3704 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3705 m
->CurrentQuestion
= q
->next
;
3707 m
->CurrentQuestion
= mDNSNULL
;
3710 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
3711 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
3712 // If new questions are created as a result of invoking client callbacks, they will be added to
3713 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
3714 // rr is an existing cache CacheRecord that just expired and is being deleted
3715 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
3716 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
3717 // which may change the record list and/or question list.
3718 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
3719 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
3721 if (m
->CurrentQuestion
)
3722 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
3723 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3724 m
->CurrentQuestion
= m
->Questions
;
3726 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
3727 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
3728 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3730 DNSQuestion
*q
= m
->CurrentQuestion
;
3731 // When a question enters suppressed state, we generate RMV events and generate a negative
3732 // response. A cache may be present that answers this question e.g., cache entry generated
3733 // before the question became suppressed. We need to skip the suppressed questions here as
3734 // the RMV event has already been generated.
3735 if (!QuerySuppressed(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
3737 verbosedebugf("CacheRecordRmv %p %s", rr
, CRDisplayString(m
, rr
));
3738 q
->FlappingInterface1
= mDNSNULL
;
3739 q
->FlappingInterface2
= mDNSNULL
;
3741 if (q
->CurrentAnswers
== 0)
3742 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
3743 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
3744 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
3747 q
->CurrentAnswers
--;
3748 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
3749 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
3751 if (rr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
3753 if (q
->CurrentAnswers
== 0)
3755 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
3756 q
->qname
.c
, DNSTypeName(q
->qtype
));
3757 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
3759 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
3762 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
3763 m
->CurrentQuestion
= q
->next
;
3765 m
->CurrentQuestion
= mDNSNULL
;
3768 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
3770 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
3772 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
3774 e
->next
= m
->rrcache_free
;
3775 m
->rrcache_free
= e
;
3776 m
->rrcache_totalused
--;
3779 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
3781 CacheEntity
*e
= (CacheEntity
*)(*cp
);
3782 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
3783 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
3784 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
3785 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
3786 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
3787 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
3788 (*cp
)->name
= mDNSNULL
;
3789 *cp
= (*cp
)->next
; // Cut record from list
3790 ReleaseCacheEntity(m
, e
);
3793 mDNSexport
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
3797 const mDNSu32 slot
= HashSlot(r
->resrec
.name
);
3799 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
3800 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
3801 r
->resrec
.rdata
= mDNSNULL
;
3803 cg
= CacheGroupForRecord(m
, slot
, &r
->resrec
);
3804 if (!cg
) LogMsg("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
3806 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
3807 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
3808 // (which is handled below) and in that case it should be freed here.
3809 if (r
->resrec
.name
&& cg
&& r
->resrec
.name
!= cg
->name
)
3811 LogInfo("ReleaseCacheRecord: freeing %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
3812 mDNSPlatformMemFree((void *)r
->resrec
.name
);
3814 r
->resrec
.name
= mDNSNULL
;
3819 CacheRecord
*rr
= *rp
;
3820 *rp
= (*rp
)->next
; // Cut record from list
3821 if (rr
->resrec
.rdata
&& rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
)
3823 mDNSPlatformMemFree(rr
->resrec
.rdata
);
3824 rr
->resrec
.rdata
= mDNSNULL
;
3826 // NSEC records that are added to the "nsec" list does not share the name
3827 // of the CacheGroup.
3828 if (rr
->resrec
.name
)
3830 LogInfo("ReleaseCacheRecord: freeing cached nsec %##s (%s)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
3831 mDNSPlatformMemFree((void *)rr
->resrec
.name
);
3832 rr
->resrec
.name
= mDNSNULL
;
3834 ReleaseCacheEntity(m
, (CacheEntity
*)rr
);
3836 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
3839 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
3840 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
3841 // callbacks for old records are delivered before callbacks for newer records.
3842 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
3844 CacheRecord
**rp
= &cg
->members
;
3846 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
3847 m
->lock_rrcache
= 1;
3851 CacheRecord
*const rr
= *rp
;
3852 mDNSs32 event
= RRExpireTime(rr
);
3853 if (m
->timenow
- event
>= 0) // If expired, delete it
3855 *rp
= rr
->next
; // Cut it from the list
3856 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
3857 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
3858 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
3860 DNSQuestion
*q
= rr
->CRActiveQuestion
;
3861 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
3862 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
3863 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
3864 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
3865 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
3866 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
3867 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
3868 if (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
&& ActiveQuestion(q
))
3870 q
->ThisQInterval
= InitialQuestionInterval
;
3871 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3872 SetNextQueryTime(m
, q
);
3874 CacheRecordRmv(m
, rr
);
3875 m
->rrcache_active
--;
3877 ReleaseCacheRecord(m
, rr
);
3879 else // else, not expired; see if we need to query
3881 // If waiting to delay delivery, do nothing until then
3882 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
3883 event
= rr
->DelayDelivery
;
3886 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
3887 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3889 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
3890 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
3891 else // else trigger our question to go out now
3893 // Set NextScheduledQuery to timenow so that SendQueries() will run.
3894 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
3895 m
->NextScheduledQuery
= m
->timenow
;
3896 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
3897 // which will correctly update m->NextCacheCheck for us.
3898 event
= m
->timenow
+ 0x3FFFFFFF;
3902 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
3903 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
3904 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3905 m
->rrcache_nextcheck
[slot
] = event
;
3909 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
3910 cg
->rrcache_tail
= rp
;
3911 m
->lock_rrcache
= 0;
3914 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
3916 mDNSBool ShouldQueryImmediately
= mDNStrue
;
3917 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
3918 mDNSu32 slot
= HashSlot(&q
->qname
);
3919 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
3922 mDNSBool AnsweredFromCache
= mDNSfalse
;
3924 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3926 if (cg
) CheckCacheExpiration(m
, slot
, cg
);
3927 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
3928 m
->NewQuestions
= q
->next
;
3929 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
3930 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
3932 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
3933 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
3934 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
3935 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
3936 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
3937 // advanced it), that means the question was deleted, so we no longer need to worry about answering
3938 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
3939 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
3941 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
3942 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
3943 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
3944 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
3946 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
3947 // This should be safe, because calling the client's question callback may cause the
3948 // question list to be modified, but should not ever cause the rrcache list to be modified.
3949 // If the client's question callback deletes the question, then m->CurrentQuestion will
3950 // be advanced, and we'll exit out of the loop
3951 m
->lock_rrcache
= 1;
3952 if (m
->CurrentQuestion
)
3953 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
3954 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3955 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
3957 if (q
->NoAnswer
== NoAnswer_Fail
)
3959 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3960 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
3961 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
3962 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
3963 // Don't touch the question if it has been stopped already
3964 if (m
->CurrentQuestion
== q
) q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
3965 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
3967 if (m
->CurrentQuestion
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); goto exit
; }
3969 // See if we want to tell it about LocalOnly records
3970 if (m
->CurrentRecord
)
3971 LogMsg("AnswerNewQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3972 slot
= AuthHashSlot(&q
->qname
);
3973 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
3976 m
->CurrentRecord
= ag
->members
;
3977 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
3979 AuthRecord
*rr
= m
->CurrentRecord
;
3980 m
->CurrentRecord
= rr
->next
;
3982 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
3983 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
3985 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
3986 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
3987 // we handle both mDNSInterface_Any and scoped questions.
3989 if (rr
->ARType
== AuthRecordLocalOnly
|| (rr
->ARType
== AuthRecordP2P
&& q
->InterfaceID
== mDNSInterface_Any
))
3990 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
3992 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, mDNStrue
);
3993 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
3997 m
->CurrentRecord
= mDNSNULL
;
3999 if (m
->CurrentQuestion
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while while giving LocalOnly record answers"); goto exit
; }
4001 if (q
->LOAddressAnswers
)
4003 LogInfo("AnswerNewQuestion: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4004 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4008 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4009 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4010 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4011 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4012 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4015 lr
= ag
->NewLocalOnlyRecords
;
4018 if (LORecordAnswersAddressType(lr
) && LocalOnlyRecordAnswersQuestion(lr
, q
))
4020 LogInfo("AnswerNewQuestion: Question %p %##s (%s) will be answered using new local auth records "
4021 " LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4029 // If we are not supposed to answer this question, generate a negative response.
4030 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4032 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4033 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4034 // the question out.
4035 if (QuerySuppressed(q
)) { q
->SuppressQuery
= mDNSfalse
; GenerateNegativeResponse(m
); q
->SuppressQuery
= mDNStrue
; }
4036 else if (!q
->ValidatingResponse
)
4039 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4040 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
4042 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4043 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
4044 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
4046 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
4047 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, CRDisplayString(m
, rr
), m
->timenow
, rr
->TimeRcvd
);
4048 continue; // Go to next one in loop
4051 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4052 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4053 if ((rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
4054 ShouldQueryImmediately
= mDNSfalse
;
4055 q
->CurrentAnswers
++;
4056 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4057 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4058 AnsweredFromCache
= mDNStrue
;
4059 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
4060 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4062 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
4063 ShouldQueryImmediately
= mDNSfalse
;
4065 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4066 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4067 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
4069 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4070 // with search domains, generate a negative response which will now retry after appending search domains.
4071 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4072 // we will retry with search domains.
4073 if (!QuerySuppressed(q
) && !AnsweredFromCache
&& q
->RetryWithSearchDomains
)
4075 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4076 GenerateNegativeResponse(m
);
4079 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit
; }
4081 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4082 // Hence we don't execute the following block of code for those cases.
4083 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
4085 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4086 q
->ThisQInterval
= InitialQuestionInterval
;
4087 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4088 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
4090 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4091 if (!m
->RandomQueryDelay
)
4092 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
4093 q
->LastQTime
+= m
->RandomQueryDelay
;
4097 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
4098 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
4099 // answers for this question until *after* its scheduled transmission time, in which case
4100 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
4101 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
4102 SetNextQueryTime(m
,q
);
4105 m
->CurrentQuestion
= mDNSNULL
;
4106 m
->lock_rrcache
= 0;
4109 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
4110 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
4111 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
4115 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
4116 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
4118 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4120 if (m
->CurrentQuestion
)
4121 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4122 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4123 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4125 if (m
->CurrentRecord
)
4126 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4128 // 1. First walk the LocalOnly records answering the LocalOnly question
4129 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
4130 // walk the ResourceRecords list delivering the answers
4131 slot
= AuthHashSlot(&q
->qname
);
4132 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
4135 m
->CurrentRecord
= ag
->members
;
4136 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
4138 AuthRecord
*rr
= m
->CurrentRecord
;
4139 m
->CurrentRecord
= rr
->next
;
4140 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
4142 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, mDNStrue
);
4143 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4148 if (m
->CurrentQuestion
== q
)
4150 m
->CurrentRecord
= m
->ResourceRecords
;
4152 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
4154 AuthRecord
*rr
= m
->CurrentRecord
;
4155 m
->CurrentRecord
= rr
->next
;
4156 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4158 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, mDNStrue
);
4159 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4164 m
->CurrentQuestion
= mDNSNULL
;
4165 m
->CurrentRecord
= mDNSNULL
;
4168 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
4170 CacheEntity
*e
= mDNSNULL
;
4172 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
4173 m
->lock_rrcache
= 1;
4175 // If we have no free records, ask the client layer to give us some more memory
4176 if (!m
->rrcache_free
&& m
->MainCallback
)
4178 if (m
->rrcache_totalused
!= m
->rrcache_size
)
4179 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4180 m
->rrcache_totalused
, m
->rrcache_size
);
4182 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4183 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4184 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4185 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
4186 // and recycle them, instead of allocating more memory.
4187 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
4188 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4189 m
->rrcache_size
, m
->rrcache_active
);
4192 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
4193 m
->MainCallback(m
, mStatus_GrowCache
);
4194 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4198 // If we still have no free records, recycle all the records we can.
4199 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4200 if (!m
->rrcache_free
)
4202 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
4204 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4206 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
4209 CacheRecord
**rp
= &(*cp
)->members
;
4212 // Records that answer still-active questions are not candidates for recycling
4213 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4214 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
4218 CacheRecord
*rr
= *rp
;
4219 *rp
= (*rp
)->next
; // Cut record from list
4220 ReleaseCacheRecord(m
, rr
);
4223 if ((*cp
)->rrcache_tail
!= rp
)
4224 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
4225 (*cp
)->rrcache_tail
= rp
;
4226 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
4227 else ReleaseCacheGroup(m
, cp
);
4230 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4231 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
4234 if (m
->rrcache_free
) // If there are records in the free list, take one
4236 e
= m
->rrcache_free
;
4237 m
->rrcache_free
= e
->next
;
4238 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
4240 LogInfo("RR Cache now using %ld objects", m
->rrcache_totalused
);
4241 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
4242 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
4243 else m
->rrcache_report
+= 1000;
4245 mDNSPlatformMemZero(e
, sizeof(*e
));
4248 m
->lock_rrcache
= 0;
4253 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
4255 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
4258 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
4259 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
4261 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
4262 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
4263 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
4269 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
4271 mDNSu16 namelen
= DomainNameLength(rr
->name
);
4272 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
4273 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
4274 cg
->next
= m
->rrcache_hash
[slot
];
4275 cg
->namehash
= rr
->namehash
;
4276 cg
->members
= mDNSNULL
;
4277 cg
->rrcache_tail
= &cg
->members
;
4278 if (namelen
> sizeof(cg
->namestorage
))
4279 cg
->name
= mDNSPlatformMemAllocate(namelen
);
4281 cg
->name
= (domainname
*)cg
->namestorage
;
4284 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
4285 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
4288 AssignDomainName(cg
->name
, rr
->name
);
4290 if (CacheGroupForRecord(m
, slot
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
4291 m
->rrcache_hash
[slot
] = cg
;
4292 if (CacheGroupForRecord(m
, slot
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
4297 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
4299 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
4300 LogMsg("mDNS_PurgeCacheResourceRecord: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
4301 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4302 // a positive answer using an expired record (e.g. from an interface that has gone away).
4303 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4304 // summary deletion without giving the proper callback to any questions that are monitoring it.
4305 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4306 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
4307 rr
->UnansweredQueries
= MaxUnansweredQueries
;
4308 rr
->resrec
.rroriginalttl
= 0;
4309 SetNextCacheCheckTimeForRecord(m
, rr
);
4312 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
4315 mDNSPlatformLock(m
);
4318 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4319 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
4322 if (m
->timenow
) time
= m
->timenow
;
4323 else time
= mDNS_TimeNow_NoLock(m
);
4324 mDNSPlatformUnlock(m
);
4328 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4329 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4330 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4331 #define SetSPSProxyListChanged(X) do { \
4332 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4333 m->SPSProxyListChanged = (X); } while(0)
4335 // Called from mDNS_Execute() to expire stale proxy records
4336 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
4338 m
->CurrentRecord
= list
;
4339 while (m
->CurrentRecord
)
4341 AuthRecord
*rr
= m
->CurrentRecord
;
4342 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
4344 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4345 // so we need to cease proxying for *all* records we may have, expired or not.
4346 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
4348 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
4349 m
->NextScheduledSPS
= rr
->TimeExpire
;
4351 else // else proxy record expired, so remove it
4353 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4354 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
4355 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
4356 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
4357 // Don't touch rr after this -- memory may have been free'd
4360 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4361 // new records could have been added to the end of the list as a result of that call.
4362 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
4363 m
->CurrentRecord
= rr
->next
;
4367 mDNSlocal
void CheckRmvEventsForLocalRecords(mDNS
*const m
)
4369 while (m
->CurrentRecord
)
4371 AuthRecord
*rr
= m
->CurrentRecord
;
4372 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
4374 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m
, rr
));
4375 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
4376 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
);
4377 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
4379 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
4380 rr
->AnsweredLocalQ
= mDNSfalse
;
4381 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
4382 // For LocalOnly records, we don't do that and hence we need to do that here.
4383 if (RRLocalOnly(rr
)) CompleteDeregistration(m
, rr
);
4386 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
4387 m
->CurrentRecord
= rr
->next
;
4391 mDNSlocal
void TimeoutQuestions(mDNS
*const m
)
4393 m
->NextScheduledStopTime
= m
->timenow
+ 0x3FFFFFFF;
4394 if (m
->CurrentQuestion
)
4395 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
,
4396 DNSTypeName(m
->CurrentQuestion
->qtype
));
4397 m
->CurrentQuestion
= m
->Questions
;
4398 while (m
->CurrentQuestion
)
4400 DNSQuestion
*const q
= m
->CurrentQuestion
;
4403 if (m
->timenow
- q
->StopTime
>= 0)
4405 LogInfo("TimeoutQuestions: question %##s timed out, time %d", q
->qname
.c
, m
->timenow
- q
->StopTime
);
4406 GenerateNegativeResponse(m
);
4407 if (m
->CurrentQuestion
== q
) q
->StopTime
= 0;
4411 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
4412 m
->NextScheduledStopTime
= q
->StopTime
;
4415 // If m->CurrentQuestion wasn't modified out from under us, advance it now
4416 // We can't do this at the start of the loop because GenerateNegativeResponse
4417 // depends on having m->CurrentQuestion point to the right question
4418 if (m
->CurrentQuestion
== q
)
4419 m
->CurrentQuestion
= q
->next
;
4421 m
->CurrentQuestion
= mDNSNULL
;
4424 mDNSlocal
void mDNSCoreFreeProxyRR(mDNS
*const m
)
4426 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
4427 AuthRecord
*rrPtr
= mDNSNULL
, *rrNext
= mDNSNULL
;
4431 rrPtr
= intf
->SPSRRSet
;
4434 rrNext
= rrPtr
->next
;
4435 mDNSPlatformMemFree(rrPtr
);
4438 intf
->SPSRRSet
= mDNSNULL
;
4443 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
4445 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
4447 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
4450 AuthRecord
*head
, *tail
;
4454 verbosedebugf("mDNS_Execute");
4456 if (m
->CurrentQuestion
)
4457 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
4458 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4460 if (m
->CurrentRecord
)
4461 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
4463 // 1. If we're past the probe suppression time, we can clear it
4464 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
4466 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
4467 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
4469 // 3. Purge our cache of stale old records
4470 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
4472 mDNSu32 numchecked
= 0;
4473 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
4474 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4476 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
4478 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
4479 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ 0x3FFFFFFF;
4482 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
4484 CheckCacheExpiration(m
, slot
, *cp
);
4485 if ((*cp
)->members
) cp
=&(*cp
)->next
;
4486 else ReleaseCacheGroup(m
, cp
);
4489 // Even if we didn't need to actually check this slot yet, still need to
4490 // factor its nextcheck time into our overall NextCacheCheck value
4491 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
4492 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
4494 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
4497 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
4499 m
->NextScheduledSPS
= m
->timenow
+ 0x3FFFFFFF;
4500 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
4501 CheckProxyRecords(m
, m
->ResourceRecords
);
4504 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
4506 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
4507 // as records could have expired during that check
4508 if (m
->timenow
- m
->NextScheduledKA
>= 0)
4510 m
->NextScheduledKA
= m
->timenow
+ 0x3FFFFFFF;
4511 mDNS_SendKeepalives(m
);
4514 // After two seconds after the owner option is set, call the ioctl to clear the
4515 // ignore neighbor advertisement flag.
4516 #if APPLE_OSX_mDNSResponder
4517 if (m
->clearIgnoreNA
&& m
->timenow
- m
->clearIgnoreNA
>= 0)
4519 mDNSPlatformToggleInterfaceAdvt(m
, mDNSfalse
);
4520 m
->clearIgnoreNA
= 0;
4523 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
4524 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0)
4526 m
->AnnounceOwner
= 0;
4527 // Also free the stored records that we had registered with the sleep proxy
4528 mDNSCoreFreeProxyRR(m
);
4531 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
4534 if (m
->SleepState
== SleepState_Transferring
)
4536 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
4537 BeginSleepProcessing(m
);
4541 // 4. See if we can answer any of our new local questions from the cache
4542 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
4544 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
4545 AnswerNewQuestion(m
);
4547 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
4549 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
4550 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
4551 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
4553 m
->LocalRemoveEvents
= mDNSfalse
;
4554 m
->CurrentRecord
= m
->ResourceRecords
;
4555 CheckRmvEventsForLocalRecords(m
);
4556 // Walk the LocalOnly records and deliver the RMV events
4557 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4558 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4560 m
->CurrentRecord
= ag
->members
;
4561 if (m
->CurrentRecord
) CheckRmvEventsForLocalRecords(m
);
4565 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
4567 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
4568 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
4570 head
= tail
= mDNSNULL
;
4571 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
4573 AuthRecord
*rr
= m
->NewLocalRecords
;
4574 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
4575 if (LocalRecordReady(rr
))
4577 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
4578 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNStrue
);
4582 // If we have just one record that is not ready, we don't have to unlink and
4583 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
4584 // terminate and set the NewLocalRecords to rr.
4585 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
4586 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
4587 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
4593 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
4594 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
4595 // if this is the first record we are skipping, move to the end of the list.
4596 // if we have already skipped records before, append it at the end.
4597 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
4598 if (*p
) *p
= rr
->next
; // Cut this record from the list
4599 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
4602 while (*p
) p
=&(*p
)->next
;
4611 rr
->next
= mDNSNULL
;
4614 m
->NewLocalRecords
= head
;
4615 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
4617 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
4619 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
4620 // to our local questions
4621 if (m
->NewLocalOnlyRecords
)
4623 m
->NewLocalOnlyRecords
= mDNSfalse
;
4624 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4625 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4627 for (i
=0; i
<100 && ag
->NewLocalOnlyRecords
; i
++)
4629 AuthRecord
*rr
= ag
->NewLocalOnlyRecords
;
4630 ag
->NewLocalOnlyRecords
= ag
->NewLocalOnlyRecords
->next
;
4631 // LocalOnly records should always be ready as they never probe
4632 if (LocalRecordReady(rr
))
4634 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
4635 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNStrue
);
4637 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m
, rr
));
4639 // We limit about 100 per AuthGroup that can be serviced at a time
4640 if (i
>= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
4644 // 5. See what packets we need to send
4645 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
4646 DiscardDeregistrations(m
);
4647 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
4649 // If the platform code is ready, and we're not suppressing packet generation right now
4650 // then send our responses, probes, and questions.
4651 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
4652 // We send queries next, because there might be final-stage probes that complete their probing here, causing
4653 // them to advance to announcing state, and we want those to be included in any announcements we send out.
4654 // Finally, we send responses, including the previously mentioned records that just completed probing.
4655 m
->SuppressSending
= 0;
4657 // 6. Send Query packets. This may cause some probing records to advance to announcing state
4658 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
4659 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
4662 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
4663 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
4664 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
4665 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
4666 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
4667 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4669 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
4671 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
4672 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
4673 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
4676 // 7. Send Response packets, including probing records just advanced to announcing state
4677 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
4678 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
4680 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
4681 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
4685 // Clear RandomDelay values, ready to pick a new different value next time
4686 m
->RandomQueryDelay
= 0;
4687 m
->RandomReconfirmDelay
= 0;
4689 if (m
->NextScheduledStopTime
&& m
->timenow
- m
->NextScheduledStopTime
>= 0) TimeoutQuestions(m
);
4690 #ifndef UNICAST_DISABLED
4691 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
4692 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
4693 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
4697 // Note about multi-threaded systems:
4698 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
4699 // performing mDNS API operations that change our next scheduled event time.
4701 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
4702 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
4703 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
4704 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
4705 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
4706 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
4707 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
4708 // without blocking. This avoids the race condition between the signal from the other thread arriving
4709 // just *before* or just *after* the main thread enters the blocking primitive.
4711 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
4712 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
4713 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
4714 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
4715 // by the time it gets to the timer callback function).
4717 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
4718 return(m
->NextScheduledEvent
);
4721 mDNSlocal
void SuspendLLQs(mDNS
*m
)
4724 for (q
= m
->Questions
; q
; q
= q
->next
)
4725 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
4726 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
4729 mDNSlocal mDNSBool
QuestionHasLocalAnswers(mDNS
*const m
, DNSQuestion
*q
)
4735 slot
= AuthHashSlot(&q
->qname
);
4736 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
4739 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
4740 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
4741 if (LORecordAnswersAddressType(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
4743 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
));
4750 // ActivateUnicastQuery() is called from three places:
4751 // 1. When a new question is created
4752 // 2. On wake from sleep
4753 // 3. When the DNS configuration changes
4754 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
4755 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
4756 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
4758 // For now this AutoTunnel stuff is specific to Mac OS X.
4759 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
4760 #if APPLE_OSX_mDNSResponder
4761 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
4762 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
4763 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
4764 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
4765 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
4766 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
4768 if (RRTypeIsAddressType(question
->qtype
) && PrivateQuery(question
) &&
4769 !SameDomainLabel(question
->qname
.c
, (const mDNSu8
*)"\x0c_autotunnel6")&& question
->QuestionCallback
!= AutoTunnelCallback
)
4771 question
->NoAnswer
= NoAnswer_Suspended
;
4772 AddNewClientTunnel(m
, question
);
4775 #endif // APPLE_OSX_mDNSResponder
4777 if (!question
->DuplicateOf
)
4779 debugf("ActivateUnicastQuery: %##s %s%s%s",
4780 question
->qname
.c
, DNSTypeName(question
->qtype
), PrivateQuery(question
) ? " (Private)" : "", ScheduleImmediately
? " ScheduleImmediately" : "");
4781 question
->CNAMEReferrals
= 0;
4782 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
4783 if (question
->LongLived
)
4785 question
->state
= LLQ_InitialRequest
;
4786 question
->id
= zeroOpaque64
;
4787 question
->servPort
= zeroIPPort
;
4788 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
4790 // If the question has local answers, then we don't want answers from outside
4791 if (ScheduleImmediately
&& !QuestionHasLocalAnswers(m
, question
))
4793 question
->ThisQInterval
= InitialQuestionInterval
;
4794 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
4795 SetNextQueryTime(m
, question
);
4800 // Caller should hold the lock
4801 mDNSexport
void mDNSCoreRestartAddressQueries(mDNS
*const m
, mDNSBool SearchDomainsChanged
, FlushCache flushCacheRecords
,
4802 CallbackBeforeStartQuery BeforeStartCallback
, void *context
)
4805 DNSQuestion
*restart
= mDNSNULL
;
4807 if (!m
->mDNS_busy
) LogMsg("mDNSCoreRestartAddressQueries: ERROR!! Lock not held");
4809 // 1. Flush the cache records
4810 if (flushCacheRecords
) flushCacheRecords(m
);
4812 // 2. Even though we may have purged the cache records above, before it can generate RMV event
4813 // we are going to stop the question. Hence we need to deliver the RMV event before we
4814 // stop the question.
4816 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
4817 // application callback can potentially stop the current question (detected by CurrentQuestion) or
4818 // *any* other question which could be the next one that we may process here. RestartQuestion
4819 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
4820 // if the "next" question is stopped while the CurrentQuestion is stopped
4822 if (m
->RestartQuestion
)
4823 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
4824 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
4826 m
->RestartQuestion
= m
->Questions
;
4827 while (m
->RestartQuestion
)
4829 q
= m
->RestartQuestion
;
4830 m
->RestartQuestion
= q
->next
;
4831 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
4832 // question) through their "nta" pointer. Normally when the original query stops, it stops the
4833 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
4834 // question followed by the original query that refers to this GetZoneData question, we will end up
4835 // freeing the GetZoneData question and then start the "freed" question at the end.
4837 if (IsGetZoneDataQuestion(q
))
4839 DNSQuestion
*refq
= q
->next
;
4840 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
4841 // debug stuff, we just try to find the referencing question and don't do much with it
4844 if (q
== &refq
->nta
->question
)
4846 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq
, refq
->qname
.c
, DNSTypeName(refq
->qtype
), q
);
4853 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
4854 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
&& q
->qtype
!= kDNSType_CNAME
) continue;
4856 // If the search domains did not change, then we restart all the queries. Otherwise, only
4857 // for queries for which we "might" have appended search domains ("might" because we may
4858 // find results before we apply search domains even though AppendSearchDomains is set to 1)
4859 if (!SearchDomainsChanged
|| q
->AppendSearchDomains
)
4861 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
4862 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
4863 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
4864 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
4865 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
4866 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
4867 // for the original query using these cache entries as ADDs were never delivered using these cache
4868 // entries and hence this order is needed.
4870 // If the query is suppressed, the RMV events won't be delivered
4871 if (!CacheRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
4873 // SuppressQuery status does not affect questions that are answered using local records
4874 if (!LocalRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
4876 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q
,
4877 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->AppendSearchDomains
, q
->qnameOrig
);
4878 mDNS_StopQuery_internal(m
, q
);
4879 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
4880 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
4883 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q
->qnameOrig
);
4884 AssignDomainName(&q
->qname
, q
->qnameOrig
);
4885 mDNSPlatformMemFree(q
->qnameOrig
);
4886 q
->qnameOrig
= mDNSNULL
;
4887 q
->RetryWithSearchDomains
= ApplySearchDomainsFirst(q
) ? 1 : 0;
4889 q
->SearchListIndex
= 0;
4895 // 3. Callback before we start the query
4896 if (BeforeStartCallback
) BeforeStartCallback(m
, context
);
4898 // 4. Restart all the stopped queries
4902 restart
= restart
->next
;
4904 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
4905 mDNS_StartQuery_internal(m
, q
);
4909 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
4913 #ifndef UNICAST_DISABLED
4914 // Retrigger all our uDNS questions
4915 if (m
->CurrentQuestion
)
4916 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
4917 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4918 m
->CurrentQuestion
= m
->Questions
;
4919 while (m
->CurrentQuestion
)
4921 q
= m
->CurrentQuestion
;
4922 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
4923 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
)) ActivateUnicastQuery(m
, q
, mDNStrue
);
4927 // Retrigger all our mDNS questions
4928 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
4929 mDNSCoreRestartQuestion(m
, q
);
4932 // restart question if it's multicast and currently active
4933 mDNSexport
void mDNSCoreRestartQuestion(mDNS
*const m
, DNSQuestion
*q
)
4935 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
4937 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
4938 q
->RequestUnicast
= 2; // Set to 2 because is decremented once *before* we check it
4939 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4940 q
->RecentAnswerPkts
= 0;
4941 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
4942 m
->NextScheduledQuery
= m
->timenow
;
4946 // restart the probe/announce cycle for multicast record
4947 mDNSexport
void mDNSCoreRestartRegistration(mDNS
*const m
, AuthRecord
*rr
, int announceCount
)
4949 if (!AuthRecord_uDNS(rr
))
4951 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
4952 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
4954 // announceCount < 0 indicates default announce count should be used
4955 if (announceCount
< 0)
4956 announceCount
= InitialAnnounceCount
;
4957 if (rr
->AnnounceCount
< announceCount
)
4958 rr
->AnnounceCount
= announceCount
;
4959 rr
->AnnounceCount
= InitialAnnounceCount
;
4960 rr
->SendNSECNow
= mDNSNULL
;
4961 InitializeLastAPTime(m
, rr
);
4965 // ***************************************************************************
4966 #if COMPILER_LIKES_PRAGMA_MARK
4968 #pragma mark - Power Management (Sleep/Wake)
4971 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
4973 #ifndef IDLESLEEPCONTROL_DISABLED
4974 mDNSBool allowSleep
= mDNStrue
;
4979 if (m
->SystemSleepOnlyIfWakeOnLAN
)
4981 // Don't sleep if we are a proxy for any services
4982 if (m
->ProxyRecords
)
4984 allowSleep
= mDNSfalse
;
4985 mDNS_snprintf(reason
, sizeof(reason
), "sleep proxy for %d records", m
->ProxyRecords
);
4986 LogInfo("Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
4989 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
4991 // Scan the list of active interfaces
4992 NetworkInterfaceInfo
*intf
;
4993 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
4995 if (intf
->McastTxRx
&& !intf
->Loopback
)
4997 // Disallow sleep if this interface doesn't support NetWake
5000 allowSleep
= mDNSfalse
;
5001 mDNS_snprintf(reason
, sizeof(reason
), "%s does not support NetWake", intf
->ifname
);
5002 LogInfo("Sleep disabled because %s does not support NetWake", intf
->ifname
);
5006 // Disallow sleep if there is no sleep proxy server
5007 if (FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
) == mDNSNULL
)
5009 allowSleep
= mDNSfalse
;
5010 mDNS_snprintf(reason
, sizeof(reason
), "%s does not support NetWake", intf
->ifname
);
5011 LogInfo("Sleep disabled because %s has no sleep proxy", intf
->ifname
);
5019 // Call the platform code to enable/disable sleep
5020 mDNSPlatformSetAllowSleep(m
, allowSleep
, reason
);
5021 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5024 mDNSlocal mDNSBool
mDNSUpdateOkToSend(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSu32 scopeid
)
5026 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5027 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5029 if (AuthRecord_uDNS(rr
) || mDNSOpaque16IsZero(rr
->updateid
) || m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
5032 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5033 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5034 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5035 // updateid and we should have returned from above.
5037 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5038 // platform function to extract the value from "intf" everytime.
5040 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
5041 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
5047 mDNSlocal mStatus
UpdateKeepaliveRData(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
)
5049 mDNSu16 newrdlength
;
5050 mDNSAddr laddr
, raddr
;
5051 mDNSIPPort lport
, rport
;
5052 mDNSu32 timeout
, seq
, ack
;
5062 RData
*n
= rr
->NewRData
;
5064 LogMsg("UpdateKeepaliveRData: Update was queued on %s", ARDisplayString(m
, rr
));
5066 rr
->NewRData
= mDNSNULL
;
5067 if (rr
->UpdateCallback
)
5068 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
);
5071 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
5072 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
5074 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, &seq
, &ack
, &lport
, &rport
, &win
);
5075 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(lport
) ||
5076 mDNSIPPortIsZero(rport
))
5078 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, &raddr
, rport
.NotAnInteger
);
5079 return mStatus_UnknownErr
;
5082 // If this keepalive packet would be sent on a different interface than the current one that we are processing
5083 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
5084 // this DNS NULL record, it does not send any keepalives as it does not have all the information
5086 ret
= mDNSPlatformRetrieveTCPInfo(m
, &laddr
, &lport
, &raddr
, &rport
, &mti
);
5087 if (ret
!= mStatus_NoError
)
5089 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret
);
5093 if (mti
.IntfId
!= intf
->InterfaceID
)
5095 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti %p, Interface %p", mti
.IntfId
, intf
->InterfaceID
);
5096 return mStatus_BadParamErr
;
5099 if (laddr
.type
== mDNSAddrType_IPv4
)
5100 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d h=%#a d=%#a l=%u r=%u s=%u a=%u w=%u", timeout
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), mti
.seq
, mti
.ack
, mti
.window
);
5102 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d H=%#a D=%#a l=%u%u r=%u%u s=%u a=%u w=%u", timeout
, &laddr
, &raddr
, lport
.b
[0], lport
.b
[1], rport
.b
[0], rport
.b
[1], rport
.NotAnInteger
, mti
.seq
, mti
.ack
, mti
.window
);
5104 // Did we insert a null byte at the end ?
5105 if (newrdlength
== (sizeof(txt
.c
) - 1))
5107 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m
, rr
));
5108 return mStatus_NoMemoryErr
;
5111 // Include the length for the null byte at the end
5112 txt
.c
[0] = newrdlength
+ 1;
5113 // Account for the first length byte and the null byte at the end
5116 rdsize
= newrdlength
> sizeof(RDataBody
) ? newrdlength
: sizeof(RDataBody
);
5117 newrd
= mDNSPlatformMemAllocate(sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
5118 if (!newrd
) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr
; }
5120 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
5121 mDNSPlatformMemCopy(&newrd
->u
, txt
.c
, newrdlength
);
5123 rr
->NewRData
= newrd
;
5124 rr
->newrdlength
= newrdlength
;
5125 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrd
))
5127 LogMsg("UpdateKeepaliveRData: ValidateRData failed %s", ARDisplayString(m
, rr
));
5128 return mStatus_BadParamErr
;
5131 // We don't send goodbyes for non-shared records and hence updating here should be fine
5132 CompleteRDataUpdate(m
, rr
);
5134 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m
, rr
));
5135 return mStatus_NoError
;
5138 mDNSlocal
void SendSPSRegistrationForOwner(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
, const OwnerOptData
*const owner
)
5140 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
5141 const int sps
= intf
->NextSPSAttempt
/ 3;
5146 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
5147 if (!intf
->SPSAddr
[sps
].type
)
5149 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
5150 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
5151 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
5152 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
5156 // Mark our mDNS records (not unicast records) for transfer to SPS
5157 if (mDNSOpaque16IsZero(id
))
5159 // We may have to register this record over multiple interfaces and we don't want to
5160 // overwrite the id. We send the registration over interface X with id "IDX" and before
5161 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
5162 // for "IDX". Hence, we want to use the same ID across all interfaces.
5164 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
5165 // option check below will set the same ID across the records from the same owner. Records
5166 // with different owner option gets different ID.
5167 msgid
= mDNS_NewMessageID(m
);
5168 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5169 if (rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
5170 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
5171 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
5173 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
5174 // When we are registering on the first interface, rr->updateid is zero in which case
5175 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
5176 // At the end, all the updates sent across all the interfaces with the same ID.
5177 if (mDNSOpaque16IsZero(rr
->updateid
))
5178 rr
->updateid
= msgid
;
5180 msgid
= rr
->updateid
;
5188 mDNSu8
*p
= m
->omsg
.data
;
5189 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
5190 // For now we follow that same logic for SPS registrations too.
5191 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
5192 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
5193 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
5195 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5196 if (rr
->SendRNow
|| mDNSUpdateOkToSend(m
, rr
, intf
, scopeid
))
5198 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
5201 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
5203 // If we can't update the keepalive record, don't send it
5204 if (mDNS_KeepaliveRecord(&rr
->resrec
) && (UpdateKeepaliveRData(m
, rr
, intf
) != mStatus_NoError
))
5206 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
5208 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
5213 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
5214 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
5215 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
5216 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
5218 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
5221 LogSPS("SendSPSRegistration put %s 0x%x 0x%x (updateid %d) %s", intf
->ifname
, rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(m
->omsg
.h
.id
), ARDisplayString(m
, rr
));
5222 rr
->SendRNow
= mDNSNULL
;
5223 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
5224 rr
->LastAPTime
= m
->timenow
;
5225 // should be initialized above
5226 if (mDNSOpaque16IsZero(rr
->updateid
)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m
, rr
));
5227 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
5228 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
5234 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
5238 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
5239 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
5240 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
5241 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
5242 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
5243 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
5244 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
5245 if (!owner
->HMAC
.l
[0]) // If no owner data,
5246 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]); // use our own interface information
5247 else // otherwise, use the owner data we were given
5249 opt
.resrec
.rdata
->u
.opt
[1].u
.owner
= *owner
;
5250 opt
.resrec
.rdata
->u
.opt
[1].opt
= kDNSOpt_Owner
;
5251 opt
.resrec
.rdata
->u
.opt
[1].optlen
= DNSOpt_Owner_Space(&owner
->HMAC
, &owner
->IMAC
) - 4;
5253 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
5254 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
5256 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
5261 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
5262 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
5263 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
5264 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSNULL
, mDNSfalse
);
5265 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
5266 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv6
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
5268 LogSPS("SendSPSRegistration %d %##s failed to send to IPv6 address; will try IPv4 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
5269 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_A
;
5270 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
5277 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
5280 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
5283 mDNSlocal mDNSBool
RecordIsFirstOccurrenceOfOwner(mDNS
*const m
, const AuthRecord
*const rr
)
5286 for (ar
= m
->ResourceRecords
; ar
&& ar
!= rr
; ar
=ar
->next
)
5287 if (mDNSPlatformMemSame(&rr
->WakeUp
, &ar
->WakeUp
, sizeof(rr
->WakeUp
))) return mDNSfalse
;
5291 mDNSlocal
void mDNSCoreStoreProxyRR(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, AuthRecord
*const rr
)
5293 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
5294 AuthRecord
*newRR
= mDNSPlatformMemAllocate(sizeof(AuthRecord
));
5296 if ((intf
== mDNSNULL
) || (newRR
== mDNSNULL
))
5301 mDNSPlatformMemZero(newRR
, sizeof(AuthRecord
));
5302 mDNS_SetupResourceRecord(newRR
, mDNSNULL
, InterfaceID
, rr
->resrec
.rrtype
,
5303 rr
->resrec
.rroriginalttl
, rr
->resrec
.RecordType
,
5304 rr
->ARType
, mDNSNULL
, mDNSNULL
);
5306 AssignDomainName(&newRR
->namestorage
, &rr
->namestorage
);
5307 newRR
->resrec
.rdlength
= DomainNameLength(rr
->resrec
.name
);
5308 newRR
->resrec
.rdata
->u
.name
.c
[0] = 0;
5309 AssignDomainName(&newRR
->resrec
.rdata
->u
.name
, rr
->resrec
.name
);
5310 newRR
->resrec
.namehash
= DomainNameHashValue(newRR
->resrec
.name
);
5311 newRR
->resrec
.rrclass
= rr
->resrec
.rrclass
;
5313 if (intf
->ip
.type
== mDNSAddrType_IPv4
)
5315 newRR
->resrec
.rdata
->u
.ipv4
= rr
->resrec
.rdata
->u
.ipv4
;
5319 newRR
->resrec
.rdata
->u
.ipv6
= rr
->resrec
.rdata
->u
.ipv6
;
5321 SetNewRData(&newRR
->resrec
, mDNSNULL
, 0);
5323 // Insert the new node at the head of the list.
5324 newRR
->next
= intf
->SPSRRSet
;
5325 intf
->SPSRRSet
= newRR
;
5328 // Some records are interface specific and some are not. The ones that are supposed to be registered
5329 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
5330 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
5331 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
5332 // registration on all the interfaces
5333 mDNSlocal
void SPSInitRecordsBeforeUpdate(mDNS
*const m
, mDNSOpaque64 updateIntID
)
5336 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID
.l
[1], updateIntID
.l
[0]);
5338 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
5339 // make sure that the old sleep proxy records are removed.
5340 mDNSCoreFreeProxyRR(m
);
5342 // For records that are registered only on a specific interface, mark only that bit as it will
5343 // never be registered on any other interface. For others, it should be sent on all interfaces.
5344 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
5346 if (AuthRecord_uDNS(ar
))
5350 ar
->updateid
= zeroID
;
5351 if (!ar
->resrec
.InterfaceID
)
5353 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID
.l
[1], updateIntID
.l
[0], ARDisplayString(m
, ar
));
5354 ar
->updateIntID
= updateIntID
;
5358 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
5360 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, ar
->resrec
.InterfaceID
, mDNStrue
);
5361 if ((scopeid
< (sizeof(updateIntID
) * mDNSNBBY
)) && bit_get_opaque64(updateIntID
, scopeid
))
5363 ar
->updateIntID
= zeroOpaque64
;
5364 bit_set_opaque64(ar
->updateIntID
, scopeid
);
5365 LogSPS("Setting scopeid(%d) 0x%x 0x%x for %s", scopeid
, ar
->updateIntID
.l
[1], ar
->updateIntID
.l
[0], ARDisplayString(m
, ar
));
5369 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid
);
5372 // Store the A and AAAA records that we registered with the sleep proxy.
5373 // We will use this to prevent spurious name conflicts that may occur when we wake up
5374 if (ar
->resrec
.rrtype
== kDNSType_A
|| ar
->resrec
.rrtype
== kDNSType_AAAA
)
5376 mDNSCoreStoreProxyRR(m
, ar
->resrec
.InterfaceID
, ar
);
5381 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
)
5384 OwnerOptData owner
= zeroOwner
;
5386 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
5388 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
5390 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)) && RecordIsFirstOccurrenceOfOwner(m
, ar
))
5393 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
5398 // RetrySPSRegistrations is called from SendResponses, with the lock held
5399 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
5402 NetworkInterfaceInfo
*intf
;
5404 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
5405 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5406 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
5407 intf
->NextSPSAttemptTime
++;
5409 // Retry any record registrations that are due
5410 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5411 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
5413 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5415 // If we still have registrations pending on this interface, send it now
5416 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
5417 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
5418 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
5420 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
5421 SendSPSRegistration(m
, intf
, rr
->updateid
);
5426 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
5427 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5428 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
5429 intf
->NextSPSAttempt
++;
5432 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
5434 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
5435 int sps
= (int)(question
- intf
->NetWakeResolve
);
5437 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
5439 if (!AddRecord
) return; // Don't care about REMOVE events
5440 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
5442 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
5444 if (answer
->rrtype
== kDNSType_SRV
)
5446 // 1. Got the SRV record; now look up the target host's IPv6 link-local address
5447 mDNS_StopQuery(m
, question
);
5448 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
5449 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
5450 question
->qtype
= kDNSType_AAAA
;
5451 mDNS_StartQuery(m
, question
);
5453 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
5455 // 2. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
5456 mDNS_StopQuery(m
, question
);
5457 question
->ThisQInterval
= -1;
5458 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
5459 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
5461 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
5464 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== 0)
5466 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
5467 mDNS_StopQuery(m
, question
);
5468 LogSPS("NetWakeResolve: SPS %d %##s has no IPv6 address, will try IPv4 instead", sps
, question
->qname
.c
);
5469 question
->qtype
= kDNSType_A
;
5470 mDNS_StartQuery(m
, question
);
5472 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
5474 // 4. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
5475 mDNS_StopQuery(m
, question
);
5476 question
->ThisQInterval
= -1;
5477 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
5478 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
5480 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
5485 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
5488 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5489 if (mDNS_KeepaliveRecord(&rr
->resrec
) || (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
)))
5494 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
)
5497 m
->SleepState
= SleepState_Sleeping
;
5499 #ifndef UNICAST_DISABLED
5500 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
5501 #endif /* UNICAST_DISABLED */
5503 // Mark all the records we need to deregister and send them
5504 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5505 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
5506 rr
->ImmedAnswer
= mDNSInterfaceMark
;
5510 mDNSlocal mDNSBool
skipSameSubnetRegistration(mDNS
*const m
, mDNSInterfaceID
*regID
, mDNSu32 count
, mDNSInterfaceID intfid
)
5512 NetworkInterfaceInfo
*intf
;
5513 NetworkInterfaceInfo
*newIntf
;
5516 newIntf
= FirstInterfaceForID(m
, intfid
);
5517 if (newIntf
== mDNSNULL
)
5519 LogMsg("%s : Could not get Interface for id %d", __func__
, intfid
);
5523 for ( i
= 0; i
< count
; i
++)
5525 intf
= FirstInterfaceForID(m
, regID
[i
]);
5526 if (intf
== mDNSNULL
)
5528 LogMsg("%s : Could not get Interface for id %d", __func__
, regID
[i
]);
5532 if ((newIntf
->ip
.type
== mDNSAddrType_IPv4
) &&
5533 (((intf
->ip
.ip
.v4
.NotAnInteger
^ newIntf
->ip
.ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0))
5535 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__
, intf
->ifname
);
5539 if ( (newIntf
->ip
.type
== mDNSAddrType_IPv6
) &&
5540 ((((intf
->ip
.ip
.v6
.l
[0] ^ newIntf
->ip
.ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
5541 (((intf
->ip
.ip
.v6
.l
[1] ^ newIntf
->ip
.ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
5542 (((intf
->ip
.ip
.v6
.l
[2] ^ newIntf
->ip
.ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
5543 (((intf
->ip
.ip
.v6
.l
[3] ^ newIntf
->ip
.ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0)))
5545 LogSPS("%s : Already registered for the same subnet (IPv6) for interface %s", __func__
, intf
->ifname
);
5552 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
5553 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
5555 mDNSBool SendGoodbyes
= mDNStrue
;
5556 const CacheRecord
*sps
[3] = { mDNSNULL
};
5557 mDNSOpaque64 updateIntID
= zeroOpaque64
;
5558 mDNSInterfaceID registeredIntfIDS
[128];
5559 mDNSu32 registeredCount
= 0;
5561 m
->NextScheduledSPRetry
= m
->timenow
;
5563 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
5564 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
5565 else // If we have at least one advertised service
5567 NetworkInterfaceInfo
*intf
;
5568 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5570 if (!intf
->NetWake
) LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
5572 // Check if we have already registered with a sleep proxy for this subnet
5573 if (skipSameSubnetRegistration(m
, registeredIntfIDS
, registeredCount
, intf
->InterfaceID
))
5575 LogSPS("%s : Skipping sleep proxy registration on %s", __func__
, intf
->ifname
);
5579 #if APPLE_OSX_mDNSResponder
5580 else if (ActivateLocalProxy(m
, intf
->ifname
) == mStatus_NoError
)
5582 SendGoodbyes
= mDNSfalse
;
5583 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
5584 // This will leave m->SleepState set to SleepState_Transferring,
5585 // which is okay because with no outstanding resolves, or updates in flight,
5586 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
5588 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
5591 #endif // APPLE_OSX_mDNSResponder
5594 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
5595 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
5596 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
5601 SendGoodbyes
= mDNSfalse
;
5602 intf
->NextSPSAttempt
= 0;
5603 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
5605 #if APPLE_OSX_mDNSResponder
5606 // Before we start the sleep processing, stop IPv6 advertisements
5607 mDNSPlatformToggleInterfaceAdvt(m
, mDNStrue
);
5609 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
5610 // Now we know for sure that we have to wait for registration to complete on this interface.
5611 if (scopeid
< (sizeof(updateIntID
) * mDNSNBBY
))
5612 bit_set_opaque64(updateIntID
, scopeid
);
5614 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
5618 if (intf
->SPSAddr
[i
].type
)
5619 { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
); *(long*)0 = 0; }
5620 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
5621 { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
); *(long*)0 = 0; }
5623 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
5624 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
5625 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
5628 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
5629 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
5630 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
5631 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
5633 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
5634 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
5643 // If we have at least one interface on which we are registering with an external sleep proxy,
5644 // initialize all the records appropriately.
5645 if (!mDNSOpaque64IsZero(&updateIntID
)) SPSInitRecordsBeforeUpdate(m
, updateIntID
);
5647 if (SendGoodbyes
) // If we didn't find even one Sleep Proxy
5649 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
5650 SendSleepGoodbyes(m
);
5654 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
5655 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
5656 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
5657 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
5661 LogSPS("%s (old state %d) at %ld", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
5663 if (sleep
&& !m
->SleepState
) // Going to sleep
5666 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
5669 mDNSu8 oldstate
= m
->SPSState
;
5670 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
5672 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
5673 mDNS_ReclaimLockAfterCallback();
5676 m
->SleepState
= SleepState_Transferring
;
5677 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
5679 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
5680 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
5681 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
5686 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
5687 BeginSleepProcessing(m
);
5690 #ifndef UNICAST_DISABLED
5693 #if APPLE_OSX_mDNSResponder
5694 RemoveAutoTunnel6Record(m
);
5696 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m
->SleepState
,
5697 m
->SleepState
== SleepState_Transferring
? "Transferring" :
5698 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
5701 else if (!sleep
) // Waking up
5706 NetworkInterfaceInfo
*intf
;
5709 // Reset SleepLimit back to 0 now that we're awake again.
5712 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
5713 if (m
->SleepState
!= SleepState_Awake
)
5715 m
->SleepState
= SleepState_Awake
;
5717 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
5718 // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
5719 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
5720 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
5721 m
->DelaySleep
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 16);
5724 if (m
->SPSState
== 3)
5727 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
);
5730 // ... and the same for NextSPSAttempt
5731 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
5733 // Restart unicast and multicast queries
5734 mDNSCoreRestartQueries(m
);
5736 // and reactivtate service registrations
5737 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
5738 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
5740 // 2. Re-validate our cache records
5741 FORALL_CACHERECORDS(slot
, cg
, cr
)
5743 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
5746 // 3. Retrigger probing and announcing for all our authoritative records
5747 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
5748 if (AuthRecord_uDNS(rr
))
5750 ActivateUnicastRegistration(m
, rr
);
5754 mDNSCoreRestartRegistration(m
, rr
, -1);
5757 // 4. Refresh NAT mappings
5758 // We don't want to have to assume that all hardware can necessarily keep accurate
5759 // track of passage of time while asleep, so on wake we refresh our NAT mappings
5760 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
5761 // When we get a network configuration change, mDNSMacOSXNetworkChanged calls uDNS_SetupDNSConfig, which calls
5762 // mDNS_SetPrimaryInterfaceInfo, which then sets m->retryGetAddr to immediately request our external address from the NAT gateway.
5763 m
->retryIntervalGetAddr
= NATMAP_INIT_RETRY
;
5764 m
->retryGetAddr
= m
->timenow
+ mDNSPlatformOneSecond
* 5;
5765 LogInfo("mDNSCoreMachineSleep: retryGetAddr in %d %d", m
->retryGetAddr
- m
->timenow
, m
->timenow
);
5766 RecreateNATMappings(m
);
5771 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
5775 NetworkInterfaceInfo
*intf
;
5779 if (m
->DelaySleep
) goto notready
;
5781 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
5782 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
5784 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
5786 // See if we might need to retransmit any lost Sleep Proxy Registrations
5787 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5788 if (intf
->NextSPSAttempt
>= 0)
5790 if (now
- intf
->NextSPSAttemptTime
>= 0)
5792 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
5793 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
5794 SendSPSRegistration(m
, intf
, zeroID
);
5795 // Don't need to "goto notready" here, because if we do still have record registrations
5796 // that have not been acknowledged yet, we'll catch that in the record list scan below.
5799 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
5800 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
5803 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
5804 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5806 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
5807 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
5809 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
5810 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
5815 // Scan list of registered records
5816 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
5817 if (!AuthRecord_uDNS(rr
))
5818 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
5819 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS updateIntID 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto spsnotready
; }
5821 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
5822 for (q
= m
->Questions
; q
; q
= q
->next
)
5823 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
5825 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5829 // Scan list of registered records
5830 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
5831 if (AuthRecord_uDNS(rr
))
5833 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
5834 { LogSPS("mDNSCoreReadyForSleep: waiting for Record updateIntID 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
)); goto notready
; }
5835 #if APPLE_OSX_mDNSResponder
5836 if (!RecordReadyForSleep(m
, rr
)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m
, rr
)); goto notready
; }
5845 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
5846 // and allow up to ten seconds more to complete wide-area deregistration instead
5847 if (now
- m
->SleepLimit
>= 0)
5849 LogMsg("Failed to register with SPS, now sending goodbyes");
5851 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5852 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
5854 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
5855 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
5856 mDNS_DeactivateNetWake_internal(m
, intf
);
5859 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
5860 if (!AuthRecord_uDNS(rr
))
5861 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
5863 LogSPS("ReadyForSleep clearing updateIntID 0x%x 0x%x (updateid %d) for %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
5864 rr
->updateIntID
= zeroOpaque64
;
5867 // We'd really like to allow up to ten seconds more here,
5868 // but if we don't respond to the sleep notification within 30 seconds
5869 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
5870 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
5871 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
5872 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
5873 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
5875 SendSleepGoodbyes(m
);
5883 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
)
5887 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
5888 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
5889 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
5890 // and if that happens we don't want to just give up and go back to sleep and never try again.
5891 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
5893 NATTraversalInfo
*nat
;
5894 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
5895 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
5897 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
5898 if (e
- t
> 0) e
= t
;
5899 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
5900 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
5901 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
5902 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
5903 nat
->retryInterval
/ mDNSPlatformOneSecond
,
5904 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
5905 (t
- now
) / mDNSPlatformOneSecond
);
5908 // This loop checks both the time we need to renew wide-area registrations,
5909 // and the time we need to renew Sleep Proxy registrations
5910 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
5911 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
5913 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
5914 if (e
- t
> 0) e
= t
;
5915 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
5916 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
5917 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
5918 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
5919 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
5925 // ***************************************************************************
5926 #if COMPILER_LIKES_PRAGMA_MARK
5928 #pragma mark - Packet Reception Functions
5931 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
5933 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
5934 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
5936 mDNSu8
*responseptr
= response
->data
;
5937 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
5938 const mDNSu8
*ptr
= query
->data
;
5940 mDNSu32 maxttl
= 0x70000000;
5943 // Initialize the response fields so we can answer the questions
5944 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
5947 // *** 1. Write out the list of questions we are actually going to answer with this packet
5951 maxttl
= kStaticCacheTTL
;
5952 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
5955 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
5956 if (!ptr
) return(mDNSNULL
);
5958 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
5960 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
5961 { // then put the question in the question section
5962 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
5963 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
5964 break; // break out of the ResponseRecords loop, and go on to the next question
5969 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
5973 // *** 2. Write Answers
5975 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5976 if (rr
->NR_AnswerTo
)
5978 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
5979 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
5980 if (p
) responseptr
= p
;
5981 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
5985 // *** 3. Write Additionals
5987 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
5988 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
5990 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
5991 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
5992 if (p
) responseptr
= p
;
5993 else debugf("GenerateUnicastResponse: No more space for additionals");
5996 return(responseptr
);
5999 // AuthRecord *our is our Resource Record
6000 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
6001 // Returns 0 if there is no conflict
6002 // Returns +1 if there was a conflict and we won
6003 // Returns -1 if there was a conflict and we lost and have to rename
6004 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
6006 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
6007 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
6008 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
6009 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
6011 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
6012 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
6013 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
6014 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
6016 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
6017 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
6018 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
6019 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
6021 LogMsg("CompareRData ERROR: Invalid state");
6025 // See if we have an authoritative record that's identical to this packet record,
6026 // whose canonical DependentOn record is the specified master record.
6027 // The DependentOn pointer is typically used for the TXT record of service registrations
6028 // It indicates that there is no inherent conflict detection for the TXT record
6029 // -- it depends on the SRV record to resolve name conflicts
6030 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
6031 // pointer chain (if any) to make sure we reach the canonical DependentOn record
6032 // If the record has no DependentOn, then just return that record's pointer
6033 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6034 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
6036 const AuthRecord
*r1
;
6037 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
6039 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
6041 const AuthRecord
*r2
= r1
;
6042 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
6043 if (r2
== master
) return(mDNStrue
);
6046 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
6048 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
6050 const AuthRecord
*r2
= r1
;
6051 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
6052 if (r2
== master
) return(mDNStrue
);
6058 // Find the canonical RRSet pointer for this RR received in a packet.
6059 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
6060 // pointers (if any) to make sure we return the canonical member of this name/type/class
6061 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6062 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
6064 const AuthRecord
*rr
;
6065 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6067 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
6069 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
6076 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
6077 // as one of our records (our) but different rdata.
6078 // 1. If our record is not a type that's supposed to be unique, we don't care.
6079 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
6080 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
6081 // points to our record, ignore this conflict (e.g. the packet record matches one of our
6082 // TXT records, and that record is marked as dependent on 'our', its SRV record).
6083 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
6084 // are members of the same RRSet, then this is not a conflict.
6085 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
6087 // If not supposed to be unique, not a conflict
6088 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
6090 // If a dependent record, not a conflict
6091 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
6094 // If the pktrr matches a member of ourset, not a conflict
6095 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
6096 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
6097 if (pktset
== ourset
) return(mDNSfalse
);
6099 // For records we're proxying, where we don't know the full
6100 // relationship between the records, having any matching record
6101 // in our AuthRecords list is sufficient evidence of non-conflict
6102 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
6105 // Okay, this is a conflict
6109 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
6110 // the record list and/or question list.
6111 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
6112 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
6113 DNSQuestion
*q
, AuthRecord
*our
)
6116 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
6117 mDNSBool FoundUpdate
= mDNSfalse
;
6119 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
6121 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
6123 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
6125 FoundUpdate
= mDNStrue
;
6126 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
6128 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
6129 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
6130 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
6133 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
6134 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
6135 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
6137 // 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.
6138 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
6139 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
6142 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
6143 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
6144 our
->AnnounceCount
= InitialAnnounceCount
;
6145 InitializeLastAPTime(m
, our
);
6152 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
6153 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
6157 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6160 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
6162 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6165 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
6167 mDNSu32 slot
= HashSlot(pktrr
->name
);
6168 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, pktrr
);
6171 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
6173 if (!pktrr
->InterfaceID
)
6175 mDNSu16 id1
= (pktrr
->rDNSServer
? pktrr
->rDNSServer
->resGroupID
: 0);
6176 mDNSu16 id2
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
6177 match
= (id1
== id2
);
6179 else match
= (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
);
6181 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
6186 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
6187 // to check our lists and discard any stale duplicates of this record we already have
6188 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
6190 if (m
->CurrentRecord
)
6191 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
6192 m
->CurrentRecord
= thelist
;
6193 while (m
->CurrentRecord
)
6195 AuthRecord
*const rr
= m
->CurrentRecord
;
6196 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
6197 // Normally, the RDATA of the keepalive record will be different each time and hence we always
6198 // clean up the keepalive record.
6199 if (mDNS_KeepaliveRecord(&rr
->resrec
) || IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
6201 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
6202 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
6203 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
6204 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
6205 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6206 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
6208 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
6209 // new records could have been added to the end of the list as a result of that call.
6210 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
6211 m
->CurrentRecord
= rr
->next
;
6215 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
6216 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
6218 if (m
->CurrentRecord
)
6219 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
6220 m
->CurrentRecord
= thelist
;
6221 while (m
->CurrentRecord
)
6223 AuthRecord
*const rr
= m
->CurrentRecord
;
6224 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
6225 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
6227 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
6229 // We don't do this here because we know that the host is waking up at this point, so we don't send
6230 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
6231 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
6232 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
6233 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
6234 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
6235 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
6238 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
6239 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
6240 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
6241 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
6242 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
6243 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
6244 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
6245 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
6247 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
6248 // new records could have been added to the end of the list as a result of that call.
6249 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
6250 m
->CurrentRecord
= rr
->next
;
6254 // ProcessQuery examines a received query to see if we have any answers to give
6255 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
6256 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
6257 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
6259 mDNSBool FromLocalSubnet
= srcaddr
&& mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
6260 AuthRecord
*ResponseRecords
= mDNSNULL
;
6261 AuthRecord
**nrp
= &ResponseRecords
;
6262 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
6263 CacheRecord
**eap
= &ExpectedAnswers
;
6264 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
6265 DNSQuestion
**dqp
= &DupQuestions
;
6266 mDNSs32 delayresponse
= 0;
6267 mDNSBool SendLegacyResponse
= mDNSfalse
;
6269 mDNSu8
*responseptr
= mDNSNULL
;
6274 // *** 1. Look in Additional Section for an OPT record
6276 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
6279 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
6280 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
6282 const rdataOPT
*opt
;
6283 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
6284 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
6285 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
6286 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
6287 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
6289 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
6290 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
6293 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6297 // *** 2. Parse Question Section and mark potential answers
6300 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
6302 mDNSBool QuestionNeedsMulticastResponse
;
6303 int NumAnswersForThisQuestion
= 0;
6304 AuthRecord
*NSECAnswer
= mDNSNULL
;
6305 DNSQuestion pktq
, *q
;
6306 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
6307 if (!ptr
) goto exit
;
6309 // The only queries that *need* a multicast response are:
6310 // * Queries sent via multicast
6312 // * that don't have the kDNSQClass_UnicastResponse bit set
6313 // These queries need multicast responses because other clients will:
6314 // * suppress their own identical questions when they see these questions, and
6315 // * expire their cache records if they don't see the expected responses
6316 // For other queries, we may still choose to send the occasional multicast response anyway,
6317 // to keep our neighbours caches warm, and for ongoing conflict detection.
6318 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
6319 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
6320 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
6322 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
6323 // can result in user callbacks which may change the record list and/or question list.
6324 // Also note: we just mark potential answer records here, without trying to build the
6325 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
6326 // from that list while we're in the middle of trying to build it.
6327 if (m
->CurrentRecord
)
6328 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
6329 m
->CurrentRecord
= m
->ResourceRecords
;
6330 while (m
->CurrentRecord
)
6332 rr
= m
->CurrentRecord
;
6333 m
->CurrentRecord
= rr
->next
;
6334 if (AnyTypeRecordAnswersQuestion(&rr
->resrec
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
6336 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
6338 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
6339 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
6340 else if (ResourceRecordIsValidAnswer(rr
))
6342 NumAnswersForThisQuestion
++;
6343 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
6344 // unicast answer back to the source, because timeliness in answering probes is important.
6347 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
6348 // NR_AnswerTo == (mDNSu8*)~1 means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
6349 // NR_AnswerTo == (mDNSu8*)~0 means "definitely answer via multicast" (can't downgrade to unicast later)
6350 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
6351 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
6352 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
6353 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
6355 // We only mark this question for sending if it is at least one second since the last time we multicast it
6356 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
6357 // This is to guard against the case where someone blasts us with queries as fast as they can.
6358 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
6359 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
6360 rr
->NR_AnswerTo
= (mDNSu8
*)~0;
6362 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: (mDNSu8
*)~1;
6365 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
6367 // If we don't have any answers for this question, but we do own another record with the same name,
6368 // then we'll want to mark it to generate an NSEC record on this interface
6369 if (!NSECAnswer
) NSECAnswer
= rr
;
6374 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
6376 NumAnswersForThisQuestion
++;
6377 NSECAnswer
->SendNSECNow
= InterfaceID
;
6378 m
->NextScheduledResponse
= m
->timenow
;
6381 // If we couldn't answer this question, someone else might be able to,
6382 // so use random delay on response to reduce collisions
6383 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
6385 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6386 if (QuestionNeedsMulticastResponse
)
6388 // We only do the following accelerated cache expiration and duplicate question suppression processing
6389 // for non-truncated multicast queries with multicast responses.
6390 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
6391 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
6392 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
6393 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
6396 const mDNSu32 slot
= HashSlot(&pktq
.qname
);
6397 CacheGroup
*cg
= CacheGroupForName(m
, slot
, pktq
.qnamehash
, &pktq
.qname
);
6400 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
6401 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
6402 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6403 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
6405 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
6406 if (SameNameRecordAnswersQuestion(&cr
->resrec
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
6407 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
6410 eap
= &cr
->NextInKAList
;
6411 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6412 if (cr
->MPUnansweredQ
== 0 || m
->timenow
- cr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
6414 // Although MPUnansweredQ is only really used for multi-packet query processing,
6415 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
6416 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
6417 cr
->MPUnansweredQ
++;
6418 cr
->MPLastUnansweredQT
= m
->timenow
;
6419 cr
->MPExpectingKA
= mDNStrue
;
6424 // Check if this question is the same as any of mine.
6425 // We only do this for non-truncated queries. Right now it would be too complicated to try
6426 // to keep track of duplicate suppression state between multiple packets, especially when we
6427 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
6428 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6429 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
6431 for (q
= m
->Questions
; q
; q
=q
->next
)
6432 if (!q
->Target
.type
&& ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
6433 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
6434 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
6435 if (q
->qtype
== pktq
.qtype
&&
6436 q
->qclass
== pktq
.qclass
&&
6437 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
6438 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
6443 // *** 3. Now we can safely build the list of marked answers
6445 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
6446 if (rr
->NR_AnswerTo
) // If we marked the record...
6447 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
6450 // *** 4. Add additional records
6452 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
6455 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
6457 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
6459 // Get the record...
6460 CacheRecord
*ourcacherr
;
6461 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
6462 if (!ptr
) goto exit
;
6463 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
6465 // See if this Known-Answer suppresses any of our currently planned answers
6466 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
6467 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
6468 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
6470 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
6471 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
6473 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
6474 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
6476 if (srcaddr
->type
== mDNSAddrType_IPv4
)
6478 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
6480 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
6482 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
6484 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
6486 rr
->ImmedAnswer
= mDNSNULL
;
6487 rr
->ImmedUnicast
= mDNSfalse
;
6488 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6489 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
6495 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
6497 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6498 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
6499 // 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).
6500 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
6502 ourcacherr
->MPUnansweredKA
++;
6503 ourcacherr
->MPExpectingKA
= mDNSfalse
;
6507 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
6508 // any records that are suppressed by the Known Answer list in this packet.
6509 eap
= &ExpectedAnswers
;
6512 CacheRecord
*cr
= *eap
;
6513 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
6514 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
6515 else eap
= &cr
->NextInKAList
;
6518 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
6521 dqp
= &DupQuestions
;
6524 DNSQuestion
*q
= *dqp
;
6525 if (ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
6526 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
6527 else dqp
= &q
->NextInDQList
;
6531 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6535 // *** 6. Cancel any additionals that were added because of now-deleted records
6537 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
6538 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
6539 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
6542 // *** 7. Mark the send flags on the records we plan to send
6544 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
6546 if (rr
->NR_AnswerTo
)
6548 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
6549 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
6551 // If it's been a while since we multicast this, then send a multicast response for conflict detection, etc.
6552 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0)
6554 SendMulticastResponse
= mDNStrue
;
6555 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
6556 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
6557 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
6558 if (rr
->NR_AnswerTo
== (mDNSu8
*)~1) rr
->NR_AnswerTo
= (mDNSu8
*)~0;
6561 // If the client insists on a multicast response, then we'd better send one
6562 if (rr
->NR_AnswerTo
== (mDNSu8
*)~0) SendMulticastResponse
= mDNStrue
;
6563 else if (rr
->NR_AnswerTo
== (mDNSu8
*)~1) SendUnicastResponse
= mDNStrue
;
6564 else if (rr
->NR_AnswerTo
) SendLegacyResponse
= mDNStrue
;
6566 if (SendMulticastResponse
|| SendUnicastResponse
)
6568 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6569 rr
->ImmedAnswerMarkTime
= m
->timenow
;
6571 m
->NextScheduledResponse
= m
->timenow
;
6572 // If we're already planning to send this on another interface, just send it on all interfaces
6573 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
6574 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6577 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
6578 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
6579 if (srcaddr
->type
== mDNSAddrType_IPv4
)
6581 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
6582 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
6584 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
6586 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
6587 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
6591 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
6592 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
6593 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
6594 // else, for a simple unique record reply, we can reply immediately; no need for delay
6595 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
6596 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
6598 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== (mDNSu8
*)~0)
6600 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
6601 // If two clients on different interfaces do queries that invoke the same optional additional answer,
6602 // then the earlier client is out of luck
6603 rr
->ImmedAdditional
= InterfaceID
;
6604 // No need to set m->NextScheduledResponse here
6605 // We'll send these additional records when we send them, or not, as the case may be
6610 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
6612 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
6614 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6615 mDNSs32 oldss
= m
->SuppressSending
;
6616 if (oldss
&& delayresponse
)
6617 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
6619 // Pick a random delay:
6620 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
6621 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
6622 // This is an integer value, with resolution determined by the platform clock rate.
6623 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
6624 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
6625 // The +49 before dividing is to ensure we round up, not down, to ensure that even
6626 // on platforms where the native clock rate is less than fifty ticks per second,
6627 // we still guarantee that the final calculated delay is at least one platform tick.
6628 // We want to make sure we don't ever allow the delay to be zero ticks,
6629 // because if that happens we'll fail the Bonjour Conformance Test.
6630 // Our final computed delay is 20-120ms for normal delayed replies,
6631 // or 400-500ms in the case of multi-packet known-answer lists.
6632 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
6633 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
6634 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
6635 if (oldss
&& delayresponse
)
6636 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
6641 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
6643 if (SendLegacyResponse
)
6644 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
6647 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
6650 // *** 10. Finally, clear our link chains ready for use next time
6652 while (ResponseRecords
)
6654 rr
= ResponseRecords
;
6655 ResponseRecords
= rr
->NextResponse
;
6656 rr
->NextResponse
= mDNSNULL
;
6657 rr
->NR_AnswerTo
= mDNSNULL
;
6658 rr
->NR_AdditionalTo
= mDNSNULL
;
6661 while (ExpectedAnswers
)
6663 CacheRecord
*cr
= ExpectedAnswers
;
6664 ExpectedAnswers
= cr
->NextInKAList
;
6665 cr
->NextInKAList
= mDNSNULL
;
6667 // For non-truncated queries, we can definitively say that we should expect
6668 // to be seeing a response for any records still left in the ExpectedAnswers list
6669 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
6670 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
)
6672 cr
->UnansweredQueries
++;
6673 cr
->LastUnansweredTime
= m
->timenow
;
6674 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6675 if (cr
->UnansweredQueries
> 1)
6676 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
6677 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
6679 SetNextCacheCheckTimeForRecord(m
, cr
);
6682 // If we've seen multiple unanswered queries for this record,
6683 // then mark it to expire in five seconds if we don't get a response by then.
6684 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
6686 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6687 // Only show debugging message if this record was not about to expire anyway
6688 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
6689 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6690 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
6692 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
6694 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6695 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
6696 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
6697 // possible packet loss of up to 20% of the additional KA packets.)
6698 else if (cr
->MPUnansweredQ
* 4 > cr
->MPUnansweredKA
* 5 + 8)
6700 // We want to do this conservatively.
6701 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
6702 // then we don't want them to all hit the network simultaneously with their final expiration queries.
6703 // By setting the record to expire in four minutes, we achieve two things:
6704 // (a) the 90-95% final expiration queries will be less bunched together
6705 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
6706 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(cr
) - m
->timenow
) / 4;
6707 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
6708 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
6710 // Only show debugging message if this record was not about to expire anyway
6711 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
6712 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
6713 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
6715 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
6716 cr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
6717 cr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
6718 cr
->MPUnansweredKA
= 0;
6719 cr
->MPExpectingKA
= mDNSfalse
;
6721 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
6722 remain
= kDefaultReconfirmTimeForNoAnswer
;
6723 mDNS_Reconfirm_internal(m
, cr
, remain
);
6728 while (DupQuestions
)
6730 DNSQuestion
*q
= DupQuestions
;
6731 DupQuestions
= q
->NextInDQList
;
6732 q
->NextInDQList
= mDNSNULL
;
6733 i
= RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
6734 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
6735 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6", i
);
6738 return(responseptr
);
6741 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
6742 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
6743 const mDNSInterfaceID InterfaceID
)
6745 mDNSu8
*responseend
= mDNSNULL
;
6746 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
6747 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
6749 if (!InterfaceID
&& dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
))
6751 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6752 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
6753 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
6754 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
6755 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
6756 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
6757 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
6761 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
6762 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
6763 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
6764 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
6765 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
6766 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
6767 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
6769 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
6770 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
6772 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
6774 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
6775 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
6776 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
6777 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
6778 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
6779 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
6784 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
6788 (void)srcaddr
; // Unused
6789 for (s
= m
->DNSServers
; s
; s
= s
->next
)
6790 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
6795 struct UDPSocket_struct
6797 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
6800 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
, const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
)
6803 for (q
= m
->Questions
; q
; q
=q
->next
)
6805 if (!tcp
&& !q
->LocalSocket
) continue;
6806 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
6807 mDNSSameOpaque16(q
->TargetQID
, id
) &&
6808 q
->qtype
== question
->qtype
&&
6809 q
->qclass
== question
->qclass
&&
6810 q
->qnamehash
== question
->qnamehash
&&
6811 SameDomainName(&q
->qname
, &question
->qname
))
6817 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
6818 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
6819 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
6820 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
6826 for (q
= m
->Questions
; q
; q
=q
->next
)
6828 if (!q
->DuplicateOf
&& ResourceRecordAnswersUnicastResponse(&rr
->resrec
, q
))
6830 if (!mDNSOpaque16IsZero(q
->TargetQID
))
6832 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
6834 if (mDNSSameOpaque16(q
->TargetQID
, id
))
6839 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
6843 srcp
= q
->tcpSrcPort
;
6845 if (mDNSSameIPPort(srcp
, port
)) return(q
);
6847 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
6848 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
6849 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
6850 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
6851 q
->qname
.c
, DNSTypeName(q
->qtype
), &q
->Target
, mDNSVal16(srcp
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
6857 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
6865 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
6866 // Currently this applies only to rdata types containing more than one domainname,
6867 // or types where the domainname is not the last item in the structure.
6868 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
6872 case kDNSType_SOA
: return sizeof(rdataSOA
);
6873 case kDNSType_RP
: return sizeof(rdataRP
);
6874 case kDNSType_PX
: return sizeof(rdataPX
);
6875 default: return rr
->rdlength
;
6879 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
, mDNSBool Add
, const mDNSAddr
*sourceAddress
)
6881 CacheRecord
*rr
= mDNSNULL
;
6882 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
6884 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
6886 //if (RDLength > InlineCacheRDSize)
6887 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
6889 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
6890 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
6891 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
6894 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
6895 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
6896 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
6897 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
6898 rr
->DelayDelivery
= delay
;
6900 // If this is an oversized record with external storage allocated, copy rdata to external storage
6901 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
6902 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
6903 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
6904 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
6905 if (RDLength
> InlineCacheRDSize
)
6906 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
6908 rr
->next
= mDNSNULL
; // Clear 'next' pointer
6909 rr
->nsec
= mDNSNULL
;
6912 rr
->sourceAddress
= *sourceAddress
;
6916 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
6917 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
6918 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
6922 // Can't use the "cg->name" if we are not adding to the cache as the
6923 // CacheGroup may be released anytime if it is empty
6924 domainname
*name
= mDNSPlatformMemAllocate(DomainNameLength(cg
->name
));
6927 AssignDomainName(name
, cg
->name
);
6928 rr
->resrec
.name
= name
;
6932 ReleaseCacheRecord(m
, rr
);
6933 NoCacheAnswer(m
, &m
->rec
.r
);
6941 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
6943 rr
->TimeRcvd
= m
->timenow
;
6944 rr
->resrec
.rroriginalttl
= ttl
;
6945 rr
->UnansweredQueries
= 0;
6946 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
6947 rr
->MPUnansweredQ
= 0;
6948 rr
->MPUnansweredKA
= 0;
6949 rr
->MPExpectingKA
= mDNSfalse
;
6951 SetNextCacheCheckTimeForRecord(m
, rr
);
6954 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
6957 const mDNSu32 slot
= HashSlot(&q
->qname
);
6958 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
6959 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
6960 if (rr
->CRActiveQuestion
== q
)
6962 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
6963 RefreshCacheRecord(m
, rr
, lease
);
6967 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
6969 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
6970 else if (LLQType
== uDNS_LLQ_Events
)
6972 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
6973 if (ttl
== 0xFFFFFFFF) ttl
= 0;
6974 else ttl
= kLLQ_DefLease
;
6976 else // else not LLQ (standard uDNS response)
6978 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
6979 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
6980 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
6982 // Adjustment factor to avoid race condition:
6983 // 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.
6984 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
6985 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
6986 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
6987 // We adjust the 100 second TTL to 126. This means that when we do our 80% query at 101 seconds,
6988 // the cached copy at our local caching server will already have expired, so the server will be forced
6989 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
6992 // For mDNS, TTL zero means "delete this record"
6993 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
6994 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
6995 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
6996 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
6997 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
6998 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
6999 // (with the current code) result in the server having even less than three seconds to respond
7000 // before we deleted the record and reported a "remove" event to any active questions.
7001 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
7002 // then things really break (e.g. we end up making a negative cache entry).
7003 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
7004 if (ttl
< 15) ttl
= 15;
7010 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
7012 mDNSlocal mDNSBool
IsResponseAcceptable(mDNS
*const m
, const CacheRecord
*crlist
, DNSQuestion
*q
, mDNSBool
*nseclist
)
7014 CacheRecord
*const newcr
= &m
->rec
.r
;
7015 ResourceRecord
*rr
= &newcr
->resrec
;
7016 const CacheRecord
*cr
;
7018 *nseclist
= mDNSfalse
;
7019 for (cr
= crlist
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
7021 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
7022 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
7023 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
7024 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
7025 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
7026 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
7028 if (target
&& cr
->resrec
.rdatahash
== rr
->namehash
&& SameDomainName(target
, rr
->name
))
7030 LogInfo("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr
->name
->c
, CRDisplayString(m
, cr
));
7035 // Either the question requires validation or we are validating a response with DNSSEC in which case
7036 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
7037 // we receive NSECs for our query which does not match the qname and we need to cache in that case
7038 // too. nseclist is set if they have to be cached as part of the negative cache record.
7039 if (q
&& DNSSECQuestion(q
))
7041 mDNSBool same
= SameDomainName(&q
->qname
, rr
->name
);
7042 if (same
&& (q
->qtype
== rr
->rrtype
|| rr
->rrtype
== kDNSType_CNAME
))
7044 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q
->qtype
),
7045 CRDisplayString(m
, newcr
));
7048 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
7049 // "nseclist" is set
7050 if (rr
->rrtype
== kDNSType_RRSIG
)
7052 RDataBody2
*const rdb
= (RDataBody2
*)newcr
->smallrdatastorage
.data
;
7053 rdataRRSig
*rrsig
= &rdb
->rrsig
;
7054 mDNSu16 typeCovered
= swap16(rrsig
->typeCovered
);
7056 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
7057 // would match the qtype and they are cached normally as they are not used to prove the
7058 // non-existence of any name. In that case, it is like any other normal dnssec validation
7059 // and hence nseclist should not be set.
7061 if (same
&& ((typeCovered
== q
->qtype
) || (typeCovered
== kDNSType_CNAME
)))
7063 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m
, newcr
),
7064 DNSTypeName(q
->qtype
));
7067 else if (typeCovered
== kDNSType_NSEC
)
7069 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches NSEC type (nseclist = 1)", CRDisplayString(m
, newcr
));
7070 *nseclist
= mDNStrue
;
7073 else return mDNSfalse
;
7075 if (rr
->rrtype
== kDNSType_NSEC
)
7077 if (!UNICAST_NSEC(rr
))
7079 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m
, newcr
));
7082 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m
, newcr
));
7083 *nseclist
= mDNStrue
;
7090 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
)
7092 CacheRecord
*rp
, *next
;
7094 for (rp
= NSECRecords
; rp
; rp
= next
)
7097 ReleaseCacheRecord(m
, rp
);
7101 mDNSlocal
void mDNSCoreReceiveNoUnicastAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
7102 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
, uDNS_LLQType LLQType
, mDNSu8 rcode
, CacheRecord
*NSECRecords
)
7105 const mDNSu8
*ptr
= response
->data
;
7106 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
7109 DNSQuestion
*qptr
= mDNSNULL
;
7110 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
7111 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
7113 CacheRecord
*rr
, *neg
= mDNSNULL
;
7114 mDNSu32 slot
= HashSlot(&q
.qname
);
7115 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
7116 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7117 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
7119 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
7120 if (RRExpireTime(rr
) - m
->timenow
> 0) break;
7121 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
7122 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= rr
;
7124 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
7125 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
7126 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
7127 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
7128 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
7129 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
7130 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
7131 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
7132 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
7133 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
7135 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
7136 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
7137 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
7138 // case without creating the negative cache entries, we generate a negative response and let the layer above us
7139 // do the appropriate thing. This negative response is also needed for appending new search domains.
7140 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
7144 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q
.qname
.c
, DNSTypeName(q
.qtype
));
7145 m
->CurrentQuestion
= qptr
;
7146 GenerateNegativeResponse(m
);
7147 m
->CurrentQuestion
= mDNSNULL
;
7149 else LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check to see if we need to generate a negative cache entry for %##s (%s)", q
.qname
.c
, DNSTypeName(q
.qtype
));
7155 // We start off assuming a negative caching TTL of 60 seconds
7156 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
7157 mDNSu32 negttl
= 60;
7159 const domainname
*name
= &q
.qname
;
7160 mDNSu32 hash
= q
.qnamehash
;
7162 // Special case for our special Microsoft Active Directory "local SOA" check.
7163 // Some cheap home gateways don't include an SOA record in the authority section when
7164 // they send negative responses, so we don't know how long to cache the negative result.
7165 // Because we don't want to keep hitting the root name servers with our query to find
7166 // if we're on a network using Microsoft Active Directory using "local" as a private
7167 // internal top-level domain, we make sure to cache the negative result for at least one day.
7168 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
7170 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
7171 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
7173 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
7174 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
7176 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
7177 mDNSu32 ttl_s
= soa
->min
;
7178 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
7179 // for the SOA record for ".", where the record is reported as non-cacheable
7180 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
7181 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
7182 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
7183 if (negttl
< ttl_s
) negttl
= ttl_s
;
7185 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
7186 // with an Authority Section SOA record for d.com, then this is a hint that the authority
7187 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
7188 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
7189 if (q
.qtype
== kDNSType_SOA
)
7191 int qcount
= CountLabels(&q
.qname
);
7192 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
7193 if (qcount
- 1 > scount
)
7194 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
7195 repeat
= qcount
- 1 - scount
;
7198 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7201 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
7202 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
7203 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
7204 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
7205 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
7206 // so that we back off our polling rate and don't keep hitting the server continually.
7209 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
7210 negttl
= neg
->resrec
.rroriginalttl
* 2;
7215 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
7217 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
7220 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
7221 RefreshCacheRecord(m
, neg
, negttl
);
7222 // When we created the cache for the first time and answered the question, the question's
7223 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
7224 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
7225 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
7226 // we should reset its question interval here to MaxQuestionInterval.
7227 ResetQuestionState(m
, qptr
);
7228 // Update the NSEC records again.
7229 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
7232 if (!AddNSECSForCacheRecord(m
, NSECRecords
, neg
, rcode
))
7234 LogMsg("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m
, neg
));
7235 FreeNSECRecords(m
, NSECRecords
);
7237 NSECRecords
= mDNSNULL
;
7242 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
7243 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
7244 if (NSECRecords
&& DNSSECQuestion(qptr
))
7247 // Create the cache entry with delay and then add the NSEC records
7248 // to it and add it immediately.
7249 negcr
= CreateNewCacheEntry(m
, slot
, cg
, 1, mDNStrue
, mDNSNULL
);
7250 if (!AddNSECSForCacheRecord(m
, NSECRecords
, negcr
, rcode
))
7252 LogMsg("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s", CRDisplayString(m
, negcr
));
7253 FreeNSECRecords(m
, NSECRecords
);
7255 else LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m
, negcr
));
7256 NSECRecords
= mDNSNULL
;
7257 negcr
->DelayDelivery
= 0;
7258 CacheRecordDeferredAdd(m
, negcr
);
7259 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7264 CreateNewCacheEntry(m
, slot
, cg
, 0, mDNStrue
, mDNSNULL
); // We never need any delivery delay for these generated negative cache records
7266 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7269 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
7270 hash
= DomainNameHashValue(name
);
7271 slot
= HashSlot(name
);
7272 cg
= CacheGroupForName(m
, slot
, hash
, name
);
7278 if (NSECRecords
) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m
, NSECRecords
); }
7281 mDNSlocal mDNSBool
mDNSCoreRegisteredProxyRecord(mDNS
*const m
, AuthRecord
*rr
)
7283 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
7284 AuthRecord
*rrPtr
= mDNSNULL
;
7288 rrPtr
= intf
->SPSRRSet
;
7291 if (SameResourceRecordSignature(rrPtr
, rr
))
7293 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m
, rr
));
7296 rrPtr
= rrPtr
->next
;
7303 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
7304 // the record list and/or question list.
7305 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7306 // InterfaceID non-NULL tells us the interface this multicast response was received on
7307 // InterfaceID NULL tells us this was a unicast response
7308 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
7309 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
7310 const DNSMessage
*const response
, const mDNSu8
*end
,
7311 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
7312 const mDNSInterfaceID InterfaceID
)
7315 mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
7316 mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
7317 DNSQuestion
*llqMatch
= mDNSNULL
;
7318 DNSQuestion
*unicastQuestion
= mDNSNULL
;
7319 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
7321 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
7322 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
7323 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
7324 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
7325 CacheRecord
**cfp
= &CacheFlushRecords
;
7326 CacheRecord
*NSECRecords
= mDNSNULL
;
7327 CacheRecord
*NSECCachePtr
= mDNSNULL
;
7328 CacheRecord
**nsecp
= &NSECRecords
;
7330 mDNSu8 rcode
= '\0';
7332 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
7333 // to guard against spoof responses, then the only credible protection against that is cryptographic
7334 // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
7335 int firstauthority
= response
->h
.numAnswers
;
7336 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
7337 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
7338 const mDNSu8
*ptr
= response
->data
;
7339 DNSServer
*uDNSServer
= mDNSNULL
;
7341 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
7342 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
7343 srcaddr
, dstaddr
, InterfaceID
,
7344 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
7345 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
7346 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
7347 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
7349 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
7350 // When a DNS client receives a reply with TC
7351 // set, it should ignore that response, and query again, using a
7352 // mechanism, such as a TCP connection, that will permit larger replies.
7353 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
7354 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
7355 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
7356 // <rdar://problem/6690034> Can't bind to Active Directory
7357 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
7358 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
7359 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
7360 // and not even do the TCP query.
7361 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
7362 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
)) return;
7364 if (LLQType
== uDNS_LLQ_Ignore
) return;
7366 // 1. We ignore questions (if any) in mDNS response packets
7367 // 2. If this is an LLQ response, we handle it much the same
7368 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
7369 // answer as being the authoritative complete RRSet, and respond by deleting all other
7370 // matching cache records that don't appear in this packet.
7371 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
7372 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
|| (response
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7373 ptr
= LocateAnswers(response
, end
);
7374 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
7375 // in this response packet are immediately deemed to be invalid.
7378 mDNSBool failure
, returnEarly
;
7379 rcode
= (mDNSu8
)(response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
7380 failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
7381 returnEarly
= mDNSfalse
;
7382 // We could possibly combine this with the similar loop at the end of this function --
7383 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
7384 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
7385 // which it was received (or refreshed), and then at the end if we find any cache records which
7386 // answer questions in this packet's question section, but which aren't tagged with this packet's
7387 // packet number, then we deduce they are old and delete them
7388 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
7390 DNSQuestion q
, *qptr
= mDNSNULL
;
7391 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
7392 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
7397 // Remember the unicast question that we found, which we use to make caching
7398 // decisions later on in this function
7399 const mDNSu32 slot
= HashSlot(&q
.qname
);
7400 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
7401 if (!mDNSOpaque16IsZero(response
->h
.id
)) unicastQuestion
= qptr
;
7402 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7403 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
7405 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
7406 rr
->resrec
.InterfaceID
, CRDisplayString(m
, rr
));
7407 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
7408 rr
->TimeRcvd
= m
->timenow
- TicksTTL(rr
) - 1;
7409 rr
->UnansweredQueries
= MaxUnansweredQueries
;
7416 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)", qptr
->qDNSServer
, rcode
, q
.qname
.c
, DNSTypeName(q
.qtype
));
7417 PenalizeDNSServer(m
, qptr
);
7419 returnEarly
= mDNStrue
;
7425 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
7426 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
7427 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
7428 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
7429 // not goto exit because we won't have any CacheFlushRecords and we do not want to
7430 // generate negative cache entries (we want to query the next server)
7435 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
7437 // All responses sent via LL multicast are acceptable for caching
7438 // All responses received over our outbound TCP connections are acceptable for caching
7439 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
;
7440 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
7441 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
7443 const mDNSu8 RecordType
=
7444 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
7445 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
7446 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
7447 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
7448 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
) { m
->rec
.r
.resrec
.RecordType
= 0; continue; }
7450 // Don't want to cache OPT or TSIG pseudo-RRs
7451 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
) { m
->rec
.r
.resrec
.RecordType
= 0; continue; }
7452 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
7454 const rdataOPT
*opt
;
7455 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
7456 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7457 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7458 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
7459 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
7461 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
7462 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
7464 m
->rec
.r
.resrec
.RecordType
= 0;
7468 // if a CNAME record points to itself, then don't add it to the cache
7469 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
7471 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
7472 m
->rec
.r
.resrec
.RecordType
= 0;
7476 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
7477 // In the case of active LLQs, we'll get remove events when the records actually do go away
7478 // In the case of polling LLQs, we assume the record remains valid until the next poll
7479 if (!mDNSOpaque16IsZero(response
->h
.id
))
7480 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
7482 // If response was not sent via LL multicast,
7483 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
7488 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
7489 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
7490 // queries to get ADD/RMV events. To lookup the question, we can't use
7491 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
7492 // has already matched the question using the 64 bit Id in the packet and we use that here.
7494 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
7496 else if (!AcceptableResponse
|| !dstaddr
)
7498 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
7499 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
7500 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
7503 DNSQuestion
*q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
7505 // Intialize the DNS server on the resource record which will now filter what questions we answer with
7508 // We could potentially lookup the DNS server based on the source address, but that may not work always
7509 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
7510 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
7511 // on the "id" and "source port", then this response answers the question and assume the response
7512 // came from the same DNS server that we sent the query to.
7516 AcceptableResponse
= mDNStrue
;
7519 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
7520 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
7525 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
7526 // the question. The code below does that. So, make this record unacceptable for now
7529 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
7530 AcceptableResponse
= mDNSfalse
;
7536 // 1. Check that this packet resource record does not conflict with any of ours
7537 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
7539 if (m
->CurrentRecord
)
7540 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7541 m
->CurrentRecord
= m
->ResourceRecords
;
7542 while (m
->CurrentRecord
)
7544 AuthRecord
*rr
= m
->CurrentRecord
;
7545 m
->CurrentRecord
= rr
->next
;
7546 // We accept all multicast responses, and unicast responses resulting from queries we issued
7547 // For other unicast responses, this code accepts them only for responses with an
7548 // (apparently) local source address that pertain to a record of our own that's in probing state
7549 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
7551 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
7553 // ... check to see if type and rdata are identical
7554 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
7556 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
7557 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
7559 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
7560 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
7564 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
7565 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
7568 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
7569 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
7571 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7572 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
7574 // If this record is marked DependentOn another record for conflict detection purposes,
7575 // then *that* record has to be bumped back to probing state to resolve the conflict
7576 if (rr
->DependentOn
)
7578 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
7579 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
7582 // If we've just whacked this record's ProbeCount, don't need to do it again
7583 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
7584 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
7585 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
7586 LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
7589 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
7590 // If we'd previously verified this record, put it back to probing state and try again
7591 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
7593 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m
, rr
));
7594 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
7595 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
7596 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
7597 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
7598 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
7599 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
7600 rr
->AnnounceCount
= InitialAnnounceCount
;
7601 InitializeLastAPTime(m
, rr
);
7602 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
7604 // If we're probing for this record, we just failed
7605 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
7607 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
7608 if (!mDNSCoreRegisteredProxyRecord(m
, rr
))
7610 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr
->ProbeCount
, ARDisplayString(m
, rr
));
7611 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
7614 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
7615 // same machine giving different answers for the reverse mapping record, or there are two machines on the
7616 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
7617 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
7618 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
7619 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
7621 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
7622 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
7625 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
7628 // Else, matching signature, different type or rdata, but not a considered a conflict.
7629 // If the packet record has the cache-flush bit set, then we check to see if we
7630 // have any record(s) of the same type that we should re-assert to rescue them
7631 // (see note about "multi-homing and bridged networks" at the end of this function).
7632 else if (m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
)
7633 if ((m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
7634 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
7639 nseclist
= mDNSfalse
;
7640 if (!AcceptableResponse
)
7642 AcceptableResponse
= IsResponseAcceptable(m
, CacheFlushRecords
, unicastQuestion
, &nseclist
);
7643 if (AcceptableResponse
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
7646 // 2. See if we want to add this packet resource record to our cache
7647 // We only try to cache answers if we have a cache to put them in
7648 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
7649 if (!AcceptableResponse
) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m
, &m
->rec
.r
));
7650 if (m
->rrcache_size
&& AcceptableResponse
)
7652 const mDNSu32 slot
= HashSlot(m
->rec
.r
.resrec
.name
);
7653 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &m
->rec
.r
.resrec
);
7656 // 2a. Check if this packet resource record is already in our cache
7657 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7660 // Resource record received via unicast, the resGroupID should match ?
7663 mDNSu16 id1
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
7664 mDNSu16 id2
= (m
->rec
.r
.resrec
.rDNSServer
? m
->rec
.r
.resrec
.rDNSServer
->resGroupID
: 0);
7665 match
= (id1
== id2
);
7668 match
= (rr
->resrec
.InterfaceID
== InterfaceID
);
7669 // If we found this exact resource record, refresh its TTL
7670 if (match
&& IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
7672 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
7673 verbosedebugf("Found record size %5d interface %p already in cache: %s",
7674 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
7676 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
7678 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
7679 if (rr
->NextInCFList
== mDNSNULL
&& cfp
!= &rr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
7680 { *cfp
= rr
; cfp
= &rr
->NextInCFList
; *cfp
= (CacheRecord
*)1; }
7682 // If this packet record is marked unique, and our previous cached copy was not, then fix it
7683 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
7686 for (q
= m
->Questions
; q
; q
=q
->next
) if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
)) q
->UniqueAnswers
++;
7687 rr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
7691 if (!SameRDataBody(&m
->rec
.r
.resrec
, &rr
->resrec
.rdata
->u
, SameDomainNameCS
))
7693 // If the rdata of the packet record differs in name capitalization from the record in our cache
7694 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
7695 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
7696 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
7697 rr
->resrec
.rroriginalttl
= 0;
7698 rr
->TimeRcvd
= m
->timenow
;
7699 rr
->UnansweredQueries
= MaxUnansweredQueries
;
7700 SetNextCacheCheckTimeForRecord(m
, rr
);
7701 LogInfo("Discarding due to domainname case change old: %s", CRDisplayString(m
,rr
));
7702 LogInfo("Discarding due to domainname case change new: %s", CRDisplayString(m
,&m
->rec
.r
));
7703 LogInfo("Discarding due to domainname case change in %d slot %3d in %d %d",
7704 NextCacheCheckEvent(rr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
7705 // DO NOT break out here -- we want to continue as if we never found it
7707 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
7710 //if (rr->resrec.rroriginalttl == 0) LogMsg("uDNS rescuing %s", CRDisplayString(m, rr));
7711 RefreshCacheRecord(m
, rr
, m
->rec
.r
.resrec
.rroriginalttl
);
7713 // If we may have NSEC records returned with the answer (which we don't know yet as it
7714 // has not been processed), we need to cache them along with the first cache
7715 // record in the list that answers the question so that it can be used for validation
7717 if (response
->h
.numAnswers
&& unicastQuestion
&& !NSECCachePtr
)
7719 LogInfo("mDNSCoreReceiveResponse: rescuing RR %s", CRDisplayString(m
, rr
));
7722 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
7723 // polling the network once we get a valid response back. For the first time when a new
7724 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
7725 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
7726 // configuration changed, without flushing the cache, we reset the question interval here.
7727 // Currently, we do this for for both multicast and unicast questions as long as the record
7728 // type is unique. For unicast, resource record is always unique and for multicast it is
7729 // true for records like A etc. but not for PTR.
7730 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
7732 for (q
= m
->Questions
; q
; q
=q
->next
)
7734 if (!q
->DuplicateOf
&& !q
->LongLived
&&
7735 ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
7737 ResetQuestionState(m
, q
);
7738 debugf("mDNSCoreReceiveResponse: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
7739 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
7747 // If the packet TTL is zero, that means we're deleting this record.
7748 // To give other hosts on the network a chance to protest, we push the deletion
7749 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
7750 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
7751 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
7752 // If record's current expiry time is more than a second from now, we set it to expire in one second.
7753 // If the record is already going to expire in less than one second anyway, we leave it alone --
7754 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
7755 debugf("DE for %s", CRDisplayString(m
, rr
));
7756 if (RRExpireTime(rr
) - m
->timenow
> mDNSPlatformOneSecond
)
7758 rr
->resrec
.rroriginalttl
= 1;
7759 rr
->TimeRcvd
= m
->timenow
;
7760 rr
->UnansweredQueries
= MaxUnansweredQueries
;
7761 SetNextCacheCheckTimeForRecord(m
, rr
);
7768 // If packet resource record not in our cache, add it now
7769 // (unless it is just a deletion of a record we never had, in which case we don't care)
7770 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
7772 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
7773 const mDNSs32 delay
= AddToCFList
? NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
) :
7774 CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
, slot
);
7775 // If unique, assume we may have to delay delivery of this 'add' event.
7776 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
7777 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
7778 // to schedule an mDNS_Execute task at the appropriate time.
7779 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
, !nseclist
, srcaddr
);
7782 // NSEC Records and its signatures are cached with the negative cache entry
7783 // which we should be creating below. It is also needed in the wildcard
7784 // expanded answer case and in that case it is cached along with the answer.
7785 if (nseclist
) { *nsecp
= rr
; nsecp
= &rr
->next
; }
7786 else if (AddToCFList
) { *cfp
= rr
; cfp
= &rr
->NextInCFList
; *cfp
= (CacheRecord
*)1; }
7787 else if (rr
->DelayDelivery
) ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
7791 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7795 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7797 // If we've just received one or more records with their cache flush bits set,
7798 // then scan that cache slot to see if there are any old stale records we need to flush
7799 while (CacheFlushRecords
!= (CacheRecord
*)1)
7801 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
7802 const mDNSu32 slot
= HashSlot(r1
->resrec
.name
);
7803 const CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &r1
->resrec
);
7804 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
7805 r1
->NextInCFList
= mDNSNULL
;
7807 // Look for records in the cache with the same signature as this new one with the cache flush
7808 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
7809 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
7810 // We make these TTL adjustments *only* for records that still have *more* than one second
7811 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
7812 // (and now has half a second remaining) could inadvertently get its life extended, by either
7813 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
7814 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
7815 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
7816 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
7817 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
7818 // To avoid this, we need to ensure that the cache flushing operation will only act to
7819 // *decrease* a record's remaining lifetime, never *increase* it.
7820 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
7824 if (!r1
->resrec
.InterfaceID
)
7826 id1
= (r1
->resrec
.rDNSServer
? r1
->resrec
.rDNSServer
->resGroupID
: 0);
7827 id2
= (r2
->resrec
.rDNSServer
? r2
->resrec
.rDNSServer
->resGroupID
: 0);
7833 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
7834 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
7835 // the new RRSIG that we received. Process only if the typeCovered matches.
7836 if ((r1
->resrec
.rrtype
== r2
->resrec
.rrtype
) && (r1
->resrec
.rrtype
== kDNSType_RRSIG
))
7838 rdataRRSig
*rrsig1
= (rdataRRSig
*)(((RDataBody2
*)(r1
->resrec
.rdata
->u
.data
))->data
);
7839 rdataRRSig
*rrsig2
= (rdataRRSig
*)(((RDataBody2
*)(r2
->resrec
.rdata
->u
.data
))->data
);
7840 if (swap16(rrsig1
->typeCovered
) != swap16(rrsig2
->typeCovered
))
7842 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
7843 DNSTypeName(swap16(rrsig1
->typeCovered
)), DNSTypeName(swap16(rrsig2
->typeCovered
)));
7848 // For Unicast (null InterfaceID) the resolver IDs should also match
7849 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
7850 (r1
->resrec
.InterfaceID
|| (id1
== id2
)) &&
7851 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
7852 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
)
7854 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
7855 // else, if record is old, mark it to be flushed
7856 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
7858 // If we find mismatched TTLs in an RRSet, correct them.
7859 // We only do this for records with a TTL of 2 or higher. It's possible to have a
7860 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
7861 // which we treat as a goodbye followed by an addition) and in that case it would be
7862 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
7863 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
7864 // because certain early Bonjour devices are known to have this specific mismatch, and
7865 // there's no point filling syslog with messages about something we already know about.
7866 // We also don't log this for uDNS responses, since a caching name server is obliged
7867 // to give us an aged TTL to correct for how long it has held the record,
7868 // so our received TTLs are expected to vary in that case
7869 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
7871 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
7872 mDNSOpaque16IsZero(response
->h
.id
))
7873 LogInfo("Correcting TTL from %4d to %4d for %s",
7874 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
7875 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
7877 r2
->TimeRcvd
= m
->timenow
;
7879 else // else, if record is old, mark it to be flushed
7881 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
7882 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
7883 // We set stale records to expire in one second.
7884 // This gives the owner a chance to rescue it if necessary.
7885 // This is important in the case of multi-homing and bridged networks:
7886 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
7887 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
7888 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
7889 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
7890 // By delaying the deletion by one second, we give X a change to notice that this bridging has
7891 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
7893 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
7894 // final expiration queries for this record.
7896 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
7897 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
7898 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
7899 // <rdar://problem/5636422> Updating TXT records is too slow
7900 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
7901 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
7902 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
7904 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
7905 r2
->resrec
.rroriginalttl
= 0;
7907 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
7909 // We only set a record to expire in one second if it currently has *more* than a second to live
7910 // If it's already due to expire in a second or less, we just leave it alone
7911 r2
->resrec
.rroriginalttl
= 1;
7912 r2
->UnansweredQueries
= MaxUnansweredQueries
;
7913 r2
->TimeRcvd
= m
->timenow
- 1;
7914 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
7915 // that we marked for deletion via an explicit DE record
7918 SetNextCacheCheckTimeForRecord(m
, r2
);
7922 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
7924 // If we had a unicast question for this response with at least one positive answer and we
7925 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
7926 // signatures along with the cache record which will be used for validation later. If
7927 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
7928 // use that instead.
7929 if (response
->h
.numAnswers
&& unicastQuestion
&& NSECRecords
)
7933 LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m
, r1
));
7936 // Note: We need to do this before we call CacheRecordDeferredAdd as this
7937 // might start the verification process which needs these NSEC records
7938 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
7940 LogMsg("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
7941 FreeNSECRecords(m
, NSECRecords
);
7943 NSECRecords
= mDNSNULL
;
7944 NSECCachePtr
= mDNSNULL
;
7946 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
, slot
);
7947 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
7948 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
7949 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
7953 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
7954 // update them now for future validations.
7955 if (NSECRecords
&& NSECCachePtr
)
7957 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m
, NSECCachePtr
));
7958 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
7960 LogMsg("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
7961 FreeNSECRecords(m
, NSECRecords
);
7963 NSECRecords
= mDNSNULL
;
7964 NSECCachePtr
= mDNSNULL
;
7967 // See if we need to generate negative cache entries for unanswered unicast questions
7968 mDNSCoreReceiveNoUnicastAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
, LLQType
, rcode
, NSECRecords
);
7971 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
7972 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
7973 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
7974 // that warrants waking the sleeping host.
7975 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
7977 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
7979 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
7980 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
7981 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
7982 // simple, we use the same mechanism for both lists.
7985 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
7988 m
->CurrentRecord
= thelist
;
7989 while (m
->CurrentRecord
)
7991 AuthRecord
*const rr
= m
->CurrentRecord
;
7992 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
7994 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m
, rr
));
7995 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7997 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7998 m
->CurrentRecord
= rr
->next
;
8002 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
8004 if (!e
->l
[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
8005 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
8006 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
8009 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
8011 if (result
&& result
!= mStatus_MemFree
)
8012 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
8014 if (result
== mStatus_NameConflict
)
8017 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
8018 if (ar
->WakeUp
.HMAC
.l
[0])
8020 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
); // Send one wakeup magic packet
8021 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
); // Schedule all other records with the same owner to be woken
8026 if (result
== mStatus_NameConflict
|| result
== mStatus_MemFree
)
8029 mDNSPlatformMemFree(ar
);
8030 mDNS_UpdateAllowSleep(m
);
8034 mDNSlocal mDNSu8
*GetValueForIPv6Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv6Addr
*v6
)
8039 int digitsProcessed
;
8044 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
8045 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
8047 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
8048 // the result in "v6"
8050 numColons
= numBytes
= value
= digitsProcessed
= zeroFillStart
= 0;
8051 while (ptr
< limit
&& *ptr
!= ' ')
8053 hval
= HexVal(*ptr
);
8058 digitsProcessed
= 1;
8060 else if (*ptr
== ':')
8062 if (!digitsProcessed
)
8064 // If we have already seen a "::", we should not see one more. Handle the special
8068 // if we never filled any bytes and the next character is space (we have reached the end)
8070 if (!numBytes
&& (ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
8072 mDNSPlatformMemZero(v6
->b
, 16);
8075 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart
);
8079 // We processed "::". We need to fill zeroes later. For now, mark the
8080 // point where we will start filling zeroes from.
8081 zeroFillStart
= numBytes
;
8084 else if ((ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
8086 // We have a trailing ":" i.e., no more characters after ":"
8087 LogMsg("GetValueForIPv6Addr: Trailing colon");
8092 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
8093 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
8094 // filled here is 12 and 13.
8095 if (numBytes
> 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes
); return mDNSNULL
; }
8097 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
8098 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
8099 digitsProcessed
= value
= 0;
8101 // Make sure that we did not fill the 13th and 14th byte above
8102 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes
); return mDNSNULL
; }
8108 // We should be processing the last set of bytes following the last ":" here
8109 if (!digitsProcessed
)
8111 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes
);
8115 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes
); return mDNSNULL
; }
8116 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
8117 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
8122 for (i
= 0; i
< zeroFillStart
; i
++)
8123 v6
->b
[i
] = v6addr
[i
];
8124 for (j
= i
, n
= 0; n
< 16 - numBytes
; j
++, n
++)
8126 for (; j
< 16; i
++, j
++)
8127 v6
->b
[j
] = v6addr
[i
];
8129 else if (numBytes
== 16)
8130 mDNSPlatformMemCopy(v6
->b
, v6addr
, 16);
8133 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes
);
8139 mDNSlocal mDNSu8
*GetValueForIPv4Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv4Addr
*v4
)
8146 for (i
= 0; ptr
< limit
&& *ptr
!= ' '; ptr
++)
8148 if (*ptr
>= '0' && *ptr
<= '9')
8149 val
= val
* 10 + *ptr
- '0';
8150 else if (*ptr
== '.')
8152 v4
->b
[dots
++] = val
;
8157 // We have a zero at the end and if we reached that, then we are done.
8158 if (*ptr
== 0 && ptr
== limit
- 1 && dots
== 3)
8163 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
); return mDNSNULL
; }
8166 if (dots
!= 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots
); return mDNSNULL
; }
8171 mDNSlocal mDNSu8
*GetValueForKeepalive(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSu32
*value
)
8177 for (i
= 0; ptr
< limit
&& *ptr
!= ' '; ptr
++)
8179 if (*ptr
< '0' || *ptr
> '9')
8181 // We have a zero at the end and if we reached that, then we are done.
8182 if (*ptr
== 0 && ptr
== limit
- 1)
8187 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr
, ptr
, limit
, *(ptr
+ 1)); return mDNSNULL
; }
8189 val
= val
* 10 + *ptr
- '0';
8195 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSu32
*seq
,
8196 mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
)
8198 if (ar
->resrec
.rrtype
!= kDNSType_NULL
)
8201 if (mDNS_KeepaliveRecord(&ar
->resrec
))
8203 int len
= ar
->resrec
.rdlength
;
8204 mDNSu8
*ptr
= &ar
->resrec
.rdata
->u
.txt
.c
[1];
8205 mDNSu8
*limit
= ptr
+ len
- 1; // Exclude the first byte that is the length
8210 mDNSu8 param
= *ptr
;
8213 ptr
+= 2; // Skip the letter and the "="
8216 laddr
->type
= mDNSAddrType_IPv4
;
8217 ptr
= GetValueForIPv4Addr(ptr
, limit
, &laddr
->ip
.v4
);
8219 else if (param
== 'd')
8221 raddr
->type
= mDNSAddrType_IPv4
;
8222 ptr
= GetValueForIPv4Addr(ptr
, limit
, &raddr
->ip
.v4
);
8226 laddr
->type
= mDNSAddrType_IPv6
;
8227 ptr
= GetValueForIPv6Addr(ptr
, limit
, &laddr
->ip
.v6
);
8229 else if (param
== 'D')
8231 raddr
->type
= mDNSAddrType_IPv6
;
8232 ptr
= GetValueForIPv6Addr(ptr
, limit
, &raddr
->ip
.v6
);
8236 ptr
= GetValueForKeepalive(ptr
, limit
, &value
);
8238 if (!ptr
) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
8240 p
= (mDNSu8
*)&value
;
8241 // Extract everything in network order so that it is easy for sending a keepalive and also
8242 // for matching incoming TCP packets
8247 //if (*timeout < 120) *timeout = 120;
8255 lport
->NotAnInteger
= p
[0] << 8 | p
[1];
8258 rport
->NotAnInteger
= p
[0] << 8 | p
[1];
8261 value
= p
[0] << 24 | p
[1] << 16 | p
[2] << 8 | p
[3];
8265 value
= p
[0] << 24 | p
[1] << 16 | p
[2] << 8 | p
[3];
8269 *win
= p
[0] << 8 | p
[1];
8272 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value\n");
8276 ptr
++; // skip the space
8281 // Matches the proxied auth records to the incoming TCP packet and returns the match and its sequence and ack in "rseq" and "rack" so that
8282 // the clients need not retrieve this information from the auth record again.
8283 mDNSlocal AuthRecord
* mDNS_MatchKeepaliveInfo(mDNS
*const m
, const mDNSAddr
const* pladdr
, const mDNSAddr
const* praddr
, const mDNSIPPort plport
,
8284 const mDNSIPPort prport
, mDNSu32
*rseq
, mDNSu32
*rack
)
8287 mDNSAddr laddr
, raddr
;
8288 mDNSIPPort lport
, rport
;
8289 mDNSu32 timeout
, seq
, ack
;
8292 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
8294 timeout
= seq
= ack
= 0;
8296 laddr
= raddr
= zeroAddr
;
8297 lport
= rport
= zeroIPPort
;
8299 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
8301 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, &seq
, &ack
, &lport
, &rport
, &win
);
8303 // Did we parse correctly ?
8304 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
8306 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
8310 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
8311 &laddr
, pladdr
, &raddr
, praddr
, mDNSVal16(lport
), mDNSVal16(plport
), mDNSVal16(rport
), mDNSVal16(prport
));
8313 // Does it match the incoming TCP packet ?
8314 if (mDNSSameAddress(&laddr
, pladdr
) && mDNSSameAddress(&raddr
, praddr
) && mDNSSameIPPort(lport
, plport
) && mDNSSameIPPort(rport
, prport
))
8316 // returning in network order
8325 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
)
8329 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
8331 mDNSu32 timeout
, seq
, ack
;
8333 mDNSAddr laddr
, raddr
;
8334 mDNSIPPort lport
, rport
;
8336 timeout
= seq
= ack
= 0;
8339 laddr
= raddr
= zeroAddr
;
8340 lport
= rport
= zeroIPPort
;
8342 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
8344 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, &seq
, &ack
, &lport
, &rport
, &win
);
8346 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
8348 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
8351 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
8353 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
8354 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
8355 if (!ar
->KATimeExpire
|| (m
->timenow
- ar
->KATimeExpire
>= 0))
8357 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
8358 ar
->KATimeExpire
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
8360 if (m
->NextScheduledKA
- ar
->KATimeExpire
> 0)
8361 m
->NextScheduledKA
= ar
->KATimeExpire
;
8365 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
8366 const DNSMessage
*const msg
, const mDNSu8
*end
,
8367 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8368 const mDNSInterfaceID InterfaceID
)
8372 mDNSu8
*p
= m
->omsg
.data
;
8373 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
8374 mDNSu32 updatelease
= 0;
8377 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8378 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8379 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8380 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8381 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8382 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8383 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
8385 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
8387 if (mDNS_PacketLoggingEnabled
)
8388 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
8390 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
8393 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
8394 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
8397 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
8398 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
8400 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
8401 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
8404 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8407 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
8409 if (!updatelease
|| !owner
.HMAC
.l
[0])
8411 static int msgs
= 0;
8415 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
8416 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
8418 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
8420 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
8422 static int msgs
= 0;
8426 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
8427 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
8429 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
8433 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
8435 if (updatelease
> 24 * 60 * 60)
8436 updatelease
= 24 * 60 * 60;
8438 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
8439 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
8441 ptr
= LocateAuthorities(msg
, end
);
8442 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
8444 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8445 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
8447 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
8448 AuthRecord
*ar
= mDNSPlatformMemAllocate(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
8449 if (!ar
) { m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
; break; }
8452 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
8453 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
8454 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
8455 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
8456 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, AuthRecordAny
, SPSRecordCallback
, ar
);
8457 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
8458 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
8459 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
8460 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
8461 ar
->ForceMCast
= mDNStrue
;
8463 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
8465 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
8466 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
8467 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
8468 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
8469 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
8471 ar
->TimeRcvd
= m
->timenow
;
8472 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
8473 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
8474 m
->NextScheduledSPS
= ar
->TimeExpire
;
8475 ar
->KATimeExpire
= 0;
8476 mDNS_Register_internal(m
, ar
);
8477 // Unsolicited Neighbor Advertisements (RFC 2461 Section 7.2.6) give us fast address cache updating,
8478 // but some older IPv6 clients get confused by them, so for now we don't send them. Without Unsolicited
8479 // Neighbor Advertisements we have to rely on Neighbor Unreachability Detection instead, which is slower.
8480 // Given this, we'll do our best to wake for existing IPv6 connections, but we don't want to encourage
8481 // new ones for sleeping clients, so we'll we send deletions for our SPS clients' AAAA records.
8482 if (m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
8483 if (ar
->resrec
.rrtype
== kDNSType_AAAA
) ar
->resrec
.rroriginalttl
= 0;
8485 mDNS_UpdateAllowSleep(m
);
8486 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
8489 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8492 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
8494 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
8495 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
8496 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
8500 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
8501 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
8502 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
8503 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
8504 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
8505 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
8506 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
8510 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
8511 mDNS_SendKeepalives(m
);
8514 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSInterfaceID InterfaceID
)
8518 mDNSu32 updatelease
= 60 * 60; // If SPS fails to indicate lease time, assume one hour
8519 const mDNSu8
*ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
);
8522 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
8523 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
8526 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
8527 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
8528 if (o
->opt
== kDNSOpt_Lease
)
8530 updatelease
= o
->u
.updatelease
;
8531 LogSPS("Sleep Proxy granted lease time %4d seconds, updateid %d, InterfaceID %p", updatelease
, mDNSVal16(msg
->h
.id
), InterfaceID
);
8534 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8537 if (m
->CurrentRecord
)
8538 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
8539 m
->CurrentRecord
= m
->ResourceRecords
;
8540 while (m
->CurrentRecord
)
8542 AuthRecord
*const rr
= m
->CurrentRecord
;
8543 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
8544 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
8546 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
8547 // Clear the updateid when we are done sending on all interfaces.
8548 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, InterfaceID
, mDNStrue
);
8549 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
8550 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
8551 if (mDNSOpaque64IsZero(&rr
->updateIntID
))
8552 rr
->updateid
= zeroID
;
8553 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
8554 LogSPS("Sleep Proxy %s record %5d 0x%x 0x%x (%d) %s", rr
->WakeUp
.HMAC
.l
[0] ? "transferred" : "registered", updatelease
, rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
));
8555 if (rr
->WakeUp
.HMAC
.l
[0])
8557 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
8558 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
8559 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
8562 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
8563 // new records could have been added to the end of the list as a result of that call.
8564 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
8565 m
->CurrentRecord
= rr
->next
;
8568 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
8569 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
8570 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
8573 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
8574 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
, DNSServer
*dnsserver
)
8576 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
8578 LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
8584 // Create empty resource record
8585 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
8586 cr
->resrec
.InterfaceID
= InterfaceID
;
8587 cr
->resrec
.rDNSServer
= dnsserver
;
8588 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
8589 cr
->resrec
.rrtype
= rrtype
;
8590 cr
->resrec
.rrclass
= rrclass
;
8591 cr
->resrec
.rroriginalttl
= ttl_seconds
;
8592 cr
->resrec
.rdlength
= 0;
8593 cr
->resrec
.rdestimate
= 0;
8594 cr
->resrec
.namehash
= namehash
;
8595 cr
->resrec
.rdatahash
= 0;
8596 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
8597 cr
->resrec
.rdata
->MaxRDLength
= 0;
8599 cr
->NextInKAList
= mDNSNULL
;
8600 cr
->TimeRcvd
= m
->timenow
;
8601 cr
->DelayDelivery
= 0;
8602 cr
->NextRequiredQuery
= m
->timenow
;
8603 cr
->LastUsed
= m
->timenow
;
8604 cr
->CRActiveQuestion
= mDNSNULL
;
8605 cr
->UnansweredQueries
= 0;
8606 cr
->LastUnansweredTime
= 0;
8607 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
8608 cr
->MPUnansweredQ
= 0;
8609 cr
->MPLastUnansweredQT
= 0;
8610 cr
->MPUnansweredKA
= 0;
8611 cr
->MPExpectingKA
= mDNSfalse
;
8613 cr
->NextInCFList
= mDNSNULL
;
8614 cr
->nsec
= mDNSNULL
;
8617 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, void *const pkt
, const mDNSu8
*const end
,
8618 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
8619 const mDNSInterfaceID InterfaceID
)
8621 mDNSInterfaceID ifid
= InterfaceID
;
8622 DNSMessage
*msg
= (DNSMessage
*)pkt
;
8623 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
8624 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
8625 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
8626 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
8628 mDNSu8
*ptr
= mDNSNULL
;
8629 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
8630 if (TLS
) dstaddr
= mDNSNULL
;
8632 #ifndef UNICAST_DISABLED
8633 if (mDNSSameAddress(srcaddr
, &m
->Router
))
8635 #ifdef _LEGACY_NAT_TRAVERSAL_
8636 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
8639 LNT_ConfigureRouterInfo(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
8644 if (mDNSSameIPPort(srcport
, NATPMPPort
))
8647 uDNS_ReceiveNATPMPPacket(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
8652 #ifdef _LEGACY_NAT_TRAVERSAL_
8653 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
8657 if ((unsigned)(end
- (mDNSu8
*)pkt
) < sizeof(DNSMessageHeader
))
8659 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
);
8662 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
8663 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
8664 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
8665 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
8666 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
8667 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
8668 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
8670 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
8672 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
8673 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
8674 if (srcaddr
&& !mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
8678 #ifndef UNICAST_DISABLED
8679 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
8680 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
8682 ifid
= mDNSInterface_Any
;
8683 if (mDNS_PacketLoggingEnabled
)
8684 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
8685 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
8686 // Note: mDNSCore also needs to get access to received unicast responses
8689 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
8690 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
8691 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
8692 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, InterfaceID
);
8695 LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
8696 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
, InterfaceID
);
8697 if (mDNS_LoggingEnabled
)
8700 while (i
<end
- (mDNSu8
*)pkt
)
8703 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
8704 do if (i
<end
- (mDNSu8
*)pkt
) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", ((mDNSu8
*)pkt
)[i
]);while (++i
& 15);
8705 LogInfo("%s", buffer
);
8709 // Packet reception often causes a change to the task list:
8710 // 1. Inbound queries can cause us to need to send responses
8711 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
8712 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
8713 // 4. Response packets that answer questions may cause our client to issue new questions
8717 // ***************************************************************************
8718 #if COMPILER_LIKES_PRAGMA_MARK
8720 #pragma mark - Searcher Functions
8723 // Targets are considered the same if both queries are untargeted, or
8724 // if both are targeted to the same address+port
8725 // (If Target address is zero, TargetPort is undefined)
8726 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
8727 (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
8729 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
8730 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
8731 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
8732 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
8733 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
8735 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
8736 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
8737 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
8738 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
8739 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
8740 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
8741 // breaks this design principle.
8743 // If IsLLQ(Q) is true, it means the question is both:
8744 // (a) long-lived and
8745 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
8746 // for multicast questions, we don't want to treat LongLived as anything special
8747 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
8749 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
8752 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
8753 // This prevents circular references, where two questions are each marked as a duplicate of the other.
8754 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
8755 // further in the list.
8756 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list for another question
8757 if (q
->InterfaceID
== question
->InterfaceID
&& // with the same InterfaceID,
8758 SameQTarget(q
, question
) && // and same unicast/multicast target settings
8759 q
->qtype
== question
->qtype
&& // type,
8760 q
->qclass
== question
->qclass
&& // class,
8761 IsLLQ(q
) == IsLLQ(question
) && // and long-lived status matches
8762 (!q
->AuthInfo
|| question
->AuthInfo
) && // to avoid deadlock, don't make public query dup of a private one
8763 (q
->SuppressQuery
== question
->SuppressQuery
) && // Questions that are suppressed/not suppressed
8764 (q
->ValidationRequired
== question
->ValidationRequired
) && // Questions that require DNSSEC validation
8765 (q
->ValidatingResponse
== question
->ValidatingResponse
) && // Questions that are validating responses using DNSSEC
8766 q
->qnamehash
== question
->qnamehash
&&
8767 SameDomainName(&q
->qname
, &question
->qname
)) // and name
8772 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
8773 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
8776 DNSQuestion
*first
= mDNSNULL
;
8778 // This is referring to some other question as duplicate. No other question can refer to this
8779 // question as a duplicate.
8780 if (question
->DuplicateOf
)
8782 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
8783 question
, question
->qname
.c
, DNSTypeName(question
->qtype
),
8784 question
->DuplicateOf
, question
->DuplicateOf
->qname
.c
, DNSTypeName(question
->DuplicateOf
->qtype
));
8788 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
8789 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
8791 q
->DuplicateOf
= first
;
8795 // If q used to be a duplicate, but now is not,
8796 // then inherit the state from the question that's going away
8797 q
->LastQTime
= question
->LastQTime
;
8798 q
->ThisQInterval
= question
->ThisQInterval
;
8799 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
8800 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
8801 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
8802 q
->RequestUnicast
= question
->RequestUnicast
;
8803 q
->LastQTxTime
= question
->LastQTxTime
;
8804 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
8805 q
->nta
= question
->nta
;
8806 q
->servAddr
= question
->servAddr
;
8807 q
->servPort
= question
->servPort
;
8808 q
->qDNSServer
= question
->qDNSServer
;
8809 q
->validDNSServers
= question
->validDNSServers
;
8810 q
->unansweredQueries
= question
->unansweredQueries
;
8811 q
->noServerResponse
= question
->noServerResponse
;
8812 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
8814 q
->TargetQID
= question
->TargetQID
;
8815 q
->LocalSocket
= question
->LocalSocket
;
8817 q
->state
= question
->state
;
8818 // q->tcp = question->tcp;
8819 q
->ReqLease
= question
->ReqLease
;
8820 q
->expire
= question
->expire
;
8821 q
->ntries
= question
->ntries
;
8822 q
->id
= question
->id
;
8823 q
->ValidationState
= question
->ValidationState
;
8824 q
->ValidationStatus
= question
->ValidationStatus
;
8826 question
->LocalSocket
= mDNSNULL
;
8827 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
8828 // question->tcp = mDNSNULL;
8831 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
8835 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
8836 q
->nta
->ZoneDataContext
= q
;
8839 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
8840 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
8842 if (question
->state
== LLQ_Established
)
8844 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
8845 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
8848 SetNextQueryTime(m
,q
);
8853 mDNSexport McastResolver
*mDNS_AddMcastResolver(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, mDNSu32 timeout
)
8855 McastResolver
**p
= &m
->McastResolvers
;
8856 McastResolver
*tmp
= mDNSNULL
;
8858 if (!d
) d
= (const domainname
*)"";
8860 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d
->c
, interface
, timeout
);
8862 if (m
->mDNS_busy
!= m
->mDNS_reentrancy
+1)
8863 LogMsg("mDNS_AddMcastResolver: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", m
->mDNS_busy
, m
->mDNS_reentrancy
);
8865 while (*p
) // Check if we already have this {interface, domain} tuple registered
8867 if ((*p
)->interface
== interface
&& SameDomainName(&(*p
)->domain
, d
))
8869 if (!((*p
)->flags
& DNSServer_FlagDelete
)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d
->c
, interface
);
8870 (*p
)->flags
&= ~DNSServer_FlagDelete
;
8873 tmp
->next
= mDNSNULL
;
8879 if (tmp
) *p
= tmp
; // move to end of list, to ensure ordering from platform layer
8882 // allocate, add to list
8883 *p
= mDNSPlatformMemAllocate(sizeof(**p
));
8884 if (!*p
) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
8887 (*p
)->interface
= interface
;
8888 (*p
)->flags
= DNSServer_FlagNew
;
8889 (*p
)->timeout
= timeout
;
8890 AssignDomainName(&(*p
)->domain
, d
);
8891 (*p
)->next
= mDNSNULL
;
8897 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
8900 if (server
->penaltyTime
!= 0)
8902 ptime
= server
->penaltyTime
- m
->timenow
;
8905 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
8906 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
8908 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
8909 ptime
, server
->penaltyTime
, m
->timenow
);
8910 server
->penaltyTime
= 0;
8917 //Checks to see whether the newname is a better match for the name, given the best one we have
8918 //seen so far (given in bestcount).
8919 //Returns -1 if the newname is not a better match
8920 //Returns 0 if the newname is the same as the old match
8921 //Returns 1 if the newname is a better match
8922 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
8925 // If the name contains fewer labels than the new server's domain or the new name
8926 // contains fewer labels than the current best, then it can't possibly be a better match
8927 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
8929 // If there is no match, return -1 and the caller will skip this newname for
8932 // If we find a match and the number of labels is the same as bestcount, then
8933 // we return 0 so that the caller can do additional logic to pick one of
8934 // the best based on some other factors e.g., penaltyTime
8936 // If we find a match and the number of labels is more than bestcount, then we
8937 // return 1 so that the caller can pick this over the old one.
8939 // Note: newcount can either be equal or greater than bestcount beause of the
8942 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
8943 return bestcount
== newcount
? 0 : 1;
8948 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
8949 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
8950 // names. In that case, we give a default timeout of 5 seconds
8951 #define DEFAULT_MCAST_TIMEOUT 5
8952 mDNSlocal mDNSu32
GetTimeoutForMcastQuestion(mDNS
*m
, DNSQuestion
*question
)
8954 McastResolver
*curmatch
= mDNSNULL
;
8955 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
8956 McastResolver
*curr
;
8957 int bettermatch
, currcount
;
8958 for (curr
= m
->McastResolvers
; curr
; curr
= curr
->next
)
8960 currcount
= CountLabels(&curr
->domain
);
8961 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
8962 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
8963 // the timeout value from the first one
8964 if (bettermatch
== 1)
8967 bestmatchlen
= currcount
;
8970 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question
->qname
.c
, curmatch
,
8971 curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
8972 return ( curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
8975 // Returns true if it is a Domain Enumeration Query
8976 mDNSexport mDNSBool
DomainEnumQuery(const domainname
*qname
)
8978 const mDNSu8
*mDNS_DEQLabels
[] = { (const mDNSu8
*)"\001b", (const mDNSu8
*)"\002db", (const mDNSu8
*)"\002lb",
8979 (const mDNSu8
*)"\001r", (const mDNSu8
*)"\002dr", (const mDNSu8
*)mDNSNULL
, };
8980 const domainname
*d
= qname
;
8981 const mDNSu8
*label
;
8984 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
8985 if (CountLabels(qname
) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname
->c
); return mDNSfalse
; }
8987 label
= (const mDNSu8
*)d
;
8988 while (mDNS_DEQLabels
[i
] != (const mDNSu8
*)mDNSNULL
)
8990 if (SameDomainLabel(mDNS_DEQLabels
[i
], label
)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
); break;}
8993 if (mDNS_DEQLabels
[i
] == (const mDNSu8
*)mDNSNULL
)
8995 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname
->c
);
8998 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
);
9000 // CountLabels already verified the number of labels
9001 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Second Label
9002 label
= (const mDNSu8
*)d
;
9003 if (!SameDomainLabel(label
, (const mDNSu8
*)"\007_dns-sd"))
9005 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname
->c
);
9008 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname
->c
);
9010 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Third Label
9011 label
= (const mDNSu8
*)d
;
9012 if (!SameDomainLabel(label
, (const mDNSu8
*)"\004_udp"))
9014 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname
->c
);
9017 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname
->c
);
9019 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname
->c
);
9024 // Sets all the Valid DNS servers for a question
9025 mDNSexport mDNSu32
SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
9027 DNSServer
*curmatch
= mDNSNULL
;
9028 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
9030 int bettermatch
, currcount
;
9032 mDNSu32 timeout
= 0;
9035 question
->validDNSServers
= zeroOpaque64
;
9036 DEQuery
= DomainEnumQuery(&question
->qname
);
9037 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
9039 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scoped
);
9040 // skip servers that will soon be deleted
9041 if (curr
->flags
& DNSServer_FlagDelete
)
9042 { debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
); continue; }
9044 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
9045 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
9046 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
9047 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
9048 // match the scoped entries by mistake.
9050 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
9052 if (curr
->scoped
&& curr
->interface
== mDNSInterface_Any
)
9053 { debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr
->addr
, curr
->domain
.c
); continue; }
9055 currcount
= CountLabels(&curr
->domain
);
9056 if ((!DEQuery
|| !curr
->cellIntf
) &&
9057 ((!curr
->scoped
&& (!question
->InterfaceID
|| (question
->InterfaceID
== mDNSInterface_Unicast
))) ||
9058 (curr
->interface
== question
->InterfaceID
)))
9060 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
9062 // If we found a better match (bettermatch == 1) then clear all the bits
9063 // corresponding to the old DNSServers that we have may set before and start fresh.
9064 // If we find an equal match, then include that DNSServer also by setting the corresponding
9066 if ((bettermatch
== 1) || (bettermatch
== 0))
9069 bestmatchlen
= currcount
;
9070 if (bettermatch
) { debugf("SetValidDNSServers: Resetting all the bits"); question
->validDNSServers
= zeroOpaque64
; timeout
= 0; }
9071 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
9072 " Timeout %d, interface %p", question
->qname
.c
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
, index
, curr
->timeout
,
9074 timeout
+= curr
->timeout
;
9075 if (DEQuery
) debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question
->qname
.c
, &curr
->addr
, curr
->cellIntf
);
9076 bit_set_opaque64(question
->validDNSServers
, index
);
9081 question
->noServerResponse
= 0;
9083 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
9084 question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
9085 // If there are no matching resolvers, then use the default value to timeout
9086 return (question
->ValidatingResponse
? DEFAULT_UDNSSEC_TIMEOUT
: timeout
? timeout
: DEFAULT_UDNS_TIMEOUT
);
9089 // Get the Best server that matches a name. If you find penalized servers, look for the one
9090 // that will come out of the penalty box soon
9091 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSOpaque64 validBits
, int *selected
, mDNSBool nameMatch
)
9093 DNSServer
*curmatch
= mDNSNULL
;
9094 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
9096 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
9097 int bettermatch
, currcount
;
9101 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
9102 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
9103 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
9105 // skip servers that will soon be deleted
9106 if (curr
->flags
& DNSServer_FlagDelete
)
9107 { debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
); continue; }
9109 // Check if this is a valid DNSServer
9110 if (!bit_get_opaque64(validBits
, index
)) { debugf("GetBestServer: continuing for index %d", index
); index
++; continue; }
9112 currcount
= CountLabels(&curr
->domain
);
9113 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
9115 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
9116 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
9118 // If there are multiple best servers for a given question, we will pick the first one
9119 // if none of them are penalized. If some of them are penalized in that list, we pick
9120 // the least penalized one. BetterMatchForName walks through all best matches and
9121 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
9122 // in the list when there are no penalized servers and least one among them
9123 // when there are some penalized servers
9125 // Notes on InterfaceID matching:
9127 // 1) A DNSServer entry may have an InterfaceID but the scoped flag may not be set. This
9128 // is the old way of specifying an InterfaceID option for DNSServer. We recoginize these
9129 // entries by "scoped" being false. These are like any other unscoped entries except that
9130 // if it is picked e.g., domain match, when the packet is sent out later, the packet will
9131 // be sent out on that interface. Theese entries can be matched by either specifying a
9132 // zero InterfaceID or non-zero InterfaceID on the question. Specifying an InterfaceID on
9133 // the question will cause an extra check on matching the InterfaceID on the question
9134 // against the DNSServer.
9136 // 2) A DNSServer may also have both scoped set and InterfaceID non-NULL. This
9137 // is the new way of specifying an InterfaceID option for DNSServer. These will be considered
9138 // only when the question has non-zero interfaceID.
9140 if ((!curr
->scoped
&& !InterfaceID
) || (curr
->interface
== InterfaceID
))
9143 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
9144 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
9145 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
9146 // part and still do some redundant steps e.g., InterfaceID match
9148 if (nameMatch
) bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
9149 else bettermatch
= 0;
9151 // If we found a better match (bettermatch == 1) then we don't need to
9152 // compare penalty times. But if we found an equal match, then we compare
9153 // the penalty times to pick a better match
9155 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
9156 { currindex
= index
; curmatch
= curr
; bestmatchlen
= currcount
; bestPenaltyTime
= currPenaltyTime
; }
9160 if (selected
) *selected
= currindex
;
9164 // Look up a DNS Server, matching by name and InterfaceID
9165 mDNSexport DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
)
9167 DNSServer
*curmatch
= mDNSNULL
;
9168 char *ifname
= mDNSNULL
; // for logging purposes only
9169 mDNSOpaque64 allValid
;
9171 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
9172 InterfaceID
= mDNSNULL
;
9174 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
9176 // By passing in all ones, we make sure that every DNS server is considered
9177 allValid
.l
[0] = allValid
.l
[1] = 0xFFFFFFFF;
9179 curmatch
= GetBestServer(m
, name
, InterfaceID
, allValid
, mDNSNULL
, mDNStrue
);
9181 if (curmatch
!= mDNSNULL
)
9182 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch
->addr
,
9183 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
9186 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname
? ifname
: "None", InterfaceID
, name
);
9191 // Look up a DNS Server for a question within its valid DNSServer bits
9192 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
9194 DNSServer
*curmatch
= mDNSNULL
;
9195 char *ifname
= mDNSNULL
; // for logging purposes only
9196 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
9197 const domainname
*name
= &question
->qname
;
9200 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
9201 InterfaceID
= mDNSNULL
;
9203 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
9205 if (!mDNSOpaque64IsZero(&question
->validDNSServers
))
9207 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
9208 if (currindex
!= -1) bit_clr_opaque64(question
->validDNSServers
, currindex
);
9211 if (curmatch
!= mDNSNULL
)
9212 LogInfo("GetServerForQuestion: %p DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s (%s)", question
, &curmatch
->addr
,
9213 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
9214 InterfaceID
, name
, DNSTypeName(question
->qtype
));
9216 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p) found for name %##s (%s)", question
, ifname
? ifname
: "None", InterfaceID
, name
, DNSTypeName(question
->qtype
));
9222 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
9223 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
9225 // Called in normal client context (lock not held)
9226 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
9231 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
9232 for (q
= m
->Questions
; q
; q
=q
->next
)
9233 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
9234 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
9235 #if APPLE_OSX_mDNSResponder
9236 UpdateAutoTunnelDomainStatuses(m
);
9241 mDNSlocal mDNSBool
IsAutoTunnelAddress(mDNS
*const m
, const mDNSv6Addr a
)
9243 DomainAuthInfo
*ai
= mDNSNULL
;
9245 if (mDNSSameIPv6Address(a
, m
->AutoTunnelRelayAddr
))
9248 for (ai
= m
->AuthInfoList
; ai
; ai
= ai
->next
)
9250 if (!ai
->deltime
&& ai
->AutoTunnel
&& mDNSSameIPv6Address(a
, ai
->AutoTunnelInnerAddress
))
9259 mDNSlocal mDNSBool
ShouldSuppressQuery(mDNS
*const m
, domainname
*qname
, mDNSu16 qtype
, mDNSInterfaceID InterfaceID
)
9261 NetworkInterfaceInfo
*i
;
9263 DomainAuthInfo
*AuthInfo
;
9265 if (qtype
== kDNSType_A
) iptype
= mDNSAddrType_IPv4
;
9266 else if (qtype
== kDNSType_AAAA
) iptype
= mDNSAddrType_IPv6
;
9267 else { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
9269 // We still want the ability to be able to listen to the local services and hence
9270 // don't fail .local requests. We always have a loopback interface which we don't
9272 if (InterfaceID
!= mDNSInterface_Unicast
&& IsLocalDomain(qname
)) { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
9274 // Skip Private domains as we have special addresses to get the hosts in the Private domain
9275 AuthInfo
= GetAuthInfoForName_internal(m
, qname
);
9276 if (AuthInfo
&& !AuthInfo
->deltime
&& AuthInfo
->AutoTunnel
)
9277 { LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Private Domain", qname
, DNSTypeName(qtype
)); return mDNSfalse
; }
9279 // Match on Type, Address and InterfaceID
9281 // Check whether we are looking for a name that ends in .local, then presence of a link-local
9282 // address on the interface is sufficient.
9283 for (i
= m
->HostInterfaces
; i
; i
= i
->next
)
9285 if (i
->ip
.type
!= iptype
) continue;
9287 if (!InterfaceID
|| (InterfaceID
== mDNSInterface_LocalOnly
) || (InterfaceID
== mDNSInterface_P2P
) ||
9288 (InterfaceID
== mDNSInterface_Unicast
) || (i
->InterfaceID
== InterfaceID
))
9290 if (iptype
== mDNSAddrType_IPv4
&& !mDNSv4AddressIsLoopback(&i
->ip
.ip
.v4
) && !mDNSv4AddressIsLinkLocal(&i
->ip
.ip
.v4
))
9292 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.4a found", qname
, DNSTypeName(qtype
),
9294 if (m
->SleepState
== SleepState_Sleeping
)
9295 LogInfo("ShouldSuppressQuery: Would have returned true earlier");
9298 else if (iptype
== mDNSAddrType_IPv6
&&
9299 !mDNSv6AddressIsLoopback(&i
->ip
.ip
.v6
) &&
9300 !mDNSv6AddressIsLinkLocal(&i
->ip
.ip
.v6
) &&
9301 !IsAutoTunnelAddress(m
, i
->ip
.ip
.v6
))
9303 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local Address %.16a found", qname
, DNSTypeName(qtype
),
9305 if (m
->SleepState
== SleepState_Sleeping
)
9306 LogInfo("ShouldSuppressQuery: Would have returned true earlier");
9311 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, because no matching interface found", qname
, DNSTypeName(qtype
));
9315 mDNSlocal
void CacheRecordRmvEventsForCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
9321 slot
= HashSlot(&q
->qname
);
9322 cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
9323 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
9325 // Don't deliver RMV events for negative records
9326 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
9328 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
9329 CRDisplayString(m
, rr
), q
, q
->qname
.c
, DNSTypeName(q
->qtype
), rr
->CRActiveQuestion
, q
->CurrentAnswers
);
9333 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
9335 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
9336 q
->qname
.c
, CRDisplayString(m
, rr
), q
->LOAddressAnswers
);
9338 q
->CurrentAnswers
--;
9339 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
9340 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
9342 if (rr
->CRActiveQuestion
== q
)
9345 // If this was the active question for this cache entry, it was the one that was
9346 // responsible for keeping the cache entry fresh when the cache entry was reaching
9347 // its expiry. We need to handover the responsibility to someone else. Otherwise,
9348 // when the cache entry is about to expire, we won't find an active question
9349 // (pointed by CRActiveQuestion) to refresh the cache.
9350 for (qptr
= m
->Questions
; qptr
; qptr
=qptr
->next
)
9351 if (qptr
!= q
&& ActiveQuestion(qptr
) && ResourceRecordAnswersQuestion(&rr
->resrec
, qptr
))
9355 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
9356 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
9357 qptr
, CRDisplayString(m
,rr
), q
->CurrentAnswers
, qptr
->CurrentAnswers
, qptr
->SuppressUnusable
, qptr
->SuppressQuery
);
9359 rr
->CRActiveQuestion
= qptr
; // Question used to be active; new value may or may not be null
9360 if (!qptr
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
9362 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
9363 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
9368 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
9371 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
9372 if (q
== question
) return mDNStrue
;
9376 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
9382 if (m
->CurrentQuestion
)
9383 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
9384 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
9386 if (IsQuestionNew(m
, q
))
9388 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
9391 m
->CurrentQuestion
= q
;
9392 slot
= AuthHashSlot(&q
->qname
);
9393 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
9396 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
9397 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
9398 if (LORecordAnswersAddressType(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
9400 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
9401 ARDisplayString(m
, rr
));
9402 if (q
->CurrentAnswers
<= 0 || q
->LOAddressAnswers
<= 0)
9404 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
9405 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
9406 q
->CurrentAnswers
, q
->LOAddressAnswers
);
9409 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_rmv
); // MUST NOT dereference q again
9410 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
9413 m
->CurrentQuestion
= mDNSNULL
;
9417 // Returns false if the question got deleted while delivering the RMV events
9418 // The caller should handle the case
9419 mDNSlocal mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
9421 if (m
->CurrentQuestion
)
9422 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
9423 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
9425 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
9426 // If this question was answered using local auth records, then you can't deliver RMVs using cache
9427 if (!IsQuestionNew(m
, q
) && !q
->LOAddressAnswers
)
9429 m
->CurrentQuestion
= q
;
9430 CacheRecordRmvEventsForCurrentQuestion(m
, q
);
9431 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
9432 m
->CurrentQuestion
= mDNSNULL
;
9434 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
9438 // The caller should hold the lock
9439 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
9442 DNSQuestion
*restart
= mDNSNULL
;
9444 // We look through all questions including new questions. During network change events,
9445 // we potentially restart questions here in this function that ends up as new questions,
9446 // which may be suppressed at this instance. Before it is handled we get another network
9447 // event that changes the status e.g., address becomes available. If we did not process
9448 // new questions, we would never change its SuppressQuery status.
9450 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
9451 // application callback can potentially stop the current question (detected by CurrentQuestion) or
9452 // *any* other question which could be the next one that we may process here. RestartQuestion
9453 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
9454 // if the "next" question is stopped while the CurrentQuestion is stopped
9455 if (m
->RestartQuestion
)
9456 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
9457 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
9458 m
->RestartQuestion
= m
->Questions
;
9459 while (m
->RestartQuestion
)
9461 q
= m
->RestartQuestion
;
9462 m
->RestartQuestion
= q
->next
;
9463 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->SuppressUnusable
)
9465 mDNSBool old
= q
->SuppressQuery
;
9466 q
->SuppressQuery
= ShouldSuppressQuery(m
, &q
->qname
, q
->qtype
, q
->InterfaceID
);
9467 if (q
->SuppressQuery
!= old
)
9469 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
9470 // LOddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
9471 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
9473 if (q
->SuppressQuery
)
9475 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
9476 // followed by a negative cache response. Temporarily turn off suppression so that
9477 // AnswerCurrentQuestionWithResourceRecord can answer the question
9478 q
->SuppressQuery
= mDNSfalse
;
9479 if (!CacheRecordRmvEventsForQuestion(m
, q
)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
9480 q
->SuppressQuery
= mDNStrue
;
9483 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
9484 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
9485 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
9486 // the restart will not be a duplicate ADD
9487 if (!LocalRecordRmvEventsForQuestion(m
, q
)) { LogInfo("CheckSuppressUnusableQuestions: Question deleted while delivering RMV events"); continue; }
9489 // There are two cases here.
9491 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
9492 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
9493 // because when we get the response, if we had entries in the cache already, it will not answer
9494 // this question if the cache entry did not change. Hence, we need to restart
9495 // the query so that it can be answered from the cache.
9497 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
9498 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
9499 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
9500 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
9501 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
9502 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
9503 // the question is not suppressed, we don't want two active questions sending packets on the wire.
9504 // This affects both efficiency and also the current design where there is only one active question
9505 // pointed to from a cache entry.
9507 // We restart queries in a two step process by first calling stop and build a temporary list which we
9508 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
9509 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
9510 // will soon become the real question) including q->ThisQInterval which might be zero if it was
9511 // suppressed before. At the end when we have restarted all questions, none of them is active as each
9512 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
9514 // It is much cleaner and less error prone to build a list of questions and restart at the end.
9516 LogInfo("CheckSuppressUnusableQuestions: Stop question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9517 mDNS_StopQuery_internal(m
, q
);
9526 restart
= restart
->next
;
9528 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9529 mDNS_StartQuery_internal(m
, q
);
9533 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
9535 if (question
->Target
.type
&& !ValidQuestionTarget(question
))
9537 LogMsg("mDNS_StartQuery_internal: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
9538 question
->Target
.type
, mDNSVal16(question
->TargetPort
), question
->qname
.c
);
9539 question
->Target
.type
= mDNSAddrType_None
;
9542 if (!question
->Target
.type
) question
->TargetPort
= zeroIPPort
; // If no question->Target specified clear TargetPort
9544 question
->TargetQID
=
9545 #ifndef UNICAST_DISABLED
9546 (question
->Target
.type
|| Question_uDNS(question
)) ? mDNS_NewMessageID(m
) :
9547 #endif // UNICAST_DISABLED
9550 debugf("mDNS_StartQuery: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
9552 if (m
->rrcache_size
== 0) // Can't do queries if we have no cache space allocated
9553 return(mStatus_NoCache
);
9559 if (!ValidateDomainName(&question
->qname
))
9561 LogMsg("Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
9562 return(mStatus_Invalid
);
9565 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
9567 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
) q
= &m
->LocalOnlyQuestions
;
9568 while (*q
&& *q
!= question
) q
=&(*q
)->next
;
9572 LogMsg("Error! Tried to add a question %##s (%s) %p that's already in the active list",
9573 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
9574 return(mStatus_AlreadyRegistered
);
9579 // If this question is referencing a specific interface, verify it exists
9580 if (question
->InterfaceID
&& question
->InterfaceID
!= mDNSInterface_LocalOnly
&& question
->InterfaceID
!= mDNSInterface_Unicast
&& question
->InterfaceID
!= mDNSInterface_P2P
)
9582 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
9584 LogMsg("Note: InterfaceID %p for question %##s (%s) not currently found in active interface list",
9585 question
->InterfaceID
, question
->qname
.c
, DNSTypeName(question
->qtype
));
9588 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
9589 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
9590 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
9591 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
9592 // that to go out immediately.
9593 question
->next
= mDNSNULL
;
9594 question
->qnamehash
= DomainNameHashValue(&question
->qname
); // MUST do this before FindDuplicateQuestion()
9595 question
->DelayAnswering
= CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
, HashSlot(&question
->qname
));
9596 question
->LastQTime
= m
->timenow
;
9597 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
9598 question
->ExpectUnicastResp
= 0;
9599 question
->LastAnswerPktNum
= m
->PktNum
;
9600 question
->RecentAnswerPkts
= 0;
9601 question
->CurrentAnswers
= 0;
9602 question
->LargeAnswers
= 0;
9603 question
->UniqueAnswers
= 0;
9604 question
->LOAddressAnswers
= 0;
9605 question
->FlappingInterface1
= mDNSNULL
;
9606 question
->FlappingInterface2
= mDNSNULL
;
9607 // Must do AuthInfo and SuppressQuery before calling FindDuplicateQuestion()
9608 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
9609 if (question
->SuppressUnusable
)
9610 question
->SuppressQuery
= ShouldSuppressQuery(m
, &question
->qname
, question
->qtype
, question
->InterfaceID
);
9612 question
->SuppressQuery
= 0;
9613 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
9614 question
->NextInDQList
= mDNSNULL
;
9615 question
->SendQNow
= mDNSNULL
;
9616 question
->SendOnAll
= mDNSfalse
;
9617 question
->RequestUnicast
= 0;
9618 question
->LastQTxTime
= m
->timenow
;
9619 question
->CNAMEReferrals
= 0;
9621 // We'll create our question->LocalSocket on demand, if needed.
9622 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
9623 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
9624 // NAT mapping for receiving inbound add/remove events.
9625 question
->LocalSocket
= mDNSNULL
;
9626 question
->qDNSServer
= mDNSNULL
;
9627 question
->unansweredQueries
= 0;
9628 question
->nta
= mDNSNULL
;
9629 question
->servAddr
= zeroAddr
;
9630 question
->servPort
= zeroIPPort
;
9631 question
->tcp
= mDNSNULL
;
9632 question
->NoAnswer
= NoAnswer_Normal
;
9634 question
->state
= LLQ_InitialRequest
;
9635 question
->ReqLease
= 0;
9636 question
->expire
= 0;
9637 question
->ntries
= 0;
9638 question
->id
= zeroOpaque64
;
9639 question
->validDNSServers
= zeroOpaque64
;
9640 question
->triedAllServersOnce
= 0;
9641 question
->noServerResponse
= 0;
9642 question
->StopTime
= 0;
9643 if (question
->WakeOnResolve
)
9645 question
->WakeOnResolveCount
= InitialWakeOnResolveCount
;
9646 mDNS_PurgeBeforeResolve(m
, question
);
9649 question
->WakeOnResolveCount
= 0;
9651 question
->ValidationState
= (question
->ValidationRequired
? DNSSECValRequired
: DNSSECValNotRequired
);
9652 question
->ValidationStatus
= 0;
9655 if (question
->DuplicateOf
) question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
9657 for (i
=0; i
<DupSuppressInfoSize
; i
++)
9658 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
9660 debugf("mDNS_StartQuery: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
9661 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
9662 NextQSendTime(question
) - m
->timenow
,
9663 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
9664 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
9666 if (question
->DelayAnswering
)
9667 LogInfo("mDNS_StartQuery_internal: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
9668 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
9670 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
)
9672 if (!m
->NewLocalOnlyQuestions
) m
->NewLocalOnlyQuestions
= question
;
9676 if (!m
->NewQuestions
) m
->NewQuestions
= question
;
9678 // If the question's id is non-zero, then it's Wide Area
9679 // MUST NOT do this Wide Area setup until near the end of
9680 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
9681 // NS, etc.) and if we haven't finished setting up our own question and setting
9682 // m->NewQuestions if necessary then we could end up recursively re-entering
9683 // this routine with the question list data structures in an inconsistent state.
9684 if (!mDNSOpaque16IsZero(question
->TargetQID
))
9686 // Duplicate questions should have the same DNSServers so that when we find
9687 // a matching resource record, all of them get the answers. Calling GetServerForQuestion
9688 // for the duplicate question may get a different DNS server from the original question
9689 mDNSu32 timeout
= SetValidDNSServers(m
, question
);
9690 // We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
9691 // a networking change/search domain change that calls this function again we keep
9692 // reinitializing the timeout value which means it may never timeout. If this becomes
9693 // a common case in the future, we can easily fix this by adding extra state that
9694 // indicates that we have already set the StopTime.
9695 if (question
->TimeoutQuestion
)
9696 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
9697 if (question
->DuplicateOf
)
9699 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
9700 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
9701 LogInfo("mDNS_StartQuery_internal: Duplicate question %p (%p) %##s (%s), Timeout %d, DNS Server %#a:%d",
9702 question
, question
->DuplicateOf
, question
->qname
.c
, DNSTypeName(question
->qtype
), timeout
,
9703 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
9704 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
9708 question
->qDNSServer
= GetServerForQuestion(m
, question
);
9709 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
9710 question
, question
->qname
.c
, DNSTypeName(question
->qtype
), timeout
,
9711 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
9712 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
9714 // If we are talking to a server on the local host, unsupress the query. This happens if we have
9715 // a DNS server running locally while we don't have any interfaces UP.
9717 // TBD: Re-organise the code so that we can move this logic to ShouldSuppressQuery
9718 if (question
->SuppressQuery
&& question
->qDNSServer
&& mDNSAddressIsLoopback(&question
->qDNSServer
->addr
))
9720 LogInfo("mDNS_StartQuery_internal: question %p %##s (%s) unsuppressed due to local DNS Server %#a:%d",
9721 question
, question
->qname
.c
, DNSTypeName(question
->qtype
), &question
->qDNSServer
->addr
,
9722 mDNSVal16(question
->qDNSServer
->port
));
9723 question
->SuppressQuery
= 0;
9725 ActivateUnicastQuery(m
, question
, mDNSfalse
);
9727 // If there is a negative cache entry for this question and if it does
9728 // not have cached nsecs, then we can't validate possibly. Hence, flush
9729 // them so that we can reissue the question again with EDNS0/DO bit set.
9730 if (!question
->DuplicateOf
&& DNSSECQuestion(question
))
9731 mDNS_CheckForCachedNSECS(m
, question
);
9733 // If long-lived query, and we don't have our NAT mapping active, start it now
9734 if (question
->LongLived
&& !m
->LLQNAT
.clientContext
)
9736 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
9737 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
9738 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
9739 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
9740 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal is active
9741 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
9744 #if APPLE_OSX_mDNSResponder
9745 if (question
->LongLived
)
9746 UpdateAutoTunnelDomainStatuses(m
);
9752 if (question
->TimeoutQuestion
)
9753 question
->StopTime
= NonZeroTime(m
->timenow
+ GetTimeoutForMcastQuestion(m
, question
) * mDNSPlatformOneSecond
);
9755 if (question
->StopTime
) SetNextQueryStopTime(m
, question
);
9756 SetNextQueryTime(m
,question
);
9759 return(mStatus_NoError
);
9763 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
9764 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
9766 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
9767 // This function may be called anytime to free the zone information.The question may or may not have stopped.
9768 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
9770 if (nta
->question
.ThisQInterval
!= -1)
9772 mDNS_StopQuery_internal(m
, &nta
->question
);
9773 if (nta
->question
.ThisQInterval
!= -1)
9774 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
9776 mDNSPlatformMemFree(nta
);
9779 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
9781 const mDNSu32 slot
= HashSlot(&question
->qname
);
9782 CacheGroup
*cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
9784 DNSQuestion
**qp
= &m
->Questions
;
9786 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
9788 if (question
->InterfaceID
== mDNSInterface_LocalOnly
|| question
->InterfaceID
== mDNSInterface_P2P
) qp
= &m
->LocalOnlyQuestions
;
9789 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
9790 if (*qp
) *qp
= (*qp
)->next
;
9794 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
9796 LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
9797 question
->qname
.c
, DNSTypeName(question
->qtype
));
9801 return(mStatus_BadReferenceErr
);
9804 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
9805 UpdateQuestionDuplicates(m
, question
);
9806 // But don't trash ThisQInterval until afterwards.
9807 question
->ThisQInterval
= -1;
9809 // If there are any cache records referencing this as their active question, then see if there is any
9810 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
9811 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
9813 if (rr
->CRActiveQuestion
== question
)
9816 // Checking for ActiveQuestion filters questions that are suppressed also
9817 // as suppressed questions are not active
9818 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
9819 if (ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
9822 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
9823 "CurrentAnswers %d, SuppressQuery %d", q
, CRDisplayString(m
,rr
), question
->CurrentAnswers
, q
->CurrentAnswers
, q
->SuppressQuery
);
9824 rr
->CRActiveQuestion
= q
; // Question used to be active; new value may or may not be null
9825 if (!q
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
9829 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
9830 // bump its pointer forward one question.
9831 if (m
->CurrentQuestion
== question
)
9833 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
9834 question
->qname
.c
, DNSTypeName(question
->qtype
));
9835 m
->CurrentQuestion
= question
->next
;
9838 if (m
->NewQuestions
== question
)
9840 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
9841 question
->qname
.c
, DNSTypeName(question
->qtype
));
9842 m
->NewQuestions
= question
->next
;
9845 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
9847 if (m
->RestartQuestion
== question
)
9849 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
9850 question
->qname
.c
, DNSTypeName(question
->qtype
));
9851 m
->RestartQuestion
= question
->next
;
9854 if (m
->ValidationQuestion
== question
)
9856 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
9857 question
->qname
.c
, DNSTypeName(question
->qtype
));
9858 m
->ValidationQuestion
= question
->next
;
9861 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
9862 question
->next
= mDNSNULL
;
9864 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
9866 // And finally, cancel any associated GetZoneData operation that's still running.
9867 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
9868 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
9869 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
9870 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
9871 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
9872 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
9873 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
9875 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
9877 for (q
= m
->Questions
; q
; q
=q
->next
)
9878 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
9881 if (!m
->LLQNAT
.clientContext
) // Should never happen, but just in case...
9882 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientContext NULL");
9885 LogInfo("Stopping LLQNAT");
9886 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
9887 m
->LLQNAT
.clientContext
= mDNSNULL
; // Means LLQ NAT Traversal not running
9891 // If necessary, tell server it can delete this LLQ state
9892 if (question
->state
== LLQ_Established
)
9894 question
->ReqLease
= 0;
9895 sendLLQRefresh(m
, question
);
9896 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
9897 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
9898 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
9899 // we let that run out its natural course and complete asynchronously.
9902 question
->tcp
->question
= mDNSNULL
;
9903 question
->tcp
= mDNSNULL
;
9906 #if APPLE_OSX_mDNSResponder
9907 UpdateAutoTunnelDomainStatuses(m
);
9910 // wait until we send the refresh above which needs the nta
9911 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
9913 return(mStatus_NoError
);
9916 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
9920 status
= mDNS_StartQuery_internal(m
, question
);
9925 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
9929 status
= mDNS_StopQuery_internal(m
, question
);
9934 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
9935 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
9936 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
9937 // specifically to catch and report if the client callback does try to make API calls
9938 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
9944 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
9945 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
9947 status
= mDNS_StopQuery_internal(m
, question
);
9948 if (status
== mStatus_NoError
&& !qq
)
9950 const CacheRecord
*rr
;
9951 const mDNSu32 slot
= HashSlot(&question
->qname
);
9952 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
9953 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
9954 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
9955 if (rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameRecordAnswersQuestion(&rr
->resrec
, question
))
9957 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
9958 if (question
->QuestionCallback
)
9959 question
->QuestionCallback(m
, question
, &rr
->resrec
, mDNSfalse
);
9966 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
9970 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
9971 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
9976 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
9978 mStatus status
= mStatus_BadReferenceErr
;
9981 cr
= FindIdenticalRecordInCache(m
, rr
);
9982 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
9983 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
9984 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
9989 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
9990 const domainname
*const srv
, const domainname
*const domain
,
9991 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
9992 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
9993 mDNSQuestionCallback
*Callback
, void *Context
)
9995 question
->InterfaceID
= InterfaceID
;
9996 question
->flags
= flags
;
9997 question
->Target
= zeroAddr
;
9998 question
->qtype
= kDNSType_PTR
;
9999 question
->qclass
= kDNSClass_IN
;
10000 question
->LongLived
= mDNStrue
;
10001 question
->ExpectUnique
= mDNSfalse
;
10002 question
->ForceMCast
= ForceMCast
;
10003 question
->ReturnIntermed
= mDNSfalse
;
10004 question
->SuppressUnusable
= mDNSfalse
;
10005 question
->SearchListIndex
= 0;
10006 question
->AppendSearchDomains
= 0;
10007 question
->RetryWithSearchDomains
= mDNSfalse
;
10008 question
->TimeoutQuestion
= 0;
10009 question
->WakeOnResolve
= 0;
10010 question
->UseBrackgroundTrafficClass
= useBackgroundTrafficClass
;
10011 question
->ValidationRequired
= 0;
10012 question
->ValidatingResponse
= 0;
10013 question
->qnameOrig
= mDNSNULL
;
10014 question
->QuestionCallback
= Callback
;
10015 question
->QuestionContext
= Context
;
10016 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
)) return(mStatus_BadParamErr
);
10018 return(mDNS_StartQuery_internal(m
, question
));
10021 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
10022 const domainname
*const srv
, const domainname
*const domain
,
10023 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
10024 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
10025 mDNSQuestionCallback
*Callback
, void *Context
)
10029 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, InterfaceID
, flags
, ForceMCast
, useBackgroundTrafficClass
, Callback
, Context
);
10034 mDNSlocal mDNSBool
MachineHasActiveIPv6(mDNS
*const m
)
10036 NetworkInterfaceInfo
*intf
;
10037 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10038 if (intf
->ip
.type
== mDNSAddrType_IPv6
) return(mDNStrue
);
10042 mDNSlocal
void FoundServiceInfoSRV(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
10044 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
10045 mDNSBool PortChanged
= !mDNSSameIPPort(query
->info
->port
, answer
->rdata
->u
.srv
.port
);
10046 if (!AddRecord
) return;
10047 if (answer
->rrtype
!= kDNSType_SRV
) return;
10049 query
->info
->port
= answer
->rdata
->u
.srv
.port
;
10051 // If this is our first answer, then set the GotSRV flag and start the address query
10052 if (!query
->GotSRV
)
10054 query
->GotSRV
= mDNStrue
;
10055 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
10056 AssignDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
);
10057 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
10058 AssignDomainName(&query
->qAv6
.qname
, &answer
->rdata
->u
.srv
.target
);
10059 mDNS_StartQuery(m
, &query
->qAv4
);
10060 // Only do the AAAA query if this machine actually has IPv6 active
10061 if (MachineHasActiveIPv6(m
)) mDNS_StartQuery(m
, &query
->qAv6
);
10063 // If this is not our first answer, only re-issue the address query if the target host name has changed
10064 else if ((query
->qAv4
.InterfaceID
!= query
->qSRV
.InterfaceID
&& query
->qAv4
.InterfaceID
!= answer
->InterfaceID
) ||
10065 !SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
))
10067 mDNS_StopQuery(m
, &query
->qAv4
);
10068 if (query
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery(m
, &query
->qAv6
);
10069 if (SameDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
) && !PortChanged
)
10071 // If we get here, it means:
10072 // 1. This is not our first SRV answer
10073 // 2. The interface ID is different, but the target host and port are the same
10074 // This implies that we're seeing the exact same SRV record on more than one interface, so we should
10075 // make our address queries at least as broad as the original SRV query so that we catch all the answers.
10076 query
->qAv4
.InterfaceID
= query
->qSRV
.InterfaceID
; // Will be mDNSInterface_Any, or a specific interface
10077 query
->qAv6
.InterfaceID
= query
->qSRV
.InterfaceID
;
10081 query
->qAv4
.InterfaceID
= answer
->InterfaceID
;
10082 AssignDomainName(&query
->qAv4
.qname
, &answer
->rdata
->u
.srv
.target
);
10083 query
->qAv6
.InterfaceID
= answer
->InterfaceID
;
10084 AssignDomainName(&query
->qAv6
.qname
, &answer
->rdata
->u
.srv
.target
);
10086 debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query
->qAv4
.qname
.c
, DNSTypeName(query
->qAv4
.qtype
));
10087 mDNS_StartQuery(m
, &query
->qAv4
);
10088 // Only do the AAAA query if this machine actually has IPv6 active
10089 if (MachineHasActiveIPv6(m
)) mDNS_StartQuery(m
, &query
->qAv6
);
10091 else if (query
->ServiceInfoQueryCallback
&& query
->GotADD
&& query
->GotTXT
&& PortChanged
)
10093 if (++query
->Answers
>= 100)
10094 debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
10095 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.srv
.target
.c
,
10096 mDNSVal16(answer
->rdata
->u
.srv
.port
));
10097 query
->ServiceInfoQueryCallback(m
, query
);
10099 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
10100 // callback function is allowed to do anything, including deleting this query and freeing its memory.
10103 mDNSlocal
void FoundServiceInfoTXT(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
10105 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
10106 if (!AddRecord
) return;
10107 if (answer
->rrtype
!= kDNSType_TXT
) return;
10108 if (answer
->rdlength
> sizeof(query
->info
->TXTinfo
)) return;
10110 query
->GotTXT
= mDNStrue
;
10111 query
->info
->TXTlen
= answer
->rdlength
;
10112 query
->info
->TXTinfo
[0] = 0; // In case answer->rdlength is zero
10113 mDNSPlatformMemCopy(query
->info
->TXTinfo
, answer
->rdata
->u
.txt
.c
, answer
->rdlength
);
10115 verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query
->info
->name
.c
, query
->GotADD
);
10117 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
10118 // callback function is allowed to do anything, including deleting this query and freeing its memory.
10119 if (query
->ServiceInfoQueryCallback
&& query
->GotADD
)
10121 if (++query
->Answers
>= 100)
10122 debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
10123 query
->Answers
, query
->qSRV
.qname
.c
, answer
->rdata
->u
.txt
.c
);
10124 query
->ServiceInfoQueryCallback(m
, query
);
10128 mDNSlocal
void FoundServiceInfo(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
10130 ServiceInfoQuery
*query
= (ServiceInfoQuery
*)question
->QuestionContext
;
10131 //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
10132 if (!AddRecord
) return;
10134 if (answer
->rrtype
== kDNSType_A
)
10136 query
->info
->ip
.type
= mDNSAddrType_IPv4
;
10137 query
->info
->ip
.ip
.v4
= answer
->rdata
->u
.ipv4
;
10139 else if (answer
->rrtype
== kDNSType_AAAA
)
10141 query
->info
->ip
.type
= mDNSAddrType_IPv6
;
10142 query
->info
->ip
.ip
.v6
= answer
->rdata
->u
.ipv6
;
10146 debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer
->name
->c
, answer
->rrtype
, DNSTypeName(answer
->rrtype
));
10150 query
->GotADD
= mDNStrue
;
10151 query
->info
->InterfaceID
= answer
->InterfaceID
;
10153 verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query
->info
->ip
.type
, query
->info
->name
.c
, query
->GotTXT
);
10155 // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
10156 // callback function is allowed to do anything, including deleting this query and freeing its memory.
10157 if (query
->ServiceInfoQueryCallback
&& query
->GotTXT
)
10159 if (++query
->Answers
>= 100)
10160 debugf(answer
->rrtype
== kDNSType_A
?
10161 "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
10162 "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
10163 query
->Answers
, query
->qSRV
.qname
.c
, &answer
->rdata
->u
.data
);
10164 query
->ServiceInfoQueryCallback(m
, query
);
10168 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
10169 // If the query is not interface-specific, then InterfaceID may be zero
10170 // Each time the Callback is invoked, the remainder of the fields will have been filled in
10171 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
10172 mDNSexport mStatus
mDNS_StartResolveService(mDNS
*const m
,
10173 ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
)
10178 query
->qSRV
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10179 query
->qSRV
.InterfaceID
= info
->InterfaceID
;
10180 query
->qSRV
.flags
= 0;
10181 query
->qSRV
.Target
= zeroAddr
;
10182 AssignDomainName(&query
->qSRV
.qname
, &info
->name
);
10183 query
->qSRV
.qtype
= kDNSType_SRV
;
10184 query
->qSRV
.qclass
= kDNSClass_IN
;
10185 query
->qSRV
.LongLived
= mDNSfalse
;
10186 query
->qSRV
.ExpectUnique
= mDNStrue
;
10187 query
->qSRV
.ForceMCast
= mDNSfalse
;
10188 query
->qSRV
.ReturnIntermed
= mDNSfalse
;
10189 query
->qSRV
.SuppressUnusable
= mDNSfalse
;
10190 query
->qSRV
.SearchListIndex
= 0;
10191 query
->qSRV
.AppendSearchDomains
= 0;
10192 query
->qSRV
.RetryWithSearchDomains
= mDNSfalse
;
10193 query
->qSRV
.TimeoutQuestion
= 0;
10194 query
->qSRV
.WakeOnResolve
= 0;
10195 query
->qSRV
.UseBrackgroundTrafficClass
= mDNSfalse
;
10196 query
->qSRV
.ValidationRequired
= 0;
10197 query
->qSRV
.ValidatingResponse
= 0;
10198 query
->qSRV
.qnameOrig
= mDNSNULL
;
10199 query
->qSRV
.QuestionCallback
= FoundServiceInfoSRV
;
10200 query
->qSRV
.QuestionContext
= query
;
10202 query
->qTXT
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10203 query
->qTXT
.InterfaceID
= info
->InterfaceID
;
10204 query
->qTXT
.flags
= 0;
10205 query
->qTXT
.Target
= zeroAddr
;
10206 AssignDomainName(&query
->qTXT
.qname
, &info
->name
);
10207 query
->qTXT
.qtype
= kDNSType_TXT
;
10208 query
->qTXT
.qclass
= kDNSClass_IN
;
10209 query
->qTXT
.LongLived
= mDNSfalse
;
10210 query
->qTXT
.ExpectUnique
= mDNStrue
;
10211 query
->qTXT
.ForceMCast
= mDNSfalse
;
10212 query
->qTXT
.ReturnIntermed
= mDNSfalse
;
10213 query
->qTXT
.SuppressUnusable
= mDNSfalse
;
10214 query
->qTXT
.SearchListIndex
= 0;
10215 query
->qTXT
.AppendSearchDomains
= 0;
10216 query
->qTXT
.RetryWithSearchDomains
= mDNSfalse
;
10217 query
->qTXT
.TimeoutQuestion
= 0;
10218 query
->qTXT
.WakeOnResolve
= 0;
10219 query
->qTXT
.UseBrackgroundTrafficClass
= mDNSfalse
;
10220 query
->qTXT
.ValidationRequired
= 0;
10221 query
->qTXT
.ValidatingResponse
= 0;
10222 query
->qTXT
.qnameOrig
= mDNSNULL
;
10223 query
->qTXT
.QuestionCallback
= FoundServiceInfoTXT
;
10224 query
->qTXT
.QuestionContext
= query
;
10226 query
->qAv4
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10227 query
->qAv4
.InterfaceID
= info
->InterfaceID
;
10228 query
->qAv4
.flags
= 0;
10229 query
->qAv4
.Target
= zeroAddr
;
10230 query
->qAv4
.qname
.c
[0] = 0;
10231 query
->qAv4
.qtype
= kDNSType_A
;
10232 query
->qAv4
.qclass
= kDNSClass_IN
;
10233 query
->qAv4
.LongLived
= mDNSfalse
;
10234 query
->qAv4
.ExpectUnique
= mDNStrue
;
10235 query
->qAv4
.ForceMCast
= mDNSfalse
;
10236 query
->qAv4
.ReturnIntermed
= mDNSfalse
;
10237 query
->qAv4
.SuppressUnusable
= mDNSfalse
;
10238 query
->qAv4
.SearchListIndex
= 0;
10239 query
->qAv4
.AppendSearchDomains
= 0;
10240 query
->qAv4
.RetryWithSearchDomains
= mDNSfalse
;
10241 query
->qAv4
.TimeoutQuestion
= 0;
10242 query
->qAv4
.WakeOnResolve
= 0;
10243 query
->qAv4
.UseBrackgroundTrafficClass
= mDNSfalse
;
10244 query
->qAv4
.ValidationRequired
= 0;
10245 query
->qAv4
.ValidatingResponse
= 0;
10246 query
->qAv4
.qnameOrig
= mDNSNULL
;
10247 query
->qAv4
.QuestionCallback
= FoundServiceInfo
;
10248 query
->qAv4
.QuestionContext
= query
;
10250 query
->qAv6
.ThisQInterval
= -1; // So that mDNS_StopResolveService() knows whether to cancel this question
10251 query
->qAv6
.InterfaceID
= info
->InterfaceID
;
10252 query
->qAv6
.flags
= 0;
10253 query
->qAv6
.Target
= zeroAddr
;
10254 query
->qAv6
.qname
.c
[0] = 0;
10255 query
->qAv6
.qtype
= kDNSType_AAAA
;
10256 query
->qAv6
.qclass
= kDNSClass_IN
;
10257 query
->qAv6
.LongLived
= mDNSfalse
;
10258 query
->qAv6
.ExpectUnique
= mDNStrue
;
10259 query
->qAv6
.ForceMCast
= mDNSfalse
;
10260 query
->qAv6
.ReturnIntermed
= mDNSfalse
;
10261 query
->qAv6
.SuppressUnusable
= mDNSfalse
;
10262 query
->qAv6
.SearchListIndex
= 0;
10263 query
->qAv6
.AppendSearchDomains
= 0;
10264 query
->qAv6
.RetryWithSearchDomains
= mDNSfalse
;
10265 query
->qAv6
.TimeoutQuestion
= 0;
10266 query
->qAv6
.UseBrackgroundTrafficClass
= mDNSfalse
;
10267 query
->qAv6
.ValidationRequired
= 0;
10268 query
->qAv6
.ValidatingResponse
= 0;
10269 query
->qAv6
.qnameOrig
= mDNSNULL
;
10270 query
->qAv6
.QuestionCallback
= FoundServiceInfo
;
10271 query
->qAv6
.QuestionContext
= query
;
10273 query
->GotSRV
= mDNSfalse
;
10274 query
->GotTXT
= mDNSfalse
;
10275 query
->GotADD
= mDNSfalse
;
10276 query
->Answers
= 0;
10278 query
->info
= info
;
10279 query
->ServiceInfoQueryCallback
= Callback
;
10280 query
->ServiceInfoQueryContext
= Context
;
10282 // info->name = Must already be set up by client
10283 // info->interface = Must already be set up by client
10284 info
->ip
= zeroAddr
;
10285 info
->port
= zeroIPPort
;
10288 // We use mDNS_StartQuery_internal here because we're already holding the lock
10289 status
= mDNS_StartQuery_internal(m
, &query
->qSRV
);
10290 if (status
== mStatus_NoError
) status
= mDNS_StartQuery_internal(m
, &query
->qTXT
);
10291 if (status
!= mStatus_NoError
) mDNS_StopResolveService(m
, query
);
10297 mDNSexport
void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*q
)
10300 // We use mDNS_StopQuery_internal here because we're already holding the lock
10301 if (q
->qSRV
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qSRV
);
10302 if (q
->qTXT
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qTXT
);
10303 if (q
->qAv4
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qAv4
);
10304 if (q
->qAv6
.ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &q
->qAv6
);
10308 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
10309 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
10311 question
->InterfaceID
= InterfaceID
;
10312 question
->flags
= 0;
10313 question
->Target
= zeroAddr
;
10314 question
->qtype
= kDNSType_PTR
;
10315 question
->qclass
= kDNSClass_IN
;
10316 question
->LongLived
= mDNSfalse
;
10317 question
->ExpectUnique
= mDNSfalse
;
10318 question
->ForceMCast
= mDNSfalse
;
10319 question
->ReturnIntermed
= mDNSfalse
;
10320 question
->SuppressUnusable
= mDNSfalse
;
10321 question
->SearchListIndex
= 0;
10322 question
->AppendSearchDomains
= 0;
10323 question
->RetryWithSearchDomains
= mDNSfalse
;
10324 question
->TimeoutQuestion
= 0;
10325 question
->WakeOnResolve
= 0;
10326 question
->UseBrackgroundTrafficClass
= mDNSfalse
;
10327 question
->ValidationRequired
= 0;
10328 question
->ValidatingResponse
= 0;
10329 question
->qnameOrig
= mDNSNULL
;
10330 question
->QuestionCallback
= Callback
;
10331 question
->QuestionContext
= Context
;
10332 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
10333 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
10334 if (!dom
) dom
= &localdomain
;
10335 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
10336 return(mDNS_StartQuery(m
, question
));
10339 // ***************************************************************************
10340 #if COMPILER_LIKES_PRAGMA_MARK
10342 #pragma mark - Responder Functions
10345 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
10349 status
= mDNS_Register_internal(m
, rr
);
10354 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
10355 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
10357 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
10359 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
10360 return(mStatus_Invalid
);
10365 // If TTL is unspecified, leave TTL unchanged
10366 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
10368 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
10371 RData
*n
= rr
->NewRData
;
10372 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
10373 if (rr
->UpdateCallback
)
10374 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
10377 rr
->NewRData
= newrdata
;
10378 rr
->newrdlength
= newrdlength
;
10379 rr
->UpdateCallback
= Callback
;
10381 #ifndef UNICAST_DISABLED
10382 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
&& !IsLocalDomain(rr
->resrec
.name
))
10384 mStatus status
= uDNS_UpdateRecord(m
, rr
);
10385 // The caller frees the memory on error, don't retain stale pointers
10386 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
10392 if (RRLocalOnly(rr
) || (rr
->resrec
.rroriginalttl
== newttl
&&
10393 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
)))
10394 CompleteRDataUpdate(m
, rr
);
10397 rr
->AnnounceCount
= InitialAnnounceCount
;
10398 InitializeLastAPTime(m
, rr
);
10399 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
10400 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
10401 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
10402 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
10403 if (rr
->UpdateCredits
<= 5)
10405 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
10406 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
10407 rr
->ThisAPInterval
*= 4;
10408 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
10409 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
10410 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
10412 rr
->resrec
.rroriginalttl
= newttl
;
10416 return(mStatus_NoError
);
10419 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
10420 // the record list and/or question list.
10421 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10422 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
10426 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
10431 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
10432 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
10434 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
10436 NetworkInterfaceInfo
*intf
;
10437 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10438 if (intf
->Advertise
) break;
10442 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
10444 char buffer
[MAX_REVERSE_MAPPING_NAME
];
10445 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
10446 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
10448 // Send dynamic update for non-linklocal IPv4 Addresses
10449 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNS_HostNameCallback
, set
);
10450 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10451 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kHostNameTTL
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10453 #if ANSWER_REMOTE_HOSTNAME_QUERIES
10454 set
->RR_A
.AllowRemoteQuery
= mDNStrue
;
10455 set
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
10456 set
->RR_HINFO
.AllowRemoteQuery
= mDNStrue
;
10458 // 1. Set up Address record to map from host name ("foo.local.") to IP address
10459 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
10460 AssignDomainName(&set
->RR_A
.namestorage
, &m
->MulticastHostname
);
10461 if (set
->ip
.type
== mDNSAddrType_IPv4
)
10463 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
10464 set
->RR_A
.resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
10465 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
10466 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
10467 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
10469 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
10472 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
10473 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
10474 for (i
= 0; i
< 16; i
++)
10476 static const char hexValues
[] = "0123456789ABCDEF";
10477 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
10478 buffer
[i
* 4 + 1] = '.';
10479 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
10480 buffer
[i
* 4 + 3] = '.';
10482 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
10485 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.namestorage
, buffer
);
10486 set
->RR_PTR
.AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
10487 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
10489 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
10491 mDNS_Register_internal(m
, &set
->RR_A
);
10492 mDNS_Register_internal(m
, &set
->RR_PTR
);
10494 if (!NO_HINFO
&& m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
10496 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
10497 AssignDomainName(&set
->RR_HINFO
.namestorage
, &m
->MulticastHostname
);
10498 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
10499 mDNSPlatformMemCopy(p
, &m
->HIHardware
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
10500 p
+= 1 + (int)p
[0];
10501 mDNSPlatformMemCopy(p
, &m
->HISoftware
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
10502 mDNS_Register_internal(m
, &set
->RR_HINFO
);
10506 debugf("Not creating HINFO record: platform support layer provided no information");
10507 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
10511 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
10513 NetworkInterfaceInfo
*intf
;
10515 // If we still have address records referring to this one, update them
10516 NetworkInterfaceInfo
*primary
= FindFirstAdvertisedInterface(m
);
10517 AuthRecord
*A
= primary
? &primary
->RR_A
: mDNSNULL
;
10518 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10519 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
10520 intf
->RR_A
.RRSet
= A
;
10522 // Unregister these records.
10523 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
10524 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
10525 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
10526 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
10527 if (set
->RR_A
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
10528 if (set
->RR_PTR
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
10529 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
10532 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
10534 domainname newmname
;
10535 NetworkInterfaceInfo
*intf
;
10539 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
10540 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
10544 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
10547 AssignDomainName(&m
->MulticastHostname
, &newmname
);
10549 // 1. Stop advertising our address records on all interfaces
10550 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10551 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
);
10553 // 2. Start advertising our address records using the new name
10554 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10555 if (intf
->Advertise
) AdvertiseInterface(m
, intf
);
10558 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
10559 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) SetTargetToHostName(m
, rr
);
10560 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) SetTargetToHostName(m
, rr
);
10565 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
10567 (void)rr
; // Unused parameter
10571 char *msg
= "Unknown result";
10572 if (result
== mStatus_NoError
) msg
= "Name registered";
10573 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
10574 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
10578 if (result
== mStatus_NoError
)
10580 // Notify the client that the host name is successfully registered
10581 if (m
->MainCallback
)
10582 m
->MainCallback(m
, mStatus_NoError
);
10584 else if (result
== mStatus_NameConflict
)
10586 domainlabel oldlabel
= m
->hostlabel
;
10588 // 1. First give the client callback a chance to pick a new name
10589 if (m
->MainCallback
)
10590 m
->MainCallback(m
, mStatus_NameConflict
);
10592 // 2. If the client callback didn't do it, add (or increment) an index ourselves
10593 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
10594 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
10595 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
10596 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
10598 // 3. Generate the FQDNs from the hostlabel,
10599 // and make sure all SRV records, etc., are updated to reference our new hostname
10601 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
10603 else if (result
== mStatus_MemFree
)
10605 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
10606 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
10607 debugf("mDNS_HostNameCallback: MemFree (ignored)");
10610 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
10613 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
10615 NetworkInterfaceInfo
*intf
;
10616 active
->IPv4Available
= mDNSfalse
;
10617 active
->IPv6Available
= mDNSfalse
;
10618 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10619 if (intf
->InterfaceID
== active
->InterfaceID
)
10621 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
10622 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
10626 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
10629 LogInfo("RestartRecordGetZoneData: ResourceRecords");
10630 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
10631 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
10633 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
10634 // Zero out the updateid so that if we have a pending response from the server, it won't
10635 // be accepted as a valid response. If we accept the response, we might free the new "nta"
10636 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
10637 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
10641 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
10644 set
->NetWakeBrowse
.ThisQInterval
= -1;
10645 for (i
=0; i
<3; i
++)
10647 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
10648 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
10650 set
->NextSPSAttempt
= -1;
10651 set
->NextSPSAttemptTime
= m
->timenow
;
10654 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
10656 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
10657 while (p
&& p
!= set
) p
=p
->next
;
10658 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
10660 if (set
->InterfaceActive
)
10662 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
10663 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, set
->InterfaceID
, 0, mDNSfalse
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
10667 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
10669 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
10670 while (p
&& p
!= set
) p
=p
->next
;
10671 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
10673 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
10676 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
10678 // Stop our browse and resolve operations
10679 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
10680 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
10682 // Make special call to the browse callback to let it know it can to remove all records for this interface
10683 if (m
->SPSBrowseCallback
)
10685 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
10686 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
10687 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
10690 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
10691 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
10692 InitializeNetWakeState(m
, set
);
10696 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
10699 mDNSBool FirstOfType
= mDNStrue
;
10700 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
10702 if (!set
->InterfaceID
)
10703 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set
->ip
); return(mStatus_Invalid
); }
10705 if (!mDNSAddressIsValidNonZero(&set
->mask
))
10706 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set
->ip
, &set
->mask
); return(mStatus_Invalid
); }
10710 // Assume this interface will be active now, unless we find a duplicate already in the list
10711 set
->InterfaceActive
= mDNStrue
;
10712 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
10713 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
10715 InitializeNetWakeState(m
, set
);
10717 // Scan list to see if this InterfaceID is already represented
10722 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
10724 return(mStatus_AlreadyRegistered
);
10727 if ((*p
)->InterfaceID
== set
->InterfaceID
)
10729 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
10730 set
->InterfaceActive
= mDNSfalse
;
10731 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
10732 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
10733 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
10739 set
->next
= mDNSNULL
;
10742 if (set
->Advertise
)
10743 AdvertiseInterface(m
, set
);
10745 LogInfo("mDNS_RegisterInterface: InterfaceID %p %s (%#a) %s", set
->InterfaceID
, set
->ifname
, &set
->ip
,
10746 set
->InterfaceActive
?
10747 "not represented in list; marking active and retriggering queries" :
10748 "already represented in list; marking inactive for now");
10750 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
10752 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
10753 // giving the false impression that there's an active representative of this interface when there really isn't.
10754 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
10755 // even if we believe that we previously had an active representative of this interface.
10756 if (set
->McastTxRx
&& (FirstOfType
|| set
->InterfaceActive
))
10759 // Normally, after an interface comes up, we pause half a second before beginning probing.
10760 // This is to guard against cases where there's rapid interface changes, where we could be confused by
10761 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
10762 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
10763 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
10764 // and think it's a conflicting answer to our probe.
10765 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
10766 const mDNSs32 probedelay
= flapping
? mDNSPlatformOneSecond
* 5 : mDNSPlatformOneSecond
/ 2;
10767 const mDNSu8 numannounce
= flapping
? (mDNSu8
)1 : InitialAnnounceCount
;
10769 // Use a small amount of randomness:
10770 // In the case of a network administrator turning on an Ethernet hub so that all the
10771 // connected machines establish link at exactly the same time, we don't want them all
10772 // to go and hit the network with identical queries at exactly the same moment.
10773 // We set a random delay of up to InitialQuestionInterval (1/3 second).
10774 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
10775 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
10776 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
10777 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
10778 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
10779 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
10781 if (flapping
) LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
10783 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set
->ifname
, &set
->ip
, probedelay
);
10784 if (m
->SuppressProbes
== 0 ||
10785 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
10786 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
10788 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
10789 // it here also handles the wake up case as the network link comes UP after waking causing
10790 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
10791 // that the network link comes UP after 60 seconds and we never set the OWNER option
10792 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
10794 // Clear the flag that ignores IPv6 neighbor advertisements after 2 seconds.
10795 m
->clearIgnoreNA
= NonZeroTime(m
->timenow
+ 2 * mDNSPlatformOneSecond
);
10797 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
10799 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
10800 if (mDNSOpaque16IsZero(q
->TargetQID
))
10801 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
10802 { // then reactivate this question
10803 // If flapping, delay between first and second queries is nine seconds instead of one second
10804 mDNSBool dodelay
= flapping
&& (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
10805 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
10806 mDNSs32 qdelay
= dodelay
? mDNSPlatformOneSecond
* 5 : 0;
10807 if (dodelay
) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q
->qname
.c
, DNSTypeName(q
->qtype
));
10809 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
10811 q
->ThisQInterval
= initial
;
10812 q
->RequestUnicast
= 2; // Set to 2 because is decremented once *before* we check it
10814 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
10815 q
->RecentAnswerPkts
= 0;
10816 SetNextQueryTime(m
,q
);
10819 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
10820 // we now need them to re-probe if necessary, and then re-announce.
10821 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
10822 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
10823 mDNSCoreRestartRegistration(m
, rr
, numannounce
);
10826 RestartRecordGetZoneData(m
);
10828 CheckSuppressUnusableQuestions(m
);
10830 mDNS_UpdateAllowSleep(m
);
10833 return(mStatus_NoError
);
10836 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
10837 // the record list and/or question list.
10838 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
10839 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
10841 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
10842 mDNSBool revalidate
= mDNSfalse
;
10846 // Find this record in our list
10847 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
10848 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
10850 mDNS_DeactivateNetWake_internal(m
, set
);
10852 // Unlink this record from our list
10854 set
->next
= mDNSNULL
;
10856 if (!set
->InterfaceActive
)
10858 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
10859 NetworkInterfaceInfo
*intf
;
10860 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10861 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
10862 UpdateInterfaceProtocols(m
, intf
);
10866 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
10869 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %p %s (%#a) exists;"
10870 " making it active", set
->InterfaceID
, set
->ifname
, &set
->ip
);
10871 if (intf
->InterfaceActive
)
10872 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set
->ifname
, &set
->ip
);
10873 intf
->InterfaceActive
= mDNStrue
;
10874 UpdateInterfaceProtocols(m
, intf
);
10876 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
10878 // See if another representative *of the same type* exists. If not, we mave have gone from
10879 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
10880 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
10881 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
10883 if (!intf
) revalidate
= mDNStrue
;
10893 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %p %s (%#a) deregistered;"
10894 " marking questions etc. dormant", set
->InterfaceID
, set
->ifname
, &set
->ip
);
10896 if (set
->McastTxRx
&& flapping
)
10897 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
10899 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
10900 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
10901 for (q
= m
->Questions
; q
; q
=q
->next
)
10903 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
10904 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
10906 q
->FlappingInterface2
= q
->FlappingInterface1
;
10907 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
10911 // 2. Flush any cache records received on this interface
10912 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
10913 FORALL_CACHERECORDS(slot
, cg
, rr
)
10915 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
10917 // If this interface is deemed flapping,
10918 // postpone deleting the cache records in case the interface comes back again
10919 if (set
->McastTxRx
&& flapping
)
10921 // For a flapping interface we want these record to go away after 30 seconds
10922 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
10923 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
10924 // if the interface does come back, any relevant questions will be reactivated anyway
10925 rr
->UnansweredQueries
= MaxUnansweredQueries
;
10929 mDNS_PurgeCacheResourceRecord(m
, rr
);
10934 // 3. Any DNS servers specific to this interface are now unusable
10935 for (s
= m
->DNSServers
; s
; s
= s
->next
)
10936 if (s
->interface
== set
->InterfaceID
)
10938 s
->interface
= mDNSInterface_Any
;
10939 s
->teststate
= DNSServer_Disabled
;
10944 // If we were advertising on this interface, deregister those address and reverse-lookup records now
10945 if (set
->Advertise
) DeadvertiseInterface(m
, set
);
10947 // If we have any cache records received on this interface that went away, then re-verify them.
10948 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
10949 // giving the false impression that there's an active representative of this interface when there really isn't.
10950 // Don't need to do this when shutting down, because *all* interfaces are about to go away
10951 if (revalidate
&& !m
->ShutdownTime
)
10956 FORALL_CACHERECORDS(slot
, cg
, rr
)
10957 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
10958 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
10961 CheckSuppressUnusableQuestions(m
);
10963 mDNS_UpdateAllowSleep(m
);
10968 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
10970 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
10971 (void)m
; // Unused parameter
10975 char *msg
= "Unknown result";
10976 if (result
== mStatus_NoError
) msg
= "Name Registered";
10977 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
10978 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
10979 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
10983 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
10984 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
10986 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
10987 if (result
== mStatus_NameConflict
)
10989 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
10990 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
10994 if (result
== mStatus_MemFree
)
10996 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
10997 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
10998 // every record is finished cleaning up.
11000 ExtraResourceRecord
*e
= sr
->Extras
;
11002 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
11003 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
11004 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
11005 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
11006 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
11010 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
11014 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
11015 // then we can now report the NameConflict to the client
11016 if (sr
->Conflict
) result
= mStatus_NameConflict
;
11020 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered" : "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
11021 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
11022 // function is allowed to do anything, including deregistering this service and freeing its memory.
11023 if (sr
->ServiceCallback
)
11024 sr
->ServiceCallback(m
, sr
, result
);
11027 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
11029 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
11030 if (sr
->ServiceCallback
)
11031 sr
->ServiceCallback(m
, sr
, result
);
11035 mDNSlocal AuthRecType
setAuthRecType(mDNSInterfaceID InterfaceID
, mDNSu32 flags
)
11037 AuthRecType artype
;
11039 if (InterfaceID
== mDNSInterface_LocalOnly
)
11040 artype
= AuthRecordLocalOnly
;
11041 else if (InterfaceID
== mDNSInterface_P2P
)
11042 artype
= AuthRecordP2P
;
11043 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& coreFlagIncludeP2P
))
11044 artype
= AuthRecordAnyIncludeP2P
;
11045 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& coreFlagIncludeAWDL
))
11046 artype
= AuthRecordAnyIncludeAWDL
;
11048 artype
= AuthRecordAny
;
11054 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
11055 // Type is service type (e.g. "_ipp._tcp.")
11056 // Domain is fully qualified domain name (i.e. ending with a null label)
11057 // We always register a TXT, even if it is empty (so that clients are not
11058 // left waiting forever looking for a nonexistent record.)
11059 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
11060 // then the default host name (m->MulticastHostname) is automatically used
11061 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
11062 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
11063 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
11064 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
11065 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
11066 mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
, mDNSu32 flags
)
11071 AuthRecType artype
;
11072 mDNSu8 recordType
= (flags
& coreFlagKnownUnique
) ? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
11074 sr
->ServiceCallback
= Callback
;
11075 sr
->ServiceContext
= Context
;
11076 sr
->Conflict
= mDNSfalse
;
11078 sr
->Extras
= mDNSNULL
;
11079 sr
->NumSubTypes
= NumSubTypes
;
11080 sr
->SubTypes
= SubTypes
;
11082 artype
= setAuthRecType(InterfaceID
, flags
);
11084 // Initialize the AuthRecord objects to sane values
11085 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
11086 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, artype
, ServiceCallback
, sr
);
11087 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
11089 if (SameDomainName(type
, (const domainname
*) "\x4" "_ubd" "\x4" "_tcp"))
11090 hostTTL
= kHostNameSmallTTL
;
11092 hostTTL
= kHostNameTTL
;
11094 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, hostTTL
, recordType
, artype
, ServiceCallback
, sr
);
11095 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
11097 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
11098 if (mDNSIPPortIsZero(port
))
11099 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, InterfaceID
, NSSCallback
, sr
, flags
));
11101 // If the client is registering an oversized TXT record,
11102 // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
11103 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
11104 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
11106 // Set up the record names
11107 // For now we only create an advisory record for the main type, not for subtypes
11108 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
11109 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
11110 return(mStatus_BadParamErr
);
11111 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
11112 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
11113 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
11115 // 1. Set up the ADV record rdata to advertise our service type
11116 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
11118 // 2. Set up the PTR record rdata to point to our service name
11119 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
11120 // Note: uDNS registration code assumes that Additional1 points to the SRV record
11121 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
11122 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
11123 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
11125 // 2a. Set up any subtype PTRs to point to our service name
11126 // If the client is using subtypes, it is the client's responsibility to have
11127 // already set the first label of the record name to the subtype being registered
11128 for (i
=0; i
<NumSubTypes
; i
++)
11131 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
11132 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
11133 AppendDomainName(&st
, type
);
11134 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
11135 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
11136 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
11137 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
11138 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
11141 // 3. Set up the SRV record rdata.
11142 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
11143 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
11144 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
11146 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
11147 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
11148 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
11150 // 4. Set up the TXT record rdata,
11151 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
11152 // Note: uDNS registration code assumes that DependentOn points to the SRV record
11153 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
11154 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
11156 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
11157 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
11158 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
11160 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
11163 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
11164 // that if the SRV cannot find a target, rest of the records that belong to this service
11165 // will not be activated.
11166 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
11167 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
11168 // any list and hence no need to deregister. We could probably do similar checks for other
11169 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
11175 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
11176 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
11177 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
11178 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
11179 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
11180 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
11181 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
11182 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
11183 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
11187 if (err
) mDNS_DeregisterService(m
, sr
);
11191 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
11192 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
, mDNSu32 flags
)
11194 ExtraResourceRecord
**e
;
11196 AuthRecType artype
;
11197 mDNSInterfaceID InterfaceID
= sr
->RR_PTR
.resrec
.InterfaceID
;
11199 artype
= setAuthRecType(InterfaceID
, flags
);
11201 extra
->next
= mDNSNULL
;
11202 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
11203 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
11204 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
11208 while (*e
) e
= &(*e
)->next
;
11210 if (ttl
== 0) ttl
= kStandardTTL
;
11212 extra
->r
.DependentOn
= &sr
->RR_SRV
;
11214 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
11215 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
11217 status
= mDNS_Register_internal(m
, &extra
->r
);
11218 if (status
== mStatus_NoError
) *e
= extra
;
11224 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
11225 mDNSRecordCallback MemFreeCallback
, void *Context
)
11227 ExtraResourceRecord
**e
;
11232 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
11235 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
11236 status
= mStatus_BadReferenceErr
;
11240 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
11241 extra
->r
.RecordCallback
= MemFreeCallback
;
11242 extra
->r
.RecordContext
= Context
;
11244 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
11250 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
11252 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
11253 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
11254 domainlabel name1
, name2
;
11255 domainname type
, domain
;
11256 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
11257 ExtraResourceRecord
*extras
= sr
->Extras
;
11260 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
11264 IncrementLabelSuffix(&name2
, mDNStrue
);
11268 if (SameDomainName(&domain
, &localdomain
))
11269 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
11270 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
11272 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
11273 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
11274 sr
->SubTypes
, sr
->NumSubTypes
,
11275 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
, 0);
11277 // mDNS_RegisterService() just reset sr->Extras to NULL.
11278 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
11279 // through the old list of extra records, and re-add them to our freshly created service registration
11280 while (!err
&& extras
)
11282 ExtraResourceRecord
*e
= extras
;
11283 extras
= extras
->next
;
11284 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
, 0);
11290 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
11291 // which may change the record list and/or question list.
11292 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
11293 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
11295 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
11296 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
11298 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
11300 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
11301 return(mStatus_BadReferenceErr
);
11303 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
11305 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
11306 // Avoid race condition:
11307 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
11308 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
11309 // If the client happens to deregister the service in the middle of that process, then
11310 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
11311 // instead of incorrectly promoting it to mStatus_NameConflict.
11312 // This race condition is exposed particularly when the conformance test generates
11313 // a whole batch of simultaneous conflicts across a range of services all advertised
11314 // using the same system default name, and if we don't take this precaution then
11315 // we end up incrementing m->nicelabel multiple times instead of just once.
11316 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
11317 sr
->Conflict
= mDNSfalse
;
11318 return(mStatus_NoError
);
11324 ExtraResourceRecord
*e
;
11328 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
11329 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
11330 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
11331 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
11333 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
11335 // We deregister all of the extra records, but we leave the sr->Extras list intact
11336 // in case the client wants to do a RenameAndReregister and reinstate the registration
11339 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
11343 for (i
=0; i
<sr
->NumSubTypes
; i
++)
11344 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
11346 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
11352 // Create a registration that asserts that no such service exists with this name.
11353 // This can be useful where there is a given function is available through several protocols.
11354 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
11355 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
11356 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
11357 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
11358 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
11359 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
11360 const domainname
*const host
,
11361 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
, mDNSu32 flags
)
11363 AuthRecType artype
;
11365 artype
= setAuthRecType(InterfaceID
, flags
);
11367 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, artype
, Callback
, Context
);
11368 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
11369 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
11370 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
11371 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
11372 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
11373 else rr
->AutoTarget
= Target_AutoHost
;
11374 return(mDNS_Register(m
, rr
));
11377 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
11378 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
11380 AuthRecType artype
;
11382 if (InterfaceID
== mDNSInterface_LocalOnly
)
11383 artype
= AuthRecordLocalOnly
;
11384 else if (InterfaceID
== mDNSInterface_P2P
)
11385 artype
= AuthRecordP2P
;
11387 artype
= AuthRecordAny
;
11388 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, mDNSNULL
, mDNSNULL
);
11389 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
11390 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
11391 return(mDNS_Register(m
, rr
));
11394 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
11397 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
11401 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
11404 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
11408 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
11413 for (i
=0; i
<10; i
++)
11415 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
11416 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
11419 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
11424 // ***************************************************************************
11425 #if COMPILER_LIKES_PRAGMA_MARK
11427 #pragma mark - Sleep Proxy Server
11430 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
11432 // If we see an ARP from a machine we think is sleeping, then either
11433 // (i) the machine has woken, or
11434 // (ii) it's just a stray old packet from before the machine slept
11435 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
11436 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
11437 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
11438 // 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*
11439 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
11440 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
11442 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
11443 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
11445 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
11446 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
11447 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
11448 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
11449 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
11450 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
11451 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
11452 InitializeLastAPTime(m
, rr
);
11455 rr
->AnnounceCount
= InitialAnnounceCount
;
11456 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
11457 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
11458 SetNextAnnounceProbeTime(m
, rr
);
11462 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
11464 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
11466 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
11472 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
11473 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
11474 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
11475 // The times we might need to react to an ARP Announcement are:
11476 // (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
11477 // (ii) if it's a conflicting Announcement from another host
11478 // -- and we check for these in Pass 2 below.
11479 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
11481 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
11482 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
11483 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
11485 static const char msg1
[] = "ARP Req from owner -- re-probing";
11486 static const char msg2
[] = "Ignoring ARP Request from ";
11487 static const char msg3
[] = "Creating Local ARP Cache entry ";
11488 static const char msg4
[] = "Answering ARP Request from ";
11489 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
11490 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
11491 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
11492 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
11493 intf
->ifname
, msg
, &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
11494 if (msg
== msg1
) RestartARPProbing(m
, rr
);
11495 else if (msg
== msg3
) mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
11496 else if (msg
== msg4
) SendARP(m
, 2, rr
, &arp
->tpa
, &arp
->sha
, &arp
->spa
, &arp
->sha
);
11501 // 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.
11502 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
11503 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
11504 // 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.
11505 // If we see an apparently conflicting ARP, we check the sender hardware address:
11506 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
11507 // 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.
11508 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
11509 debugf("ARP from self for %.4a", &arp
->tpa
);
11512 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
11513 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
11514 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
11515 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
))
11517 RestartARPProbing(m
, rr
);
11518 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
11519 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
11520 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
11521 &arp
->sha
, &arp
->spa
, &arp
->tpa
, ARDisplayString(m
, rr
));
11524 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
11525 &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
11526 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
11535 // Option 1 is Source Link Layer Address Option
11536 // Option 2 is Target Link Layer Address Option
11537 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
11539 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
11540 while (options < end)
11542 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
11543 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
11544 options += options[1] * 8;
11550 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
11551 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
11554 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
11559 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
11560 if (ndp
->type
== NDP_Sol
)
11562 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
11564 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
11565 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
11566 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
11568 static const char msg1
[] = "NDP Req from owner -- re-probing";
11569 static const char msg2
[] = "Ignoring NDP Request from ";
11570 static const char msg3
[] = "Creating Local NDP Cache entry ";
11571 static const char msg4
[] = "Answering NDP Request from ";
11572 static const char msg5
[] = "Answering NDP Probe from ";
11573 const char *const msg
= sha
&& mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
11574 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
11575 sha
&& mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
11576 spa
&& mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
11577 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
11578 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
11579 if (msg
== msg1
) RestartARPProbing(m
, rr
);
11580 else if (msg
== msg3
)
11582 if (!(m
->KnownBugs
& mDNS_KnownBug_LimitedIPv6
))
11583 mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
11585 else if (msg
== msg4
) SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
11586 else if (msg
== msg5
) SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
11590 // 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.
11591 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
11592 debugf("NDP from self for %.16a", &ndp
->target
);
11595 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
11596 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
11597 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
11598 // Hence it is the NDP target address we care about, not the actual packet source address.
11599 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
11600 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
11601 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
11602 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
11603 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
))
11605 RestartARPProbing(m
, rr
);
11606 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
11607 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
11608 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
11611 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
11612 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
11613 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
11621 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
11622 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
11624 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
11625 mDNSBool wake
= mDNSfalse
;
11626 mDNSBool kaWake
= mDNSfalse
;
11630 #define XX wake ? "Received" : "Ignoring", end-p
11631 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
11637 #define TH_FIN 0x01
11638 #define TH_SYN 0x02
11639 #define TH_RST 0x04
11641 kr
= mDNS_MatchKeepaliveInfo(m
, dst
, src
, port
, t
->tcp
.src
, &seq
, &ack
);
11644 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
));
11646 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
11647 // (b) packet that contains new data and acks a sequence number higher than the one
11648 // we have been sending in the keepalive
11650 wake
= ((t
->tcp
.flags
& TH_RST
) || (t
->tcp
.flags
& TH_FIN
)) ;
11654 mDNSu32 pseq
, pack
;
11655 mDNSBool data
= mDNSfalse
;
11658 // Convert to host order
11659 ptr
= (mDNSu8
*)&seq
;
11660 seq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
11662 ptr
= (mDNSu8
*)&ack
;
11663 ack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
11666 ptr
= (mDNSu8
*)&pseq
;
11667 pseq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
11670 ptr
= (mDNSu8
*)&pack
;
11671 pack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
11673 // If the other side is acking one more than our sequence number (keepalive is one
11674 // less than the last valid sequence sent) and it's sequence is more than what we
11676 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
11677 tcphlen
= ((t
->tcp
.offset
>> 4) * 4);
11678 if (end
- ((mDNSu8
*)t
+ tcphlen
) > 0) data
= mDNStrue
;
11679 wake
= ((int)(pack
- seq
) > 0) && ((int)(pseq
- ack
) >= 0) && data
;
11680 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
11681 end
, tcphlen
, end
- ((mDNSu8
*)t
+ tcphlen
), pack
, seq
, pseq
, ack
, wake
);
11683 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t
->tcp
.flags
); }
11690 // (a) RST is not set, AND
11691 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
11692 wake
= (!(t
->tcp
.flags
& TH_RST
) && (t
->tcp
.flags
& (TH_FIN
|TH_SYN
)) != TH_FIN
);
11694 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
11695 // except for ssh connections, where we'll wake for plain data packets too
11696 if (!mDNSSameIPPort(port
, SSHPort
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
11698 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
11699 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
11700 (t
->tcp
.flags
& 2) ? " SYN" : "",
11701 (t
->tcp
.flags
& 1) ? " FIN" : "",
11702 (t
->tcp
.flags
& 4) ? " RST" : "");
11708 #define ARD_AsNumber 3283
11709 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
11710 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
11711 if (udplen
>= sizeof(UDPHeader
))
11713 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
11716 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
11717 if (mDNSSameIPPort(port
, IPSECPort
))
11719 // Specifically ignore NAT keepalive packets
11720 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
11723 // Skip over the Non-ESP Marker if present
11724 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
11725 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
11726 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
11727 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
11728 if ((ike
->Version
& 0x10) == 0x10)
11730 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
11731 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
11732 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
11733 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
11738 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
11739 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
11740 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
11741 // UDP header (8 bytes)
11742 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
11743 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
11745 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
11750 case 0x3A: if (&t
->bytes
[len
] <= end
)
11752 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
11753 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
11754 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
11758 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
11764 AuthRecord
*rr
, *r2
;
11767 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
11768 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
11769 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
11770 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
11772 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
11773 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
11774 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
11775 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
11776 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
11777 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
11779 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
11780 if (!r2
&& kaWake
) r2
= rr
; // So that we wake for keepalive packets, even without a matching SRV record
11783 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
11784 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
11785 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
11788 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
11789 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
11795 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
11797 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
11798 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
11799 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
11800 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
11801 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
11803 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
11804 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
11805 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
11806 // since it points to a an address 14 bytes before pkt.
11807 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
11808 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
11810 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
11812 // Is ARP? Length must be at least 14 + 28 = 42 bytes
11813 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
11814 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
11815 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
11816 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
11818 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
11819 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
, &pkt
->v4
.dst
);
11820 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
11821 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
11822 if (end
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
11823 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
, 0);
11825 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
11826 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
11828 const mDNSu8
*const trans
= p
+ 54;
11829 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
, &pkt
->v6
.dst
);
11830 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
11831 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
11832 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
11833 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
11834 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
11838 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
11840 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d.%d %#s",
11841 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
, &m
->nicelabel
);
11844 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
11846 if (result
== mStatus_NameConflict
)
11847 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
11848 else if (result
== mStatus_MemFree
)
11854 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
11858 ConstructSleepProxyServerName(m
, &name
);
11859 mDNS_RegisterService(m
, srs
,
11860 &name
, &SleepProxyServiceType
, &localdomain
,
11861 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
11862 (mDNSu8
*)"", 1, // TXT data, length
11863 mDNSNULL
, 0, // Subtypes (none)
11864 mDNSInterface_Any
, // Interface ID
11865 SleepProxyServerCallback
, mDNSNULL
, 0); // Callback, context, flags
11867 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
11872 // Called with lock held
11873 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
, mDNSu8 features
)
11875 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
11876 mDNS_DropLockBeforeCallback();
11878 // If turning off SPS, close our socket
11879 // (Do this first, BEFORE calling mDNS_DeregisterService below)
11880 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
11882 // If turning off, or changing type, deregister old name
11883 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
11884 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
11886 // Record our new SPS parameters
11888 m
->SPSPortability
= port
;
11889 m
->SPSMarginalPower
= marginalpower
;
11890 m
->SPSTotalPower
= totpower
;
11891 m
->SPSFeatureFlags
= features
;
11892 // If turning on, open socket and advertise service
11897 m
->SPSSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
11898 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
11900 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
11902 else if (m
->SPSState
)
11904 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
11905 m
->NextScheduledSPS
= m
->timenow
;
11908 mDNS_ReclaimLockAfterCallback();
11911 // ***************************************************************************
11912 #if COMPILER_LIKES_PRAGMA_MARK
11914 #pragma mark - Startup and Shutdown
11917 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
11919 if (storage
&& numrecords
)
11922 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
11923 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
11924 storage
[numrecords
-1].next
= m
->rrcache_free
;
11925 m
->rrcache_free
= storage
;
11926 m
->rrcache_size
+= numrecords
;
11930 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
11933 mDNS_GrowCache_internal(m
, storage
, numrecords
);
11937 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
11938 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
11939 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
11945 if (!rrcachestorage
) rrcachesize
= 0;
11949 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
11950 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
11951 m
->DivertMulticastAdvertisements
= mDNSfalse
;
11952 m
->mDNSPlatformStatus
= mStatus_Waiting
;
11953 m
->UnicastPort4
= zeroIPPort
;
11954 m
->UnicastPort6
= zeroIPPort
;
11955 m
->PrimaryMAC
= zeroEthAddr
;
11956 m
->MainCallback
= Callback
;
11957 m
->MainContext
= Context
;
11958 m
->rec
.r
.resrec
.RecordType
= 0;
11960 // For debugging: To catch and report locking failures
11962 m
->mDNS_reentrancy
= 0;
11963 m
->ShutdownTime
= 0;
11964 m
->lock_rrcache
= 0;
11965 m
->lock_Questions
= 0;
11966 m
->lock_Records
= 0;
11968 // Task Scheduling variables
11969 result
= mDNSPlatformTimeInit();
11970 if (result
!= mStatus_NoError
) return(result
);
11971 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
11972 timenow
= mDNS_TimeNow_NoLock(m
);
11974 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
11975 m
->timenow_last
= timenow
;
11976 m
->NextScheduledEvent
= timenow
;
11977 m
->SuppressSending
= timenow
;
11978 m
->NextCacheCheck
= timenow
+ 0x78000000;
11979 m
->NextScheduledQuery
= timenow
+ 0x78000000;
11980 m
->NextScheduledProbe
= timenow
+ 0x78000000;
11981 m
->NextScheduledResponse
= timenow
+ 0x78000000;
11982 m
->NextScheduledNATOp
= timenow
+ 0x78000000;
11983 m
->NextScheduledSPS
= timenow
+ 0x78000000;
11984 m
->NextScheduledKA
= timenow
+ 0x78000000;
11985 m
->NextScheduledStopTime
= timenow
+ 0x78000000;
11986 m
->RandomQueryDelay
= 0;
11987 m
->RandomReconfirmDelay
= 0;
11989 m
->LocalRemoveEvents
= mDNSfalse
;
11990 m
->SleepState
= SleepState_Awake
;
11991 m
->SleepSeqNum
= 0;
11992 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
11993 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
11994 m
->clearIgnoreNA
= NonZeroTime(timenow
+ 2 * mDNSPlatformOneSecond
);
11998 // These fields only required for mDNS Searcher...
11999 m
->Questions
= mDNSNULL
;
12000 m
->NewQuestions
= mDNSNULL
;
12001 m
->CurrentQuestion
= mDNSNULL
;
12002 m
->LocalOnlyQuestions
= mDNSNULL
;
12003 m
->NewLocalOnlyQuestions
= mDNSNULL
;
12004 m
->RestartQuestion
= mDNSNULL
;
12005 m
->ValidationQuestion
= mDNSNULL
;
12006 m
->rrcache_size
= 0;
12007 m
->rrcache_totalused
= 0;
12008 m
->rrcache_active
= 0;
12009 m
->rrcache_report
= 10;
12010 m
->rrcache_free
= mDNSNULL
;
12012 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
12014 m
->rrcache_hash
[slot
] = mDNSNULL
;
12015 m
->rrcache_nextcheck
[slot
] = timenow
+ 0x78000000;;
12018 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
12019 m
->rrauth
.rrauth_free
= mDNSNULL
;
12021 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
12022 m
->rrauth
.rrauth_hash
[slot
] = mDNSNULL
;
12024 // Fields below only required for mDNS Responder...
12025 m
->hostlabel
.c
[0] = 0;
12026 m
->nicelabel
.c
[0] = 0;
12027 m
->MulticastHostname
.c
[0] = 0;
12028 m
->HIHardware
.c
[0] = 0;
12029 m
->HISoftware
.c
[0] = 0;
12030 m
->ResourceRecords
= mDNSNULL
;
12031 m
->DuplicateRecords
= mDNSNULL
;
12032 m
->NewLocalRecords
= mDNSNULL
;
12033 m
->NewLocalOnlyRecords
= mDNSfalse
;
12034 m
->CurrentRecord
= mDNSNULL
;
12035 m
->HostInterfaces
= mDNSNULL
;
12036 m
->ProbeFailTime
= 0;
12037 m
->NumFailedProbes
= 0;
12038 m
->SuppressProbes
= 0;
12040 #ifndef UNICAST_DISABLED
12041 m
->NextuDNSEvent
= timenow
+ 0x78000000;
12042 m
->NextSRVUpdate
= timenow
+ 0x78000000;
12044 m
->DNSServers
= mDNSNULL
;
12046 m
->Router
= zeroAddr
;
12047 m
->AdvertisedV4
= zeroAddr
;
12048 m
->AdvertisedV6
= zeroAddr
;
12050 m
->AuthInfoList
= mDNSNULL
;
12052 m
->ReverseMap
.ThisQInterval
= -1;
12053 m
->StaticHostname
.c
[0] = 0;
12055 m
->Hostnames
= mDNSNULL
;
12056 m
->AutoTunnelNAT
.clientContext
= mDNSNULL
;
12058 m
->StartWABQueries
= mDNSfalse
;
12059 m
->mDNSHandlePeerEvents
= mDNSfalse
;
12061 // NAT traversal fields
12062 m
->NATTraversals
= mDNSNULL
;
12063 m
->CurrentNATTraversal
= mDNSNULL
;
12064 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
12065 m
->retryGetAddr
= timenow
+ 0x78000000; // absolute time when we retry
12066 m
->ExternalAddress
= zerov4Addr
;
12068 m
->NATMcastRecvskt
= mDNSNULL
;
12069 m
->LastNATupseconds
= 0;
12070 m
->LastNATReplyLocalTime
= timenow
;
12071 m
->LastNATMapResultCode
= NATErr_None
;
12073 m
->UPnPInterfaceID
= 0;
12074 m
->SSDPSocket
= mDNSNULL
;
12075 m
->SSDPWANPPPConnection
= mDNSfalse
;
12076 m
->UPnPRouterPort
= zeroIPPort
;
12077 m
->UPnPSOAPPort
= zeroIPPort
;
12078 m
->UPnPRouterURL
= mDNSNULL
;
12079 m
->UPnPWANPPPConnection
= mDNSfalse
;
12080 m
->UPnPSOAPURL
= mDNSNULL
;
12081 m
->UPnPRouterAddressString
= mDNSNULL
;
12082 m
->UPnPSOAPAddressString
= mDNSNULL
;
12084 m
->SPSPortability
= 0;
12085 m
->SPSMarginalPower
= 0;
12086 m
->SPSTotalPower
= 0;
12087 m
->SPSFeatureFlags
= 0;
12089 m
->SPSProxyListChanged
= mDNSNULL
;
12090 m
->SPSSocket
= mDNSNULL
;
12091 m
->SPSBrowseCallback
= mDNSNULL
;
12092 m
->ProxyRecords
= 0;
12096 #if APPLE_OSX_mDNSResponder
12097 m
->TunnelClients
= mDNSNULL
;
12100 CHECK_WCF_FUNCTION(WCFConnectionNew
)
12102 m
->WCF
= WCFConnectionNew();
12103 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
12109 result
= mDNSPlatformInit(m
);
12111 #ifndef UNICAST_DISABLED
12112 // It's better to do this *after* the platform layer has set up the
12113 // interface list and security credentials
12114 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
12120 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
12122 if (m
->SPSState
== 1)
12124 domainlabel name
, newname
;
12125 domainname type
, domain
;
12126 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
12127 ConstructSleepProxyServerName(m
, &newname
);
12128 if (!SameDomainLabelCS(name
.c
, newname
.c
))
12130 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
12131 // When SleepProxyServerCallback gets the mStatus_MemFree message,
12132 // it will reregister the service under the new name
12134 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
12138 if (m
->MainCallback
)
12139 m
->MainCallback(m
, mStatus_ConfigChanged
);
12142 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
12145 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
12146 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
12149 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
, const DNSServer
* const ptr
, mDNSBool lameduck
)
12151 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
12152 cr
->resrec
.rrtype
== kDNSType_A
||
12153 cr
->resrec
.rrtype
== kDNSType_AAAA
||
12154 cr
->resrec
.rrtype
== kDNSType_SRV
;
12158 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
12159 purge
? "purging" : "reconfirming",
12160 lameduck
? "lame duck" : "new",
12161 ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
, CRDisplayString(m
, cr
));
12165 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
12166 mDNS_PurgeCacheResourceRecord(m
, cr
);
12170 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
12171 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12175 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
)
12177 const mDNSu32 slot
= HashSlot(&q
->qname
);
12178 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
12181 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
12183 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
12185 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m
, rp
));
12186 mDNS_PurgeCacheResourceRecord(m
, rp
);
12191 // If we need to validate the negative response, we need the NSECs to prove
12192 // the non-existence. If we don't have the cached NSECs, purge them so that
12193 // we can reissue the question with EDNS0/DO bit set.
12194 mDNSlocal
void mDNS_CheckForCachedNSECS(mDNS
*const m
, DNSQuestion
*q
)
12196 const mDNSu32 slot
= HashSlot(&q
->qname
);
12197 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
12200 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
12202 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
) &&
12203 rp
->resrec
.RecordType
== kDNSRecordTypePacketNegative
&&
12206 LogInfo("mDNS_CheckForCachedNSECS: Flushing %s", CRDisplayString(m
, rp
));
12207 mDNS_PurgeCacheResourceRecord(m
, rp
);
12212 // Check for a positive unicast response to the question but with qtype
12213 mDNSexport mDNSBool
mDNS_CheckForCacheRecord(mDNS
*const m
, DNSQuestion
*q
, mDNSu16 qtype
)
12215 DNSQuestion question
;
12216 const mDNSu32 slot
= HashSlot(&q
->qname
);
12217 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
12220 // Create an identical question but with qtype
12221 mDNS_SetupQuestion(&question
, q
->InterfaceID
, &q
->qname
, qtype
, mDNSNULL
, mDNSNULL
);
12222 question
.qDNSServer
= q
->qDNSServer
;
12224 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
12226 if (!rp
->resrec
.InterfaceID
&& rp
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&&
12227 SameNameRecordAnswersQuestion(&rp
->resrec
, &question
))
12229 LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m
, rp
));
12236 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
12242 if (q
->DuplicateOf
)
12243 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
12245 // Make sure all the duplicate questions point to the same DNSServer so that delivery
12246 // of events for all of them are consistent. Duplicates for a question are always inserted
12247 // after in the list.
12248 q
->qDNSServer
= new;
12249 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
12251 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
12255 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
12261 mDNSAddr v4
, v6
, r
;
12263 DNSServer
*ptr
, **p
= &m
->DNSServers
;
12264 const DNSServer
*oldServers
= m
->DNSServers
;
12266 McastResolver
*mr
, **mres
= &m
->McastResolvers
;
12268 debugf("uDNS_SetupDNSConfig: entry");
12270 // Let the platform layer get the current DNS information
12271 // The m->StartWABQueries is set when we get the first domain enumeration query (no need to hit the network
12272 // with domain enumeration queries until we actually need that information). Even if it is not set, we still
12273 // need to setup the search domains so that we can append them to queries that need them.
12275 uDNS_SetupSearchDomains(m
, m
->StartWABQueries
? UDNS_START_WAB_QUERY
: 0);
12279 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
12281 ptr
->penaltyTime
= 0;
12282 ptr
->flags
|= DNSServer_FlagDelete
;
12285 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
12286 // mcast resolvers. Today we get both mcast and ucast configuration using the same
12288 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
12289 mr
->flags
|= McastResolver_FlagDelete
;
12291 mDNSPlatformSetDNSConfig(m
, mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
);
12293 // For now, we just delete the mcast resolvers. We don't deal with cache or
12294 // questions here. Neither question nor cache point to mcast resolvers. Questions
12295 // do inherit the timeout values from mcast resolvers. But we don't bother
12296 // affecting them as they never change.
12299 if (((*mres
)->flags
& DNSServer_FlagDelete
) != 0)
12302 *mres
= (*mres
)->next
;
12303 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr
, mr
->domain
.c
);
12304 mDNSPlatformMemFree(mr
);
12308 (*mres
)->flags
&= ~McastResolver_FlagNew
;
12309 mres
= &(*mres
)->next
;
12313 // Update our qDNSServer pointers before we go and free the DNSServer object memory
12315 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
12316 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
12317 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
12318 // DNSServers and flush the cache.
12320 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
12321 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
12322 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
12323 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
12324 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
12325 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
12326 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
12327 // the same resGroupID.
12329 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
12330 // of the old followed by ADD of the new records.
12332 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
12333 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
12334 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
12336 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
12337 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
12338 // non-scoped question and vice versa.
12340 for (q
= m
->Questions
; q
; q
=q
->next
)
12341 if (!mDNSOpaque16IsZero(q
->TargetQID
))
12345 if (q
->DuplicateOf
) continue;
12346 SetValidDNSServers(m
, q
);
12347 q
->triedAllServersOnce
= 0;
12348 s
= GetServerForQuestion(m
, q
);
12352 // If DNS Server for this question has changed, reactivate it
12353 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
12354 t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), t
? t
->domain
.c
: (mDNSu8
*)"",
12355 s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), s
? s
->domain
.c
: (mDNSu8
*)"",
12356 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->InterfaceID
);
12358 DNSServerChangeForQuestion(m
, q
, s
);
12359 q
->unansweredQueries
= 0;
12360 // We still need to pick a new DNSServer for the questions that have been
12361 // suppressed, but it is wrong to activate the query as DNS server change
12362 // could not possibly change the status of SuppressUnusable questions
12363 if (!QuerySuppressed(q
))
12365 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
12366 ActivateUnicastQuery(m
, q
, mDNStrue
);
12367 // ActivateUnicastQuery is called for duplicate questions also as it does something
12368 // special for AutoTunnel questions
12369 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
12371 if (qptr
->DuplicateOf
== q
) ActivateUnicastQuery(m
, qptr
, mDNStrue
);
12377 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
12378 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), q
->DuplicateOf
, q
->SuppressUnusable
);
12379 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
12380 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
12384 FORALL_CACHERECORDS(slot
, cg
, cr
)
12386 if (cr
->resrec
.InterfaceID
) continue;
12387 // We just mark them for purge or reconfirm.
12389 // The new DNSServer may be a scoped or non-scoped one. We use the active question's
12390 // InterfaceID for looking up the right DNS server
12391 ptr
= GetServerForName(m
, cr
->resrec
.name
, cr
->CRActiveQuestion
? cr
->CRActiveQuestion
->InterfaceID
: mDNSNULL
);
12393 // Purge or Reconfirm if this cache entry would use the new DNS server
12394 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
12396 // As the DNSServers for this cache record is not the same anymore, we don't
12397 // want any new questions to pick this old value. If there is no active question,
12398 // we can't possibly re-confirm, so purge in that case.
12399 if (cr
->CRActiveQuestion
== mDNSNULL
)
12401 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m
, cr
),
12402 &ptr
->addr
, (cr
->resrec
.rDNSServer
!= mDNSNULL
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
));
12403 mDNS_PurgeCacheResourceRecord(m
, cr
);
12407 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m
, cr
),
12408 &ptr
->addr
, (cr
->resrec
.rDNSServer
!= mDNSNULL
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
));
12409 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNSfalse
);
12416 if (((*p
)->flags
& DNSServer_FlagDelete
) != 0)
12418 // Scan our cache, looking for uDNS records that we would have queried this server for.
12419 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
12420 // different DNS servers can give different answers to the same question.
12422 FORALL_CACHERECORDS(slot
, cg
, cr
)
12424 if (cr
->resrec
.InterfaceID
) continue;
12425 if (cr
->resrec
.rDNSServer
== ptr
)
12427 // If we don't have an active question for this cache record, neither Purge can
12428 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
12429 // pointer on the record NULL so that we don't point to freed memory (We might dereference
12430 // DNSServer pointers from resource record for logging purposes).
12432 // If there is an active question, point to its DNSServer as long as it does not point to the
12433 // freed one. We already went through the questions above and made them point at either the
12434 // new server or NULL if there is no server.
12436 if (cr
->CRActiveQuestion
)
12438 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
12440 if (qptr
->qDNSServer
== ptr
)
12442 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) poining to DNSServer Address %#a"
12443 " to be freed", CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
, &ptr
->addr
);
12444 qptr
->validDNSServers
= zeroOpaque64
;
12445 qptr
->qDNSServer
= mDNSNULL
;
12446 cr
->resrec
.rDNSServer
= mDNSNULL
;
12450 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
12451 " resetting to question's DNSServer Address %#a", CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
),
12452 qptr
->InterfaceID
, &ptr
->addr
, (qptr
->qDNSServer
? &qptr
->qDNSServer
->addr
: mDNSNULL
));
12453 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
12458 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
12459 cr
->resrec
.name
, &cr
->resrec
.rDNSServer
->addr
, &ptr
->addr
);
12460 cr
->resrec
.rDNSServer
= mDNSNULL
;
12463 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNStrue
);
12467 debugf("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
);
12468 mDNSPlatformMemFree(ptr
);
12469 NumUnicastDNSServers
--;
12473 (*p
)->flags
&= ~DNSServer_FlagNew
;
12478 // 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).
12479 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
12480 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
12481 // 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.
12482 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
12485 FORALL_CACHERECORDS(slot
, cg
, cr
)
12487 if (!cr
->resrec
.InterfaceID
)
12489 mDNS_PurgeCacheResourceRecord(m
, cr
);
12493 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
12494 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
12496 // Force anything that needs to get zone data to get that information again
12497 RestartRecordGetZoneData(m
);
12500 // Did our FQDN change?
12501 if (!SameDomainName(&fqdn
, &m
->FQDN
))
12503 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
12505 AssignDomainName(&m
->FQDN
, &fqdn
);
12509 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
12510 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
12516 // handle router and primary interface changes
12517 v4
= v6
= r
= zeroAddr
;
12518 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
12520 if (mDNSPlatformGetPrimaryInterface(m
, &v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
12522 mDNS_SetPrimaryInterfaceInfo(m
,
12523 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
12524 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
12525 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
12529 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
12530 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
12533 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers
);
12534 return mStatus_NoError
;
12537 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
12539 m
->mDNSPlatformStatus
= result
;
12540 if (m
->MainCallback
)
12543 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12544 m
->MainCallback(m
, mStatus_NoError
);
12545 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12550 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
12552 m
->CurrentRecord
= start
;
12553 while (m
->CurrentRecord
)
12555 AuthRecord
*rr
= m
->CurrentRecord
;
12556 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
12557 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
12558 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
12559 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
12560 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
12561 else if (rr
->AnnounceCount
> 1)
12563 rr
->AnnounceCount
= 1;
12564 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
12566 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
12567 // new records could have been added to the end of the list as a result of that call.
12568 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
12569 m
->CurrentRecord
= rr
->next
;
12573 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
12575 NetworkInterfaceInfo
*intf
;
12580 LogInfo("mDNS_StartExit");
12581 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
12583 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0, 0);
12585 #if APPLE_OSX_mDNSResponder
12587 CHECK_WCF_FUNCTION(WCFConnectionDealloc
)
12589 if (m
->WCF
) WCFConnectionDealloc((WCFConnection
*)m
->WCF
);
12594 #ifndef UNICAST_DISABLED
12598 // Don't need to do SleepRecordRegistrations() here
12599 // because we deregister all records and services later in this routine
12600 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
12602 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
12603 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
12604 // and we may crash because the list still contains dangling pointers.
12605 for (s
= SearchList
; s
; s
= s
->next
)
12606 while (s
->AuthRecs
)
12608 ARListElem
*dereg
= s
->AuthRecs
;
12609 s
->AuthRecs
= s
->AuthRecs
->next
;
12610 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
12615 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12616 if (intf
->Advertise
)
12617 DeadvertiseInterface(m
, intf
);
12619 // Shut down all our active NAT Traversals
12620 while (m
->NATTraversals
)
12622 NATTraversalInfo
*t
= m
->NATTraversals
;
12623 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
12625 // After stopping the NAT Traversal, we zero out the fields.
12626 // This has particularly important implications for our AutoTunnel records --
12627 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
12628 // handlers to just turn around and attempt to re-register those same records.
12629 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
12631 t
->ExternalAddress
= zerov4Addr
;
12632 t
->ExternalPort
= zeroIPPort
;
12633 t
->RequestedPort
= zeroIPPort
;
12635 t
->Result
= mStatus_NoError
;
12638 // Make sure there are nothing but deregistering records remaining in the list
12639 if (m
->CurrentRecord
)
12640 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
12642 // We're in the process of shutting down, so queries, etc. are no longer available.
12643 // Consequently, determining certain information, e.g. the uDNS update server's IP
12644 // address, will not be possible. The records on the main list are more likely to
12645 // already contain such information, so we deregister the duplicate records first.
12646 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
12647 DeregLoop(m
, m
->DuplicateRecords
);
12648 LogInfo("mDNS_StartExit: Deregistering resource records");
12649 DeregLoop(m
, m
->ResourceRecords
);
12651 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
12652 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
12653 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
12655 m
->NextScheduledResponse
= m
->timenow
;
12656 m
->SuppressSending
= 0;
12659 if (m
->ResourceRecords
) LogInfo("mDNS_StartExit: Sending final record deregistrations");
12660 else LogInfo("mDNS_StartExit: No deregistering records remain");
12662 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
12663 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
12665 // If any deregistering records remain, send their deregistration announcements before we exit
12666 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
12670 LogInfo("mDNS_StartExit: done");
12673 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
12675 mDNSu32 rrcache_active
= 0;
12676 mDNSu32 rrcache_totalused
= 0;
12680 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
12681 mDNSPlatformClose(m
);
12683 rrcache_totalused
= m
->rrcache_totalused
;
12684 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
12686 while (m
->rrcache_hash
[slot
])
12688 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
12689 while (cg
->members
)
12691 CacheRecord
*cr
= cg
->members
;
12692 cg
->members
= cg
->members
->next
;
12693 if (cr
->CRActiveQuestion
) rrcache_active
++;
12694 ReleaseCacheRecord(m
, cr
);
12696 cg
->rrcache_tail
= &cg
->members
;
12697 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
12700 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
12701 if (rrcache_active
!= m
->rrcache_active
)
12702 LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active
, m
->rrcache_active
);
12704 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
12705 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
12707 LogInfo("mDNS_FinalExit: done");