1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2015 Apple 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 utility routines
27 #include "uDNS.h" // Defines entry points into unicast-specific routines
30 #include "anonymous.h"
32 // Disable certain benign warnings with Microsoft compilers
33 #if (defined(_MSC_VER))
34 // Disable "conditional expression is constant" warning for debug macros.
35 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
36 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
37 #pragma warning(disable:4127)
39 // Disable "assignment within conditional expression".
40 // Other compilers understand the convention that if you place the assignment expression within an extra pair
41 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
42 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
43 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
44 #pragma warning(disable:4706)
47 #include "dns_sd.h" // for kDNSServiceFlags* definitions
49 #if APPLE_OSX_mDNSResponder
50 #include <WebFilterDNS/WebFilterDNS.h>
52 // Delay in seconds before disabling multicast after there are no active queries or registrations.
53 #define BONJOUR_DISABLE_DELAY 60
56 WCFConnection
*WCFConnectionNew(void) __attribute__((weak_import
));
57 void WCFConnectionDealloc(WCFConnection
* c
) __attribute__((weak_import
));
59 // Do we really need to define a macro for "if"?
60 #define CHECK_WCF_FUNCTION(X) if (X)
66 #endif // APPLE_OSX_mDNSResponder
68 #if TARGET_OS_EMBEDDED
72 // Forward declarations
73 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
);
74 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
);
75 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
);
76 mDNSlocal mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
77 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
78 mDNSlocal
void mDNS_PurgeForQuestion(mDNS
*const m
, DNSQuestion
*q
);
79 mDNSlocal
void CheckForDNSSECRecords(mDNS
*const m
, DNSQuestion
*q
);
80 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
);
81 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
,
82 mDNSu32
*seq
, mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
);
84 mDNSlocal
void AdvertiseAllInterfaceRecords(mDNS
*const m
);
85 mDNSlocal
void DeadvertiseAllInterfaceRecords(mDNS
*const m
);
86 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
);
87 mDNSlocal
void mDNSParseNSEC3Records(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
88 const mDNSInterfaceID InterfaceID
, CacheRecord
**NSEC3Records
);
89 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
);
92 // ***************************************************************************
93 #if COMPILER_LIKES_PRAGMA_MARK
94 #pragma mark - Program Constants
97 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
102 // Any records bigger than this are considered 'large' records
103 #define SmallRecordLimit 1024
105 #define kMaxUpdateCredits 10
106 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
108 // define special NR_AnswerTo values
109 #define NR_AnswerMulticast (mDNSu8*)~0
110 #define NR_AnswerUnicast (mDNSu8*)~1
112 // The code (see SendQueries() and BuildQuestion()) needs to have the
113 // RequestUnicast value set to a value one greater than the number of times you want the query
114 // sent with the "request unicast response" (QU) bit set.
115 #define SET_QU_IN_FIRST_QUERY 2
116 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
118 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
119 #define DARK_WAKE_DELAY_SLEEP 5
120 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
122 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
123 #define MAX_CONFLICT_PROCESSING_DELAYS 3
125 // RFC 6762 defines Passive Observation Of Failures (POOF)
127 // A host observes the multicast queries issued by the other hosts on
128 // the network. One of the major benefits of also sending responses
129 // using multicast is that it allows all hosts to see the responses
130 // (or lack thereof) to those queries.
132 // If a host sees queries, for which a record in its cache would be
133 // expected to be given as an answer in a multicast response, but no
134 // such answer is seen, then the host may take this as an indication
135 // that the record may no longer be valid.
137 // After seeing two or more of these queries, and seeing no multicast
138 // response containing the expected answer within ten seconds, then even
139 // though its TTL may indicate that it is not yet due to expire, that
140 // record SHOULD be flushed from the cache.
142 // <https://tools.ietf.org/html/rfc6762#section-10.5>
144 #define POOF_ENABLED 1
146 mDNSexport
const char *const mDNS_DomainTypeNames
[] =
148 "b._dns-sd._udp.", // Browse
149 "db._dns-sd._udp.", // Default Browse
150 "lb._dns-sd._udp.", // Automatic Browse
151 "r._dns-sd._udp.", // Registration
152 "dr._dns-sd._udp." // Default Registration
155 #ifdef UNICAST_DISABLED
156 #define uDNS_IsActiveQuery(q, u) mDNSfalse
159 // ***************************************************************************
160 #if COMPILER_LIKES_PRAGMA_MARK
162 #pragma mark - General Utility Functions
165 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
166 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
167 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
168 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
169 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
170 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
171 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
172 (rr)->resrec.rrtype == kDNSType_CNAME || \
173 (rr)->resrec.rrtype == kDNSType_PTR))
175 mDNSlocal
void SetNextQueryStopTime(mDNS
*const m
, const DNSQuestion
*const q
)
179 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
180 m
->NextScheduledStopTime
= q
->StopTime
;
183 mDNSexport
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
187 if (ActiveQuestion(q
))
189 // Depending on whether this is a multicast or unicast question we want to set either:
190 // m->NextScheduledQuery = NextQSendTime(q) or
191 // m->NextuDNSEvent = NextQSendTime(q)
192 mDNSs32
*const timer
= mDNSOpaque16IsZero(q
->TargetQID
) ? &m
->NextScheduledQuery
: &m
->NextuDNSEvent
;
193 if (*timer
- NextQSendTime(q
) > 0)
194 *timer
= NextQSendTime(q
);
198 mDNSlocal
void ReleaseAuthEntity(AuthHash
*r
, AuthEntity
*e
)
200 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
202 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
204 e
->next
= r
->rrauth_free
;
206 r
->rrauth_totalused
--;
209 mDNSlocal
void ReleaseAuthGroup(AuthHash
*r
, AuthGroup
**cp
)
211 AuthEntity
*e
= (AuthEntity
*)(*cp
);
212 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp
)->name
->c
);
213 if ((*cp
)->rrauth_tail
!= &(*cp
)->members
)
214 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
215 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
216 (*cp
)->name
= mDNSNULL
;
217 *cp
= (*cp
)->next
; // Cut record from list
218 ReleaseAuthEntity(r
, e
);
221 mDNSlocal AuthEntity
*GetAuthEntity(AuthHash
*r
, const AuthGroup
*const PreserveAG
)
223 AuthEntity
*e
= mDNSNULL
;
225 if (r
->rrauth_lock
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
230 // We allocate just one AuthEntity at a time because we need to be able
231 // free them all individually which normally happens when we parse /etc/hosts into
232 // AuthHash where we add the "new" entries and discard (free) the already added
233 // entries. If we allocate as chunks, we can't free them individually.
234 AuthEntity
*storage
= mDNSPlatformMemAllocate(sizeof(AuthEntity
));
235 storage
->next
= mDNSNULL
;
236 r
->rrauth_free
= storage
;
239 // If we still have no free records, recycle all the records we can.
240 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
243 mDNSu32 oldtotalused
= r
->rrauth_totalused
;
245 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
247 AuthGroup
**cp
= &r
->rrauth_hash
[slot
];
250 if ((*cp
)->members
|| (*cp
)==PreserveAG
) cp
=&(*cp
)->next
;
251 else ReleaseAuthGroup(r
, cp
);
254 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
255 oldtotalused
- r
->rrauth_totalused
, oldtotalused
, r
->rrauth_totalused
);
258 if (r
->rrauth_free
) // If there are records in the free list, take one
261 r
->rrauth_free
= e
->next
;
262 if (++r
->rrauth_totalused
>= r
->rrauth_report
)
264 LogInfo("RR Auth now using %ld objects", r
->rrauth_totalused
);
265 if (r
->rrauth_report
< 100) r
->rrauth_report
+= 10;
266 else if (r
->rrauth_report
< 1000) r
->rrauth_report
+= 100;
267 else r
->rrauth_report
+= 1000;
269 mDNSPlatformMemZero(e
, sizeof(*e
));
277 mDNSexport AuthGroup
*AuthGroupForName(AuthHash
*r
, const mDNSu32 slot
, const mDNSu32 namehash
, const domainname
*const name
)
280 for (ag
= r
->rrauth_hash
[slot
]; ag
; ag
=ag
->next
)
281 if (ag
->namehash
== namehash
&& SameDomainName(ag
->name
, name
))
286 mDNSexport AuthGroup
*AuthGroupForRecord(AuthHash
*r
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
288 return(AuthGroupForName(r
, slot
, rr
->namehash
, rr
->name
));
291 mDNSlocal AuthGroup
*GetAuthGroup(AuthHash
*r
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
293 mDNSu16 namelen
= DomainNameLength(rr
->name
);
294 AuthGroup
*ag
= (AuthGroup
*)GetAuthEntity(r
, mDNSNULL
);
295 if (!ag
) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
296 ag
->next
= r
->rrauth_hash
[slot
];
297 ag
->namehash
= rr
->namehash
;
298 ag
->members
= mDNSNULL
;
299 ag
->rrauth_tail
= &ag
->members
;
300 ag
->NewLocalOnlyRecords
= mDNSNULL
;
301 if (namelen
> sizeof(ag
->namestorage
))
302 ag
->name
= mDNSPlatformMemAllocate(namelen
);
304 ag
->name
= (domainname
*)ag
->namestorage
;
307 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
308 ReleaseAuthEntity(r
, (AuthEntity
*)ag
);
311 AssignDomainName(ag
->name
, rr
->name
);
313 if (AuthGroupForRecord(r
, slot
, rr
)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr
->name
->c
);
314 r
->rrauth_hash
[slot
] = ag
;
315 if (AuthGroupForRecord(r
, slot
, rr
) != ag
) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr
->name
->c
);
320 // Returns the AuthGroup in which the AuthRecord was inserted
321 mDNSexport AuthGroup
*InsertAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
325 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
326 ag
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
327 if (!ag
) ag
= GetAuthGroup(r
, slot
, &rr
->resrec
); // If we don't have a AuthGroup for this name, make one now
330 *(ag
->rrauth_tail
) = rr
; // Append this record to tail of cache slot list
331 ag
->rrauth_tail
= &(rr
->next
); // Advance tail pointer
336 mDNSexport AuthGroup
*RemoveAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
340 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
342 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
343 if (!a
) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m
, rr
)); return mDNSNULL
; }
351 // We don't break here, so that we can set the tail below without tracking "prev" pointers
353 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m
, rr
));
354 *rp
= (*rp
)->next
; // Cut record from list
357 // TBD: If there are no more members, release authgroup ?
362 mDNSexport CacheGroup
*CacheGroupForName(const mDNS
*const m
, const mDNSu32 slot
, const mDNSu32 namehash
, const domainname
*const name
)
365 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
366 if (cg
->namehash
== namehash
&& SameDomainName(cg
->name
, name
))
371 mDNSlocal CacheGroup
*CacheGroupForRecord(const mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
373 return(CacheGroupForName(m
, slot
, rr
->namehash
, rr
->name
));
376 mDNSexport mDNSBool
mDNS_AddressIsLocalSubnet(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, const mDNSAddr
*addr
)
378 NetworkInterfaceInfo
*intf
;
380 if (addr
->type
== mDNSAddrType_IPv4
)
382 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
383 if (mDNSv4AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
384 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
385 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
386 if (((intf
->ip
.ip
.v4
.NotAnInteger
^ addr
->ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0)
390 if (addr
->type
== mDNSAddrType_IPv6
)
392 if (mDNSv6AddressIsLinkLocal(&addr
->ip
.v6
)) return(mDNStrue
);
393 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
394 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
395 if ((((intf
->ip
.ip
.v6
.l
[0] ^ addr
->ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
396 (((intf
->ip
.ip
.v6
.l
[1] ^ addr
->ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
397 (((intf
->ip
.ip
.v6
.l
[2] ^ addr
->ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
398 (((intf
->ip
.ip
.v6
.l
[3] ^ addr
->ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0))
405 mDNSlocal NetworkInterfaceInfo
*FirstInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
407 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
408 while (intf
&& intf
->InterfaceID
!= InterfaceID
) intf
= intf
->next
;
412 mDNSlocal NetworkInterfaceInfo
*FirstIPv4LLInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
414 NetworkInterfaceInfo
*intf
;
419 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
420 // we still want to find the first IPv4 Link-Local interface
421 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
423 if (intf
->InterfaceID
== InterfaceID
&&
424 intf
->ip
.type
== mDNSAddrType_IPv4
&& mDNSv4AddressIsLinkLocal(&intf
->ip
.ip
.v4
))
426 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf
->ip
.ip
.v4
);
433 mDNSexport
char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
435 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
436 return(intf
? intf
->ifname
: mDNSNULL
);
439 // Caller should hold the lock
440 mDNSlocal
void GenerateNegativeResponse(mDNS
*const m
, mDNSInterfaceID InterfaceID
, QC_result qc
)
443 if (!m
->CurrentQuestion
) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
444 q
= m
->CurrentQuestion
;
445 LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
447 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, InterfaceID
, mDNSNULL
);
449 // We need to force the response through in the following cases
451 // a) SuppressUnusable questions that are suppressed
452 // b) Append search domains and retry the question
454 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
455 // through we use "QC_forceresponse".
456 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, qc
);
457 if (m
->CurrentQuestion
== q
) { q
->ThisQInterval
= 0; } // Deactivate this question
458 // Don't touch the question after this
459 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
462 mDNSexport
void AnswerQuestionByFollowingCNAME(mDNS
*const m
, DNSQuestion
*q
, ResourceRecord
*rr
)
464 const mDNSBool selfref
= SameDomainName(&q
->qname
, &rr
->rdata
->u
.name
);
465 if (q
->CNAMEReferrals
>= 10 || selfref
)
467 LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
468 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CNAMEReferrals
, selfref
? " (Self-Referential)" : "", RRDisplayString(m
, rr
));
472 const mDNSu32 c
= q
->CNAMEReferrals
+ 1; // Stash a copy of the new q->CNAMEReferrals value
473 UDPSocket
*sock
= q
->LocalSocket
;
474 mDNSOpaque16 id
= q
->TargetQID
;
475 #if TARGET_OS_EMBEDDED
479 q
->LocalSocket
= mDNSNULL
;
481 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
482 // themselves. Without that check we can get into a case where we have two duplicate questions,
483 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
484 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
485 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
486 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
487 // for either of them. This is not a problem for CNAME loops of two or more records because in
488 // those cases the newly re-appended question A has a different target name and therefore cannot be
489 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
491 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
492 // and track CNAMEs coming and going, we should really create a subordinate query here,
493 // which we would subsequently cancel and retract if the CNAME referral record were removed.
494 // In reality this is such a corner case we'll ignore it until someone actually needs it.
496 LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
497 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CNAMEReferrals
, RRDisplayString(m
, rr
));
499 #if TARGET_OS_EMBEDDED
500 if ((q
->CNAMEReferrals
== 0) && !q
->metrics
.originalQName
)
505 qNameLen
= DomainNameLength(&q
->qname
);
506 if ((qNameLen
> 0) && (qNameLen
<= MAX_DOMAIN_NAME
))
508 qName
= mDNSPlatformMemAllocate(qNameLen
);
511 mDNSPlatformMemCopy(qName
->c
, q
->qname
.c
, qNameLen
);
512 q
->metrics
.originalQName
= qName
;
516 metrics
= q
->metrics
;
517 mDNSPlatformMemZero(&q
->metrics
, sizeof(q
->metrics
));
519 mDNS_StopQuery_internal(m
, q
); // Stop old query
520 AssignDomainName(&q
->qname
, &rr
->rdata
->u
.name
); // Update qname
521 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
522 // If a unicast query results in a CNAME that points to a .local, we need to re-try
523 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
524 // to try this as unicast query even though it is a .local name
525 if (!mDNSOpaque16IsZero(q
->TargetQID
) && IsLocalDomain(&q
->qname
))
527 LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
528 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), RRDisplayString(m
, rr
));
529 q
->InterfaceID
= mDNSInterface_Unicast
;
531 mDNS_StartQuery_internal(m
, q
); // start new query
532 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
533 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
534 q
->CNAMEReferrals
= c
;
535 #if TARGET_OS_EMBEDDED
536 q
->metrics
= metrics
;
540 // If our new query is a duplicate, then it can't have a socket of its own, so we have to close the one we saved.
541 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
544 // Transplant the old socket into the new question, and copy the query ID across too.
545 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
546 q
->LocalSocket
= sock
;
555 #include <unicode/uidna.h>
557 // #define DEBUG_PUNYCODE 1
559 mDNSlocal mDNSu8
*PunycodeConvert(const mDNSu8
*const src
, mDNSu8
*const dst
, const mDNSu8
*const end
)
561 UErrorCode errorCode
= U_ZERO_ERROR
;
562 UIDNAInfo info
= UIDNA_INFO_INITIALIZER
;
563 UIDNA
*uts46
= uidna_openUTS46(UIDNA_USE_STD3_RULES
|UIDNA_NONTRANSITIONAL_TO_UNICODE
, &errorCode
);
564 int32_t len
= uidna_nameToASCII_UTF8(uts46
, (const char *)src
+1, src
[0], (char *)dst
+1, end
-(dst
+1), &info
, &errorCode
);
567 if (errorCode
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src
, errorCode
);
568 if (info
.errors
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src
, info
.errors
);
569 if (len
> MAX_DOMAIN_LABEL
) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src
, len
);
571 if (errorCode
|| info
.errors
|| len
> MAX_DOMAIN_LABEL
) return mDNSNULL
;
573 return(dst
+ 1 + len
);
576 mDNSlocal mDNSBool
IsHighASCIILabel(const mDNSu8
*d
)
579 for (i
=1; i
<=d
[0]; i
++) if (d
[i
] & 0x80) return mDNStrue
;
583 mDNSlocal
const mDNSu8
*FindLastHighASCIILabel(const domainname
*const d
)
585 const mDNSu8
*ptr
= d
->c
;
586 const mDNSu8
*ans
= mDNSNULL
;
589 const mDNSu8
*const next
= ptr
+ 1 + ptr
[0];
590 if (ptr
[0] > MAX_DOMAIN_LABEL
|| next
>= d
->c
+ MAX_DOMAIN_NAME
) return mDNSNULL
;
591 if (IsHighASCIILabel(ptr
)) ans
= ptr
;
597 mDNSlocal mDNSBool
PerformNextPunycodeConversion(const DNSQuestion
*const q
, domainname
*const newname
)
599 const mDNSu8
*h
= FindLastHighASCIILabel(&q
->qname
);
601 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q
->qname
.c
, DNSTypeName(q
->qtype
), h
);
603 if (!h
) return mDNSfalse
; // There are no high-ascii labels to convert
605 mDNSu8
*const dst
= PunycodeConvert(h
, newname
->c
+ (h
- q
->qname
.c
), newname
->c
+ MAX_DOMAIN_NAME
);
607 return mDNSfalse
; // The label was not convertible to Punycode
610 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
611 const mDNSu8
*const src
= h
+ 1 + h
[0];
612 const mDNSu8 remainder
= DomainNameLength((domainname
*)src
);
613 if (dst
+ remainder
> newname
->c
+ MAX_DOMAIN_NAME
) return mDNSfalse
; // Name too long -- cannot be converted to Punycode
615 mDNSPlatformMemCopy(newname
->c
, q
->qname
.c
, h
- q
->qname
.c
); // Fill in the leading part
616 mDNSPlatformMemCopy(dst
, src
, remainder
); // Fill in the trailing part
618 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q
->qname
.c
, newname
->c
);
626 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
627 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
628 mDNSlocal
void AnswerLocalQuestionWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
630 DNSQuestion
*q
= m
->CurrentQuestion
;
631 mDNSBool followcname
;
635 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m
, rr
));
639 followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
641 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
642 if (!(rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
))
644 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
645 AddRecord
? "Add" : "Rmv", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
649 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
650 if (AddRecord
) rr
->AnsweredLocalQ
= mDNStrue
;
651 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
652 if (q
->QuestionCallback
&& !q
->NoAnswer
)
654 q
->CurrentAnswers
+= AddRecord
? 1 : -1;
655 if (UniqueLocalOnlyRecord(rr
))
657 if (!followcname
|| q
->ReturnIntermed
)
659 // Don't send this packet on the wire as we answered from /etc/hosts
660 q
->ThisQInterval
= 0;
661 q
->LOAddressAnswers
+= AddRecord
? 1 : -1;
662 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
664 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
665 // The callback above could have caused the question to stop. Detect that
666 // using m->CurrentQuestion
667 if (followcname
&& m
->CurrentQuestion
== q
)
668 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
673 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
676 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
679 mDNSlocal
void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
681 if (m
->CurrentQuestion
)
682 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
683 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
684 m
->CurrentQuestion
= m
->Questions
;
685 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
688 DNSQuestion
*q
= m
->CurrentQuestion
;
690 answered
= ResourceRecordAnswersQuestion(&rr
->resrec
, q
);
692 answered
= LocalOnlyRecordAnswersQuestion(rr
, q
);
694 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, AddRecord
); // MUST NOT dereference q again
695 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
696 m
->CurrentQuestion
= q
->next
;
698 m
->CurrentQuestion
= mDNSNULL
;
701 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
702 // delivers the appropriate add/remove events to listening questions:
703 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
704 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
705 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
706 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
707 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
709 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
710 // and by mDNS_Deregister_internal()
712 mDNSlocal
void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
714 if (m
->CurrentQuestion
)
715 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
716 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
718 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
719 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
722 DNSQuestion
*q
= m
->CurrentQuestion
;
723 // We are called with both LocalOnly/P2P record or a regular AuthRecord
725 answered
= ResourceRecordAnswersQuestion(&rr
->resrec
, q
);
727 answered
= LocalOnlyRecordAnswersQuestion(rr
, q
);
729 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, AddRecord
); // MUST NOT dereference q again
730 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
731 m
->CurrentQuestion
= q
->next
;
734 m
->CurrentQuestion
= mDNSNULL
;
736 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
737 if (rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
)
738 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m
, rr
, AddRecord
);
742 // ***************************************************************************
743 #if COMPILER_LIKES_PRAGMA_MARK
745 #pragma mark - Resource Record Utility Functions
748 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
750 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask) && \
751 ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
752 ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
753 ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)) )
755 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
756 (ResourceRecordIsValidAnswer(RR) && \
757 ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
759 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
760 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
762 // See RFC 6762: "8.3 Announcing"
763 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
764 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
765 #define InitialAnnounceCount ((mDNSu8)4)
767 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
768 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
769 // and then if the machine fails to wake, 3 goodbye packets).
770 #define GoodbyeCount ((mDNSu8)3)
771 #define WakeupCount ((mDNSu8)18)
772 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
774 // Number of wakeups we send if WakeOnResolve is set in the question
775 #define InitialWakeOnResolveCount ((mDNSu8)3)
777 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
778 // This means that because the announce interval is doubled after sending the first packet, the first
779 // observed on-the-wire inter-packet interval between announcements is actually one second.
780 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
781 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
782 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
783 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
785 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
786 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
787 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
789 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
790 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
791 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
792 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
794 // Adjustment factor to avoid race condition (used for unicast cache entries) :
795 // Suppose real record has TTL of 3600, and our local caching server has held it for 3500 seconds, so it returns an aged TTL of 100.
796 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
797 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
798 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
799 // We adjust the 100 second TTL to 127. This means that when we do our 80% query at 102 seconds,
800 // the cached copy at our local caching server will already have expired, so the server will be forced
801 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
803 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
804 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
806 #define MaxUnansweredQueries 4
808 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
809 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
810 // TTL and rdata may differ.
811 // This is used for cache flush management:
812 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
813 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
815 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
817 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
819 mDNSlocal mDNSBool
SameResourceRecordNameClassInterface(const AuthRecord
*const r1
, const AuthRecord
*const r2
)
821 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
822 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
823 if (r1
->resrec
.InterfaceID
&&
824 r2
->resrec
.InterfaceID
&&
825 r1
->resrec
.InterfaceID
!= r2
->resrec
.InterfaceID
) return(mDNSfalse
);
827 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
&&
828 r1
->resrec
.namehash
== r2
->resrec
.namehash
&&
829 SameDomainName(r1
->resrec
.name
, r2
->resrec
.name
));
832 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
833 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
834 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
835 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
836 // so a response of any type should match, even if it is not actually the type the client plans to use.
838 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
839 // and require the rrtypes to match for the rdata to be considered potentially conflicting
840 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
842 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
843 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
844 if (pktrr
->resrec
.InterfaceID
&&
845 authrr
->resrec
.InterfaceID
&&
846 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
847 if (!(authrr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) || authrr
->WakeUp
.HMAC
.l
[0])
848 if (pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
849 if ((authrr
->resrec
.InterfaceID
== mDNSInterface_Any
) &&
850 !mDNSPlatformValidRecordForInterface(authrr
, pktrr
->resrec
.InterfaceID
)) return(mDNSfalse
);
852 pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&&
853 pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&&
854 SameDomainName(pktrr
->resrec
.name
, authrr
->resrec
.name
));
857 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
858 // This is the information that the requester believes to be correct.
859 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
860 // This is the information that we believe to be correct.
861 // We've already determined that we plan to give this answer on this interface
862 // (either the record is non-specific, or it is specific to this interface)
863 // so now we just need to check the name, type, class, rdata and TTL.
864 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
866 // If RR signature is different, or data is different, then don't suppress our answer
867 if (!IdenticalResourceRecord(&ka
->resrec
, &rr
->resrec
)) return(mDNSfalse
);
869 // If the requester's indicated TTL is less than half the real TTL,
870 // we need to give our answer before the requester's copy expires.
871 // If the requester's indicated TTL is at least half the real TTL,
872 // then we can suppress our answer this time.
873 // If the requester's indicated TTL is greater than the TTL we believe,
874 // then that's okay, and we don't need to do anything about it.
875 // (If two responders on the network are offering the same information,
876 // that's okay, and if they are offering the information with different TTLs,
877 // the one offering the lower TTL should defer to the one offering the higher TTL.)
878 return (mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
881 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
883 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
885 if ((rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
> mDNSPlatformOneSecond
* 10)
887 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr
->ProbeCount
, (rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
, ARDisplayString(m
, rr
));
888 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m
->SuppressProbes
, m
->timenow
, m
->SuppressProbes
- m
->timenow
);
890 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
891 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
892 // Some defensive code:
893 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
894 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
895 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
896 if (m
->NextScheduledProbe
- m
->timenow
< 0)
897 m
->NextScheduledProbe
= m
->timenow
;
899 else if (rr
->AnnounceCount
&& (ResourceRecordIsValidAnswer(rr
) || rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
))
901 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
902 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
906 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
908 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
909 rr
->ThisAPInterval
= rr
->AddressProxy
.type
? mDNSPlatformOneSecond
: DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
911 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
912 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
913 // records that are going to probe, then we delay its first announcement so that it will
914 // go out synchronized with the first announcement for the other records that *are* probing.
915 // This is a minor performance tweak that helps keep groups of related records synchronized together.
916 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
917 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
918 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
919 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
920 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
924 // If we have no probe suppression time set, or it is in the past, set it now
925 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
927 // To allow us to aggregate probes when a group of services are registered together,
928 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
929 // This means the common-case behaviour is:
930 // randomized wait; probe
931 // 1/4 second wait; probe
932 // 1/4 second wait; probe
933 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
934 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
936 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
937 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
938 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledProbe
);
939 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
940 m
->SuppressProbes
= m
->timenow
;
942 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
943 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
944 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledQuery
);
945 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
946 m
->SuppressProbes
= m
->timenow
;
948 // except... don't expect to be able to send before the m->SuppressSending timer fires
949 if (m
->SuppressSending
&& m
->SuppressProbes
- m
->SuppressSending
< 0)
950 m
->SuppressProbes
= NonZeroTime(m
->SuppressSending
);
952 if (m
->SuppressProbes
- m
->timenow
> mDNSPlatformOneSecond
* 8)
954 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
955 m
->SuppressProbes
- m
->timenow
,
956 m
->NextScheduledProbe
- m
->timenow
,
957 m
->NextScheduledQuery
- m
->timenow
,
959 m
->SuppressSending
- m
->timenow
);
960 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
963 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
965 // Skip kDNSRecordTypeKnownUnique records here and set their LastAPTime in the "else" block below so that they get announced immediately,
966 // otherwise, their announcement would be delayed until all other record probes complete.
967 else if ((rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
) && m
->SuppressProbes
&& m
->SuppressProbes
- m
->timenow
>= 0)
968 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
+ DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
970 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
972 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
973 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
974 // After three probes one second apart with no answer, we conclude the client is now sleeping
975 // and we can begin broadcasting our announcements to take over ownership of that IP address.
976 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
977 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
978 if (rr
->AddressProxy
.type
)
979 rr
->LastAPTime
= m
->timenow
;
981 // Set LastMCTime to now, to inhibit multicast responses
982 // (no need to send additional multicast responses when we're announcing anyway)
983 rr
->LastMCTime
= m
->timenow
;
984 rr
->LastMCInterface
= mDNSInterfaceMark
;
986 SetNextAnnounceProbeTime(m
, rr
);
989 mDNSlocal
const domainname
*SetUnicastTargetToHostName(mDNS
*const m
, AuthRecord
*rr
)
991 const domainname
*target
;
994 // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
995 // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
996 // with the port number in our advertised SRV record automatically tracking the external mapped port.
997 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName_internal(m
, rr
->resrec
.name
);
998 if (!AuthInfo
|| !AuthInfo
->AutoTunnel
) rr
->AutoTarget
= Target_AutoHostAndNATMAP
;
1001 target
= GetServiceTarget(m
, rr
);
1002 if (!target
|| target
->c
[0] == 0)
1004 // defer registration until we've got a target
1005 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m
, rr
));
1006 rr
->state
= regState_NoTarget
;
1011 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target
->c
, ARDisplayString(m
,rr
));
1016 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1017 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1018 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
1020 domainname
*const target
= GetRRDomainNameTarget(&rr
->resrec
);
1021 const domainname
*newname
= &m
->MulticastHostname
;
1023 if (!target
) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr
->resrec
.rrtype
));
1025 if (!(rr
->ForceMCast
|| rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
|| IsLocalDomain(&rr
->namestorage
)))
1027 const domainname
*const n
= SetUnicastTargetToHostName(m
, rr
);
1029 else { if (target
) target
->c
[0] = 0; SetNewRData(&rr
->resrec
, mDNSNULL
, 0); return; }
1032 if (target
&& SameDomainName(target
, newname
))
1033 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
->c
, target
->c
);
1035 if (target
&& !SameDomainName(target
, newname
))
1037 AssignDomainName(target
, newname
);
1038 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
1040 // If we're in the middle of probing this record, we need to start again,
1041 // because changing its rdata may change the outcome of the tie-breaker.
1042 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1043 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1045 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1046 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1047 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1048 if (rr
->RequireGoodbye
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
1049 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1050 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1052 rr
->AnnounceCount
= InitialAnnounceCount
;
1053 rr
->RequireGoodbye
= mDNSfalse
;
1054 rr
->ProbeRestartCount
= 0;
1055 InitializeLastAPTime(m
, rr
);
1059 mDNSlocal
void AcknowledgeRecord(mDNS
*const m
, AuthRecord
*const rr
)
1061 if (rr
->RecordCallback
)
1063 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1064 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1065 rr
->Acknowledged
= mDNStrue
;
1066 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1067 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
1068 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1072 mDNSexport
void ActivateUnicastRegistration(mDNS
*const m
, AuthRecord
*const rr
)
1074 // Make sure that we don't activate the SRV record and associated service records, if it is in
1075 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1076 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1077 // the target becomes available, the records will be reregistered.
1078 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
1080 AuthRecord
*srvRR
= mDNSNULL
;
1081 if (rr
->resrec
.rrtype
== kDNSType_PTR
)
1082 srvRR
= rr
->Additional1
;
1083 else if (rr
->resrec
.rrtype
== kDNSType_TXT
)
1084 srvRR
= rr
->DependentOn
;
1087 if (srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
1089 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
1093 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1094 ARDisplayString(m
, srvRR
), srvRR
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1095 rr
->state
= srvRR
->state
;
1100 if (rr
->state
== regState_NoTarget
)
1102 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m
, rr
));
1105 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1106 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1107 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1108 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1109 // 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.
1110 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1112 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m
, rr
), rr
->state
);
1113 rr
->state
= regState_DeregPending
;
1117 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m
, rr
), rr
->state
);
1118 rr
->state
= regState_Pending
;
1121 rr
->ProbeRestartCount
= 0;
1122 rr
->AnnounceCount
= 0;
1123 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1124 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1125 rr
->expire
= 0; // Forget about all the leases, start fresh
1126 rr
->uselease
= mDNStrue
;
1127 rr
->updateid
= zeroID
;
1128 rr
->SRVChanged
= mDNSfalse
;
1129 rr
->updateError
= mStatus_NoError
;
1130 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1131 // The records might already be registered with the server and hence could have NAT state.
1132 if (rr
->NATinfo
.clientContext
)
1134 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1135 rr
->NATinfo
.clientContext
= mDNSNULL
;
1137 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1138 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1139 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1140 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1143 // Two records qualify to be local duplicates if:
1144 // (a) the RecordTypes are the same, or
1145 // (b) one is Unique and the other Verified
1146 // (c) either is in the process of deregistering
1147 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1148 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1149 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1151 #define RecordIsLocalDuplicate(A,B) \
1152 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1154 mDNSlocal AuthRecord
*CheckAuthIdenticalRecord(AuthHash
*r
, AuthRecord
*rr
)
1158 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1160 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
1161 if (!a
) return mDNSNULL
;
1165 if (!RecordIsLocalDuplicate(rp
, rr
))
1169 if (rp
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1171 rp
->AnnounceCount
= 0;
1180 mDNSlocal mDNSBool
CheckAuthRecordConflict(AuthHash
*r
, AuthRecord
*rr
)
1183 const AuthRecord
*rp
;
1184 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1186 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
1187 if (!a
) return mDNSfalse
;
1191 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
1192 const AuthRecord
*s2
= rp
->RRSet
? rp
->RRSet
: rp
;
1193 if (s1
!= s2
&& SameResourceRecordSignature(rp
, rr
) && !IdenticalSameNameRecord(&rp
->resrec
, &rr
->resrec
))
1201 // checks to see if "rr" is already present
1202 mDNSlocal AuthRecord
*CheckAuthSameRecord(AuthHash
*r
, AuthRecord
*rr
)
1206 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1208 a
= AuthGroupForRecord(r
, slot
, &rr
->resrec
);
1209 if (!a
) return mDNSNULL
;
1224 mDNSlocal
void DecrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1226 if (RRLocalOnly(rr
))
1228 // A sanity check, this should be prevented in calling code.
1229 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1233 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.rrtype
== kDNSType_SRV
&& rr
->AutoTarget
== Target_AutoHost
)
1235 // If about to get rid of the last advertised service
1236 if (m
->AutoTargetServices
== 1)
1237 DeadvertiseAllInterfaceRecords(m
);
1239 m
->AutoTargetServices
--;
1240 LogInfo("DecrementAutoTargetServices: AutoTargetServices %d Record %s", m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1243 #if BONJOUR_ON_DEMAND
1244 if (!AuthRecord_uDNS(rr
))
1246 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1247 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
1248 m
->NumAllInterfaceRecords
--;
1249 LogInfo("DecrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1250 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1252 #endif // BONJOUR_ON_DEMAND
1255 mDNSlocal
void IncrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1257 mDNSBool enablingBonjour
= 0;
1259 if (RRLocalOnly(rr
))
1261 // A sanity check, this should be prevented in calling code.
1262 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1266 #if BONJOUR_ON_DEMAND
1267 if (!AuthRecord_uDNS(rr
))
1269 m
->NumAllInterfaceRecords
++;
1270 LogInfo("IncrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1271 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1272 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1274 m
->NextBonjourDisableTime
= 0;
1275 if (m
->BonjourEnabled
== 0)
1277 // Enable Bonjour immediately by scheduling network changed processing where
1278 // we will join the multicast group on each active interface.
1279 m
->BonjourEnabled
= 1;
1280 enablingBonjour
= 1;
1281 m
->NetworkChanged
= m
->timenow
;
1285 #endif // BONJOUR_ON_DEMAND
1287 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.rrtype
== kDNSType_SRV
&& rr
->AutoTarget
== Target_AutoHost
)
1289 m
->AutoTargetServices
++;
1290 LogInfo("IncrementAutoTargetServices: AutoTargetServices %d Record %s", m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1292 // If this is the first advertised service and we did not just enable Bonjour above, then
1293 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1294 // be advertised during the network changed processing scheduled above, so no need
1296 if ((m
->AutoTargetServices
== 1) && (enablingBonjour
== 0))
1297 AdvertiseAllInterfaceRecords(m
);
1301 mDNSlocal
void getKeepaliveRaddr(mDNS
*const m
, AuthRecord
*rr
, mDNSAddr
*raddr
)
1303 mDNSAddr laddr
= zeroAddr
;
1304 mDNSEthAddr eth
= zeroEthAddr
;
1305 mDNSIPPort lport
= zeroIPPort
;
1306 mDNSIPPort rport
= zeroIPPort
;
1307 mDNSu32 timeout
= 0;
1312 if (mDNS_KeepaliveRecord(&rr
->resrec
))
1314 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
1315 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
1317 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, raddr
, rport
.NotAnInteger
);
1323 // Exported so uDNS.c can call this
1324 mDNSexport mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
1326 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
1328 AuthRecord
**p
= &m
->ResourceRecords
;
1329 AuthRecord
**d
= &m
->DuplicateRecords
;
1331 if ((mDNSs32
)rr
->resrec
.rroriginalttl
<= 0)
1332 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr
->resrec
.rroriginalttl
, ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1334 if (!rr
->resrec
.RecordType
)
1335 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1337 if (m
->ShutdownTime
)
1338 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m
, rr
)); return(mStatus_ServiceNotRunning
); }
1340 if (m
->DivertMulticastAdvertisements
&& !AuthRecord_uDNS(rr
))
1342 mDNSInterfaceID previousID
= rr
->resrec
.InterfaceID
;
1343 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1345 rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
1346 rr
->ARType
= AuthRecordLocalOnly
;
1348 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
1350 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1351 if (intf
&& !intf
->Advertise
) { rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
; rr
->ARType
= AuthRecordLocalOnly
; }
1353 if (rr
->resrec
.InterfaceID
!= previousID
)
1354 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m
, rr
));
1357 if (RRLocalOnly(rr
))
1359 if (CheckAuthSameRecord(&m
->rrauth
, rr
))
1361 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1362 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1363 return(mStatus_AlreadyRegistered
);
1368 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1371 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1372 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1373 return(mStatus_AlreadyRegistered
);
1377 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
1380 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1381 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1382 return(mStatus_AlreadyRegistered
);
1385 if (rr
->DependentOn
)
1387 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1388 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1391 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1392 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1393 return(mStatus_Invalid
);
1395 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
)))
1397 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1398 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
1399 return(mStatus_Invalid
);
1403 rr
->next
= mDNSNULL
;
1405 // Field Group 1: The actual information pertaining to this resource record
1406 // Set up by client prior to call
1408 // Field Group 2: Persistent metadata for Authoritative Records
1409 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1410 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1411 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1412 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1413 // rr->Callback = already set in mDNS_SetupResourceRecord
1414 // rr->Context = already set in mDNS_SetupResourceRecord
1415 // rr->RecordType = already set in mDNS_SetupResourceRecord
1416 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1417 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1418 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1419 if (rr
->AutoTarget
&& target
) target
->c
[0] = 0;
1421 // Field Group 3: Transient state for Authoritative Records
1422 rr
->Acknowledged
= mDNSfalse
;
1423 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1424 rr
->ProbeRestartCount
= 0;
1425 rr
->AnnounceCount
= InitialAnnounceCount
;
1426 rr
->RequireGoodbye
= mDNSfalse
;
1427 rr
->AnsweredLocalQ
= mDNSfalse
;
1428 rr
->IncludeInProbe
= mDNSfalse
;
1429 rr
->ImmedUnicast
= mDNSfalse
;
1430 rr
->SendNSECNow
= mDNSNULL
;
1431 rr
->ImmedAnswer
= mDNSNULL
;
1432 rr
->ImmedAdditional
= mDNSNULL
;
1433 rr
->SendRNow
= mDNSNULL
;
1434 rr
->v4Requester
= zerov4Addr
;
1435 rr
->v6Requester
= zerov6Addr
;
1436 rr
->NextResponse
= mDNSNULL
;
1437 rr
->NR_AnswerTo
= mDNSNULL
;
1438 rr
->NR_AdditionalTo
= mDNSNULL
;
1439 if (!rr
->AutoTarget
) InitializeLastAPTime(m
, rr
);
1440 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1441 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1442 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1443 rr
->NewRData
= mDNSNULL
;
1444 rr
->newrdlength
= 0;
1445 rr
->UpdateCallback
= mDNSNULL
;
1446 rr
->UpdateCredits
= kMaxUpdateCredits
;
1447 rr
->NextUpdateCredit
= 0;
1448 rr
->UpdateBlocked
= 0;
1450 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1451 if (rr
->WakeUp
.HMAC
.l
[0] && !rr
->AddressProxy
.type
) rr
->AnnounceCount
= 2;
1453 // Field Group 4: Transient uDNS state for Authoritative Records
1454 rr
->state
= regState_Zero
;
1458 rr
->updateid
= zeroID
;
1459 rr
->updateIntID
= zeroOpaque64
;
1460 rr
->zone
= rr
->resrec
.name
;
1465 rr
->InFlightRData
= 0;
1466 rr
->InFlightRDLen
= 0;
1467 rr
->QueuedRData
= 0;
1468 rr
->QueuedRDLen
= 0;
1469 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1470 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1471 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1472 // times with different values if the external NAT port changes during the lifetime of the service registration.
1473 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1475 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1476 // rr->resrec.name->c = MUST be set by client
1477 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1478 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1479 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1480 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1482 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1483 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1484 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1485 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rr
->resrec
.rdlength
== 0) { rr
->resrec
.rdlength
= 1; rr
->resrec
.rdata
->u
.txt
.c
[0] = 0; }
1489 SetTargetToHostName(m
, rr
); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1490 #ifndef UNICAST_DISABLED
1491 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1492 // 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.
1493 if (rr
->state
== regState_NoTarget
)
1495 // Initialize the target so that we don't crash while logging etc.
1496 domainname
*tar
= GetRRDomainNameTarget(&rr
->resrec
);
1497 if (tar
) tar
->c
[0] = 0;
1498 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m
, rr
));
1504 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
1505 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
1508 if (!ValidateDomainName(rr
->resrec
.name
))
1509 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1511 // Don't do this until *after* we've set rr->resrec.rdlength
1512 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
1513 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1515 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
1516 rr
->resrec
.rdatahash
= target
? DomainNameHashValue(target
) : RDataHashValue(&rr
->resrec
);
1518 if (RRLocalOnly(rr
))
1520 // If this is supposed to be unique, make sure we don't have any name conflicts.
1521 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1522 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1523 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1524 // Hence, just bail out.
1525 // This comment is doesn’t make any sense. -- SC
1526 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1528 if (CheckAuthRecordConflict(&m
->rrauth
, rr
))
1530 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m
, rr
), rr
, rr
->resrec
.InterfaceID
);
1531 return mStatus_NameConflict
;
1536 // For uDNS records, we don't support duplicate checks at this time.
1537 #ifndef UNICAST_DISABLED
1538 if (AuthRecord_uDNS(rr
))
1540 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1541 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1542 // 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.
1543 // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1544 while (*p
) p
=&(*p
)->next
;
1546 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1548 rr
->ProbeRestartCount
= 0;
1549 rr
->AnnounceCount
= 0;
1550 if (rr
->state
!= regState_NoTarget
) ActivateUnicastRegistration(m
, rr
);
1551 return(mStatus_NoError
); // <--- Note: For unicast records, code currently bails out at this point
1555 // Now that we've finished building our new record, make sure it's not identical to one we already have
1556 if (RRLocalOnly(rr
))
1559 rr
->ProbeRestartCount
= 0;
1560 rr
->AnnounceCount
= 0;
1561 r
= CheckAuthIdenticalRecord(&m
->rrauth
, rr
);
1565 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1566 if (RecordIsLocalDuplicate(r
, rr
))
1568 if (r
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) r
->AnnounceCount
= 0;
1575 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m
,rr
));
1577 // If the previous copy of this record is already verified unique,
1578 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1579 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1580 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1581 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
1586 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m
,rr
));
1587 if (RRLocalOnly(rr
))
1590 ag
= InsertAuthRecord(m
, &m
->rrauth
, rr
);
1591 if (ag
&& !ag
->NewLocalOnlyRecords
)
1593 m
->NewLocalOnlyRecords
= mDNStrue
;
1594 ag
->NewLocalOnlyRecords
= rr
;
1596 // No probing for LocalOnly records; acknowledge them right away
1597 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1598 AcknowledgeRecord(m
, rr
);
1599 return(mStatus_NoError
);
1603 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1608 if (!AuthRecord_uDNS(rr
)) // This check is superfluous, given that for unicast records we (currently) bail out above
1610 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1611 IncrementAutoTargetServices(m
, rr
);
1613 // For records that are not going to probe, acknowledge them right away
1614 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
1615 AcknowledgeRecord(m
, rr
);
1617 // Adding a record may affect whether or not we should sleep
1618 mDNS_UpdateAllowSleep(m
);
1621 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1622 // This is used by the in-NIC proxy to send the keepalive packets.
1623 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
1626 // Set the record type to known unique to prevent probing keep alive records.
1627 // Also make sure we do not announce the keepalive records.
1628 rr
->resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
1629 rr
->AnnounceCount
= 0;
1630 getKeepaliveRaddr(m
, rr
, &raddr
);
1631 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1632 // asynchronous task to update the resource record
1633 mDNSPlatformGetRemoteMacAddr(m
, &raddr
);
1636 return(mStatus_NoError
);
1639 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
1641 m
->ProbeFailTime
= m
->timenow
;
1642 m
->NumFailedProbes
++;
1643 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1644 // If a bunch of hosts have all been configured with the same name, then they'll all
1645 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1646 // up to name-10. After that they'll start adding random increments in the range 1-100,
1647 // so they're more likely to branch out in the available namespace and settle on a set of
1648 // unique names quickly. If after five more tries the host is still conflicting, then we
1649 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1650 if (m
->NumFailedProbes
>= 15)
1652 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
1653 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1654 m
->NumFailedProbes
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1658 mDNSlocal
void CompleteRDataUpdate(mDNS
*const m
, AuthRecord
*const rr
)
1660 RData
*OldRData
= rr
->resrec
.rdata
;
1661 mDNSu16 OldRDLen
= rr
->resrec
.rdlength
;
1662 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
1663 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
1664 if (rr
->UpdateCallback
)
1665 rr
->UpdateCallback(m
, rr
, OldRData
, OldRDLen
); // ... and let the client know
1668 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1669 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1670 // Exported so uDNS.c can call this
1671 mDNSexport mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
1674 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
1675 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
1676 mDNSBool dupList
= mDNSfalse
;
1678 if (RRLocalOnly(rr
))
1682 const mDNSu32 slot
= AuthHashSlot(rr
->resrec
.name
);
1684 a
= AuthGroupForRecord(&m
->rrauth
, slot
, &rr
->resrec
);
1685 if (!a
) return mDNSfalse
;
1687 while (*rp
&& *rp
!= rr
) rp
=&(*rp
)->next
;
1692 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1697 // We found our record on the main list. See if there are any duplicates that need special handling.
1698 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
1700 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1701 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1702 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
) if (RecordIsLocalDuplicate(r2
, rr
)) r2
->ProbeCount
= 0xFF;
1706 // Before we delete the record (and potentially send a goodbye packet)
1707 // first see if we have a record on the duplicate list ready to take over from it.
1708 AuthRecord
**d
= &m
->DuplicateRecords
;
1709 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
1712 AuthRecord
*dup
= *d
;
1713 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1714 dup
, rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1715 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
1716 if (RRLocalOnly(rr
))
1718 dup
->next
= mDNSNULL
;
1719 if (!InsertAuthRecord(m
, &m
->rrauth
, dup
)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m
, dup
));
1723 dup
->next
= rr
->next
; // And then...
1724 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
1726 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
1727 dup
->ProbeCount
= rr
->ProbeCount
;
1728 dup
->ProbeRestartCount
= rr
->ProbeRestartCount
;
1729 dup
->AnnounceCount
= rr
->AnnounceCount
;
1730 dup
->RequireGoodbye
= rr
->RequireGoodbye
;
1731 dup
->AnsweredLocalQ
= rr
->AnsweredLocalQ
;
1732 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
1733 dup
->ImmedUnicast
= rr
->ImmedUnicast
;
1734 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
1735 dup
->v4Requester
= rr
->v4Requester
;
1736 dup
->v6Requester
= rr
->v6Requester
;
1737 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
1738 dup
->LastAPTime
= rr
->LastAPTime
;
1739 dup
->LastMCTime
= rr
->LastMCTime
;
1740 dup
->LastMCInterface
= rr
->LastMCInterface
;
1741 dup
->Private
= rr
->Private
;
1742 dup
->state
= rr
->state
;
1743 rr
->RequireGoodbye
= mDNSfalse
;
1744 rr
->AnsweredLocalQ
= mDNSfalse
;
1750 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1751 p
= &m
->DuplicateRecords
;
1752 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1753 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1756 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1757 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1758 // also that have been marked above in this function. In that case, we come here and if we don't
1759 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1760 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1762 rr
->WakeUp
.HMAC
= zeroEthAddr
;
1763 rr
->RequireGoodbye
= mDNSfalse
;
1764 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1767 if (*p
) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1768 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1773 // No need to log an error message if we already know this is a potentially repeated deregistration
1774 if (drt
!= mDNS_Dereg_repeat
)
1775 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr
, ARDisplayString(m
,rr
));
1776 return(mStatus_BadReferenceErr
);
1779 // If this is a shared record and we've announced it at least once,
1780 // we need to retract that announcement before we delete the record
1782 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1783 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1784 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1785 // mechanism to cope with the client callback modifying the question list while that's happening.
1786 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1787 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1788 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1789 // records, thereby invoking yet more callbacks, without limit.
1790 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1791 // actual goodbye packets.
1793 #ifndef UNICAST_DISABLED
1794 if (AuthRecord_uDNS(rr
))
1796 if (rr
->RequireGoodbye
)
1798 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1799 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1800 m
->LocalRemoveEvents
= mDNStrue
;
1801 uDNS_DeregisterRecord(m
, rr
);
1802 // At this point unconditionally we bail out
1803 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1804 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1805 // process and will complete asynchronously. Either way we don't need to do anything more here.
1806 return(mStatus_NoError
);
1808 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1809 // from the server. In that case, if the records have been part of a group update, clear the
1810 // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1811 rr
->updateid
= zeroID
;
1813 // We defer cleaning up NAT state only after sending goodbyes. This is important because
1814 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1815 // This happens today when we turn on/off interface where we get multiple network transitions
1816 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1817 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1818 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1819 // NAT state here takes care of the case where we did not send goodbyes at all.
1820 if (rr
->NATinfo
.clientContext
)
1822 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1823 rr
->NATinfo
.clientContext
= mDNSNULL
;
1825 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1826 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1828 #endif // UNICAST_DISABLED
1830 if (RecordType
== kDNSRecordTypeUnregistered
)
1831 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m
, rr
));
1832 else if (RecordType
== kDNSRecordTypeDeregistering
)
1834 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m
, rr
));
1835 return(mStatus_BadReferenceErr
);
1838 // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1839 // We may want to consider changing this code so that we generate local-only question "rmv"
1840 // events (and maybe goodbye packets too) for unique records as well as for shared records
1841 // Note: If we change the logic for this "if" statement, need to ensure that the code in
1842 // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1843 // clause will execute here and the record will be cut from the list.
1844 if (rr
->WakeUp
.HMAC
.l
[0] ||
1845 (RecordType
== kDNSRecordTypeShared
&& (rr
->RequireGoodbye
|| rr
->AnsweredLocalQ
)))
1847 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m
, rr
));
1848 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1849 rr
->resrec
.rroriginalttl
= 0;
1850 rr
->AnnounceCount
= rr
->WakeUp
.HMAC
.l
[0] ? WakeupCount
: (drt
== mDNS_Dereg_rapid
) ? 1 : GoodbyeCount
;
1851 rr
->ThisAPInterval
= mDNSPlatformOneSecond
* 2;
1852 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1853 m
->LocalRemoveEvents
= mDNStrue
;
1854 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
1855 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
1859 if (!dupList
&& RRLocalOnly(rr
))
1861 AuthGroup
*ag
= RemoveAuthRecord(m
, &m
->rrauth
, rr
);
1862 if (ag
->NewLocalOnlyRecords
== rr
) ag
->NewLocalOnlyRecords
= rr
->next
;
1866 *p
= rr
->next
; // Cut this record from the list
1867 if (m
->NewLocalRecords
== rr
) m
->NewLocalRecords
= rr
->next
;
1868 DecrementAutoTargetServices(m
, rr
);
1870 // If someone is about to look at this, bump the pointer forward
1871 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
1872 rr
->next
= mDNSNULL
;
1874 // Should we generate local remove events here?
1875 // i.e. something like:
1876 // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1878 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m
, rr
));
1879 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
1881 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
1882 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1883 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1885 // If we have an update queued up which never executed, give the client a chance to free that memory
1886 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
1889 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1890 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1891 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1892 // so any attempt to touch rr after this is likely to lead to a crash.
1893 if (drt
!= mDNS_Dereg_conflict
)
1895 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1896 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m
, rr
));
1897 if (rr
->RecordCallback
)
1898 rr
->RecordCallback(m
, rr
, mStatus_MemFree
); // MUST NOT touch rr after this
1899 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1903 RecordProbeFailure(m
, rr
);
1904 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1905 if (rr
->RecordCallback
)
1906 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
); // MUST NOT touch rr after this
1907 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1908 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1909 // Note that with all the client callbacks going on, by the time we get here all the
1910 // records we marked may have been explicitly deregistered by the client anyway.
1911 r2
= m
->DuplicateRecords
;
1914 if (r2
->ProbeCount
!= 0xFF)
1920 #if APPLE_OSX_mDNSResponder
1921 // See if this record was also registered with any D2D plugins.
1922 D2D_stop_advertising_record(r2
);
1924 mDNS_Deregister_internal(m
, r2
, mDNS_Dereg_conflict
);
1925 // As this is a duplicate record, it will be unlinked from the list
1927 r2
= m
->DuplicateRecords
;
1932 mDNS_UpdateAllowSleep(m
);
1933 return(mStatus_NoError
);
1936 // ***************************************************************************
1937 #if COMPILER_LIKES_PRAGMA_MARK
1939 #pragma mark - Packet Sending Functions
1942 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
1944 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
1947 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1948 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1949 // The referenced record will definitely be acceptable (by recursive application of this rule)
1950 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
1951 rr
->NR_AdditionalTo
= add
;
1952 *nrpp
= &rr
->NextResponse
;
1954 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1957 mDNSlocal
void AddAdditionalsToResponseList(mDNS
*const m
, AuthRecord
*ResponseRecords
, AuthRecord
***nrpp
, const mDNSInterfaceID InterfaceID
)
1959 AuthRecord
*rr
, *rr2
;
1960 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
1962 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1963 // later in the "for" loop, and we will follow further "additional" links then.)
1964 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
1965 AddRecordToResponseList(nrpp
, rr
->Additional1
, rr
);
1967 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
1968 AddRecordToResponseList(nrpp
, rr
->Additional2
, rr
);
1970 // For SRV records, automatically add the Address record(s) for the target host
1971 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
1973 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
1974 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
1975 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
1976 rr
->resrec
.rdatahash
== rr2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
1977 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, rr2
->resrec
.name
))
1978 AddRecordToResponseList(nrpp
, rr2
, rr
);
1980 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
)) // For A or AAAA, put counterpart as additional
1982 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
1983 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
1984 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
1985 rr
->resrec
.namehash
== rr2
->resrec
.namehash
&& // ... and have the same name
1986 SameDomainName(rr
->resrec
.name
, rr2
->resrec
.name
))
1987 AddRecordToResponseList(nrpp
, rr2
, rr
);
1989 else if (rr
->resrec
.rrtype
== kDNSType_PTR
) // For service PTR, see if we want to add DeviceInfo record
1991 if (ResourceRecordIsValidInterfaceAnswer(&m
->DeviceInfo
, InterfaceID
) &&
1992 SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
1993 AddRecordToResponseList(nrpp
, &m
->DeviceInfo
, rr
);
1998 mDNSlocal
int AnonInfoSpace(AnonymousInfo
*info
)
2000 ResourceRecord
*rr
= info
->nsec3RR
;
2002 // 2 bytes for compressed name + type (2) class (2) TTL (4) rdlength (2) rdata (n)
2003 return (2 + 10 + rr
->rdlength
);
2006 mDNSlocal
void SendDelayedUnicastResponse(mDNS
*const m
, const mDNSAddr
*const dest
, const mDNSInterfaceID InterfaceID
)
2009 AuthRecord
*ResponseRecords
= mDNSNULL
;
2010 AuthRecord
**nrp
= &ResponseRecords
;
2011 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
2012 int AnoninfoSpace
= 0;
2014 // Make a list of all our records that need to be unicast to this destination
2015 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2017 // If we find we can no longer unicast this answer, clear ImmedUnicast
2018 if (rr
->ImmedAnswer
== mDNSInterfaceMark
||
2019 mDNSSameIPv4Address(rr
->v4Requester
, onesIPv4Addr
) ||
2020 mDNSSameIPv6Address(rr
->v6Requester
, onesIPv6Addr
) )
2021 rr
->ImmedUnicast
= mDNSfalse
;
2023 if (rr
->ImmedUnicast
&& rr
->ImmedAnswer
== InterfaceID
)
2025 if ((dest
->type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->v4Requester
, dest
->ip
.v4
)) ||
2026 (dest
->type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->v6Requester
, dest
->ip
.v6
)))
2028 rr
->ImmedAnswer
= mDNSNULL
; // Clear the state fields
2029 rr
->ImmedUnicast
= mDNSfalse
;
2030 rr
->v4Requester
= zerov4Addr
;
2031 rr
->v6Requester
= zerov6Addr
;
2033 // Only sent records registered for P2P over P2P interfaces
2034 if (intf
&& !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
))
2039 if (rr
->NextResponse
== mDNSNULL
&& nrp
!= &rr
->NextResponse
) // rr->NR_AnswerTo
2041 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
2043 nrp
= &rr
->NextResponse
;
2049 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
2051 while (ResponseRecords
)
2053 mDNSu8
*responseptr
= m
->omsg
.data
;
2055 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2057 // Put answers in the packet
2058 while (ResponseRecords
&& ResponseRecords
->NR_AnswerTo
)
2060 rr
= ResponseRecords
;
2061 if (rr
->resrec
.AnonInfo
)
2063 AnoninfoSpace
+= AnonInfoSpace(rr
->resrec
.AnonInfo
);
2064 rr
->resrec
.AnonInfo
->SendNow
= mDNSInterfaceMark
;
2066 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2067 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2069 // Retract the limit by AnoninfoSpace which we need to put the AnoInfo option.
2070 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, rr
->resrec
.rroriginalttl
,
2071 m
->omsg
.data
+ (AllowedRRSpace(&m
->omsg
) - AnoninfoSpace
));
2073 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2074 if (!newptr
&& m
->omsg
.h
.numAnswers
)
2076 break; // If packet full, send it now
2078 if (newptr
) responseptr
= newptr
;
2079 ResponseRecords
= rr
->NextResponse
;
2080 rr
->NextResponse
= mDNSNULL
;
2081 rr
->NR_AnswerTo
= mDNSNULL
;
2082 rr
->NR_AdditionalTo
= mDNSNULL
;
2083 rr
->RequireGoodbye
= mDNStrue
;
2086 // We have reserved the space for AnonInfo option. PutResourceRecord uses the
2087 // standard limit (AllowedRRSpace) and we should have space now.
2088 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2090 if (rr
->resrec
.AnonInfo
&& rr
->resrec
.AnonInfo
->SendNow
== mDNSInterfaceMark
)
2092 ResourceRecord
*nsec3RR
= rr
->resrec
.AnonInfo
->nsec3RR
;
2094 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAuthorities
, nsec3RR
);
2097 responseptr
= newptr
;
2098 debugf("SendDelayedUnicastResponse: Added NSEC3 Record %s on %p", RRDisplayString(m
, nsec3RR
), intf
->InterfaceID
);
2102 // We allocated space and we should not fail. Don't break, we need to clear the SendNow flag.
2103 LogMsg("SendDelayedUnicastResponse: ERROR!! Cannot Add NSEC3 Record %s on %p", RRDisplayString(m
, nsec3RR
), intf
->InterfaceID
);
2105 rr
->resrec
.AnonInfo
->SendNow
= mDNSNULL
;
2109 // Add additionals, if there's space
2110 while (ResponseRecords
&& !ResponseRecords
->NR_AnswerTo
)
2112 rr
= ResponseRecords
;
2113 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2114 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2115 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2116 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2118 if (newptr
) responseptr
= newptr
;
2119 if (newptr
&& m
->omsg
.h
.numAnswers
) rr
->RequireGoodbye
= mDNStrue
;
2120 else if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
->ImmedAnswer
= mDNSInterfaceMark
;
2121 ResponseRecords
= rr
->NextResponse
;
2122 rr
->NextResponse
= mDNSNULL
;
2123 rr
->NR_AnswerTo
= mDNSNULL
;
2124 rr
->NR_AdditionalTo
= mDNSNULL
;
2127 if (m
->omsg
.h
.numAnswers
)
2128 mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, InterfaceID
, mDNSNULL
, dest
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
2132 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2133 // and the client's mStatus_MemFree callback will have been invoked
2134 mDNSexport
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
2136 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m
, rr
));
2137 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2138 // it should go ahead and immediately dispose of this registration
2139 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
2140 rr
->RequireGoodbye
= mDNSfalse
;
2141 rr
->WakeUp
.HMAC
= zeroEthAddr
;
2142 if (rr
->AnsweredLocalQ
) { AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
); rr
->AnsweredLocalQ
= mDNSfalse
; }
2143 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
); // Don't touch rr after this
2146 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2147 // any deregistering records that remain in the m->ResourceRecords list.
2148 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2149 // which may change the record list and/or question list.
2150 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2151 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
2153 if (m
->CurrentRecord
)
2154 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2155 m
->CurrentRecord
= m
->ResourceRecords
;
2157 while (m
->CurrentRecord
)
2159 AuthRecord
*rr
= m
->CurrentRecord
;
2160 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2161 CompleteDeregistration(m
, rr
); // Don't touch rr after this
2163 m
->CurrentRecord
= rr
->next
;
2167 mDNSlocal mStatus
GetLabelDecimalValue(const mDNSu8
*const src
, mDNSu8
*dst
)
2170 if (src
[0] < 1 || src
[0] > 3) return(mStatus_Invalid
);
2171 for (i
=1; i
<=src
[0]; i
++)
2173 if (src
[i
] < '0' || src
[i
] > '9') return(mStatus_Invalid
);
2174 val
= val
* 10 + src
[i
] - '0';
2176 if (val
> 255) return(mStatus_Invalid
);
2178 return(mStatus_NoError
);
2181 mDNSlocal mStatus
GetIPv4FromName(mDNSAddr
*const a
, const domainname
*const name
)
2183 int skip
= CountLabels(name
) - 6;
2184 if (skip
< 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2185 if (GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+3)->c
, &a
->ip
.v4
.b
[0]) ||
2186 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+2)->c
, &a
->ip
.v4
.b
[1]) ||
2187 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+1)->c
, &a
->ip
.v4
.b
[2]) ||
2188 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+0)->c
, &a
->ip
.v4
.b
[3])) return mStatus_Invalid
;
2189 a
->type
= mDNSAddrType_IPv4
;
2190 return(mStatus_NoError
);
2193 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2194 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2195 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2197 mDNSlocal mStatus
GetIPv6FromName(mDNSAddr
*const a
, const domainname
*const name
)
2200 const domainname
*n
;
2202 int skip
= CountLabels(name
) - 34;
2203 if (skip
< 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2205 n
= SkipLeadingLabels(name
, skip
);
2206 for (i
=0; i
<16; i
++)
2208 if (n
->c
[0] != 1) return mStatus_Invalid
;
2209 l
= HexVal(n
->c
[1]);
2210 n
= (const domainname
*)(n
->c
+ 2);
2212 if (n
->c
[0] != 1) return mStatus_Invalid
;
2213 h
= HexVal(n
->c
[1]);
2214 n
= (const domainname
*)(n
->c
+ 2);
2216 if (l
<0 || h
<0) return mStatus_Invalid
;
2217 a
->ip
.v6
.b
[15-i
] = (mDNSu8
)((h
<< 4) | l
);
2220 a
->type
= mDNSAddrType_IPv6
;
2221 return(mStatus_NoError
);
2224 mDNSlocal mDNSs32
ReverseMapDomainType(const domainname
*const name
)
2226 int skip
= CountLabels(name
) - 2;
2229 const domainname
*suffix
= SkipLeadingLabels(name
, skip
);
2230 if (SameDomainName(suffix
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4
;
2231 if (SameDomainName(suffix
, (const domainname
*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6
;
2233 return(mDNSAddrType_None
);
2236 mDNSlocal
void SendARP(mDNS
*const m
, const mDNSu8 op
, const AuthRecord
*const rr
,
2237 const mDNSv4Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2240 mDNSu8
*ptr
= m
->omsg
.data
;
2241 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2242 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2244 // 0x00 Destination address
2245 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2247 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2248 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
2250 // 0x0C ARP Ethertype (0x0806)
2251 *ptr
++ = 0x08; *ptr
++ = 0x06;
2254 *ptr
++ = 0x00; *ptr
++ = 0x01; // Hardware address space; Ethernet = 1
2255 *ptr
++ = 0x08; *ptr
++ = 0x00; // Protocol address space; IP = 0x0800
2256 *ptr
++ = 6; // Hardware address length
2257 *ptr
++ = 4; // Protocol address length
2258 *ptr
++ = 0x00; *ptr
++ = op
; // opcode; Request = 1, Response = 2
2260 // 0x16 Sender hardware address (our MAC address)
2261 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[i
];
2263 // 0x1C Sender protocol address
2264 for (i
=0; i
<4; i
++) *ptr
++ = spa
->b
[i
];
2266 // 0x20 Target hardware address
2267 for (i
=0; i
<6; i
++) *ptr
++ = tha
->b
[i
];
2269 // 0x26 Target protocol address
2270 for (i
=0; i
<4; i
++) *ptr
++ = tpa
->b
[i
];
2272 // 0x2A Total ARP Packet length 42 bytes
2273 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2276 mDNSlocal mDNSu16
CheckSum(const void *const data
, mDNSs32 length
, mDNSu32 sum
)
2278 const mDNSu16
*ptr
= data
;
2279 while (length
> 0) { length
-= 2; sum
+= *ptr
++; }
2280 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2281 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2282 return(sum
!= 0xFFFF ? sum
: 0);
2285 mDNSlocal mDNSu16
IPv6CheckSum(const mDNSv6Addr
*const src
, const mDNSv6Addr
*const dst
, const mDNSu8 protocol
, const void *const data
, const mDNSu32 length
)
2287 IPv6PseudoHeader ph
;
2290 ph
.len
.b
[0] = length
>> 24;
2291 ph
.len
.b
[1] = length
>> 16;
2292 ph
.len
.b
[2] = length
>> 8;
2293 ph
.len
.b
[3] = length
;
2297 ph
.pro
.b
[3] = protocol
;
2298 return CheckSum(&ph
, sizeof(ph
), CheckSum(data
, length
, 0));
2301 mDNSlocal
void SendNDP(mDNS
*const m
, const mDNSu8 op
, const mDNSu8 flags
, const AuthRecord
*const rr
,
2302 const mDNSv6Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv6Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2305 mDNSOpaque16 checksum
;
2306 mDNSu8
*ptr
= m
->omsg
.data
;
2307 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2308 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2309 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2310 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] } };
2311 const mDNSv6Addr
*const v6dst
= (op
== NDP_Sol
) ? &mc
: tpa
;
2312 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2313 if (!intf
) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2315 // 0x00 Destination address
2316 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2317 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2318 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2319 // link with a pointless link-layer multicast.
2320 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2321 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2325 // *ptr++ = tpa->b[0xD];
2326 // *ptr++ = tpa->b[0xE];
2327 // *ptr++ = tpa->b[0xF];
2329 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2330 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2332 // 0x0C IPv6 Ethertype (0x86DD)
2333 *ptr
++ = 0x86; *ptr
++ = 0xDD;
2336 *ptr
++ = 0x60; *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00; // Version, Traffic Class, Flow Label
2337 *ptr
++ = 0x00; *ptr
++ = 0x20; // Length
2338 *ptr
++ = 0x3A; // Protocol == ICMPv6
2339 *ptr
++ = 0xFF; // Hop Limit
2341 // 0x16 Sender IPv6 address
2342 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2344 // 0x26 Destination IPv6 address
2345 for (i
=0; i
<16; i
++) *ptr
++ = v6dst
->b
[i
];
2348 *ptr
++ = op
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2349 *ptr
++ = 0x00; // Code
2350 *ptr
++ = 0x00; *ptr
++ = 0x00; // Checksum placeholder (0x38, 0x39)
2352 *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00;
2354 if (op
== NDP_Sol
) // Neighbor Solicitation. The NDP "target" is the address we seek.
2357 for (i
=0; i
<16; i
++) *ptr
++ = tpa
->b
[i
];
2358 // 0x4E Source Link-layer Address
2359 // <http://www.ietf.org/rfc/rfc2461.txt>
2360 // MUST NOT be included when the source IP address is the unspecified address.
2361 // Otherwise, on link layers that have addresses this option MUST be included
2362 // in multicast solicitations and SHOULD be included in unicast solicitations.
2363 if (!mDNSIPv6AddressIsZero(*spa
))
2365 *ptr
++ = NDP_SrcLL
; // Option Type 1 == Source Link-layer Address
2366 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2367 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2370 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2373 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2374 // 0x4E Target Link-layer Address
2375 *ptr
++ = NDP_TgtLL
; // Option Type 2 == Target Link-layer Address
2376 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2377 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2380 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2381 m
->omsg
.data
[0x13] = ptr
- &m
->omsg
.data
[0x36]; // Compute actual length
2382 checksum
.NotAnInteger
= ~IPv6CheckSum(spa
, v6dst
, 0x3A, &m
->omsg
.data
[0x36], m
->omsg
.data
[0x13]);
2383 m
->omsg
.data
[0x38] = checksum
.b
[0];
2384 m
->omsg
.data
[0x39] = checksum
.b
[1];
2386 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2389 mDNSlocal
void SetupTracerOpt(const mDNS
*const m
, rdataOPT
*const Trace
)
2391 mDNSu32 DNS_VERS
= _DNS_SD_H
;
2392 Trace
->u
.tracer
.platf
= m
->mDNS_plat
;
2393 Trace
->u
.tracer
.mDNSv
= DNS_VERS
;
2395 Trace
->opt
= kDNSOpt_Trace
;
2396 Trace
->optlen
= DNSOpt_TraceData_Space
- 4;
2399 mDNSlocal
void SetupOwnerOpt(const mDNS
*const m
, const NetworkInterfaceInfo
*const intf
, rdataOPT
*const owner
)
2401 owner
->u
.owner
.vers
= 0;
2402 owner
->u
.owner
.seq
= m
->SleepSeqNum
;
2403 owner
->u
.owner
.HMAC
= m
->PrimaryMAC
;
2404 owner
->u
.owner
.IMAC
= intf
->MAC
;
2405 owner
->u
.owner
.password
= zeroEthAddr
;
2407 // Don't try to compute the optlen until *after* we've set up the data fields
2408 // 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
2409 owner
->opt
= kDNSOpt_Owner
;
2410 owner
->optlen
= DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) - 4;
2413 mDNSlocal
void GrantUpdateCredit(AuthRecord
*rr
)
2415 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
2416 else rr
->NextUpdateCredit
= NonZeroTime(rr
->NextUpdateCredit
+ kUpdateCreditRefreshInterval
);
2419 mDNSlocal mDNSBool
ShouldSendGoodbyesBeforeSleep(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, AuthRecord
*rr
)
2421 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2422 // and hence there is no need to check for Transfering state. But if we have sleep
2423 // proxies and partially sending goodbyes for some records, we will be in Transfering
2424 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2425 // we are not awake handles both cases.
2426 if ((rr
->AuthFlags
& AuthFlagsWakeOnly
) && (m
->SleepState
!= SleepState_Awake
))
2428 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m
, rr
));
2432 if (m
->SleepState
!= SleepState_Sleeping
)
2435 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2436 // whether you can send goodbyes or not.
2437 if (!intf
->SendGoodbyes
)
2439 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2444 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2449 mDNSlocal mDNSBool
IsInterfaceValidForAuthRecord(const AuthRecord
*ar
, mDNSInterfaceID InterfaceID
)
2453 if (ar
->resrec
.InterfaceID
== mDNSInterface_Any
)
2455 result
= mDNSPlatformValidRecordForInterface(ar
, InterfaceID
);
2459 result
= (ar
->resrec
.InterfaceID
== InterfaceID
);
2465 // Note about acceleration of announcements to facilitate automatic coalescing of
2466 // multiple independent threads of announcements into a single synchronized thread:
2467 // The announcements in the packet may be at different stages of maturity;
2468 // One-second interval, two-second interval, four-second interval, and so on.
2469 // After we've put in all the announcements that are due, we then consider
2470 // whether there are other nearly-due announcements that are worth accelerating.
2471 // To be eligible for acceleration, a record MUST NOT be older (further along
2472 // its timeline) than the most mature record we've already put in the packet.
2473 // In other words, younger records can have their timelines accelerated to catch up
2474 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2475 // Older records cannot have their timelines accelerated; this would just widen
2476 // the gap between them and their younger bretheren and get them even more out of sync.
2478 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2479 // the record list and/or question list.
2480 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2481 mDNSlocal
void SendResponses(mDNS
*const m
)
2484 AuthRecord
*rr
, *r2
;
2485 mDNSs32 maxExistingAnnounceInterval
= 0;
2486 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2488 m
->NextScheduledResponse
= m
->timenow
+ 0x78000000;
2490 if (m
->SleepState
== SleepState_Transferring
) RetrySPSRegistrations(m
);
2492 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2493 if (rr
->ImmedUnicast
)
2495 mDNSAddr v4
= { mDNSAddrType_IPv4
, {{{0}}} };
2496 mDNSAddr v6
= { mDNSAddrType_IPv6
, {{{0}}} };
2497 v4
.ip
.v4
= rr
->v4Requester
;
2498 v6
.ip
.v6
= rr
->v6Requester
;
2499 if (!mDNSIPv4AddressIsZero(rr
->v4Requester
)) SendDelayedUnicastResponse(m
, &v4
, rr
->ImmedAnswer
);
2500 if (!mDNSIPv6AddressIsZero(rr
->v6Requester
)) SendDelayedUnicastResponse(m
, &v6
, rr
->ImmedAnswer
);
2501 if (rr
->ImmedUnicast
)
2503 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m
, rr
));
2504 rr
->ImmedUnicast
= mDNSfalse
;
2509 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2512 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2513 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2515 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
2516 if (TimeToAnnounceThisRecord(rr
, m
->timenow
))
2518 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2520 if (!rr
->WakeUp
.HMAC
.l
[0])
2522 if (rr
->AnnounceCount
) rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send goodbye packet on all interfaces
2526 mDNSBool unicastOnly
;
2527 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr
->AnnounceCount
-3, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
2528 unicastOnly
= ((rr
->AnnounceCount
== WakeupCount
) || (rr
->AnnounceCount
== WakeupCount
- 1)) ? mDNStrue
: mDNSfalse
;
2529 SendWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.IMAC
, &rr
->WakeUp
.password
, unicastOnly
);
2530 for (r2
= rr
; r2
; r2
=r2
->next
)
2531 if ((r2
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) && r2
->AnnounceCount
&& (r2
->resrec
.InterfaceID
== rr
->resrec
.InterfaceID
) &&
2532 mDNSSameEthAddress(&r2
->WakeUp
.IMAC
, &rr
->WakeUp
.IMAC
) && !mDNSSameEthAddress(&zeroEthAddr
, &r2
->WakeUp
.HMAC
))
2534 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2535 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2536 if (r2
->AddressProxy
.type
== mDNSAddrType_IPv6
&& r2
->AnnounceCount
== WakeupCount
)
2538 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2539 r2
->AnnounceCount
-3, &r2
->WakeUp
.HMAC
, &r2
->WakeUp
.IMAC
, ARDisplayString(m
,r2
));
2540 SendNDP(m
, NDP_Adv
, NDP_Override
, r2
, &r2
->AddressProxy
.ip
.v6
, &r2
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2542 r2
->LastAPTime
= m
->timenow
;
2543 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2544 if (--r2
->AnnounceCount
<= GoodbyeCount
) r2
->WakeUp
.HMAC
= zeroEthAddr
;
2548 else if (ResourceRecordIsValidAnswer(rr
))
2550 if (rr
->AddressProxy
.type
)
2552 if (!mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
2554 rr
->AnnounceCount
--;
2555 rr
->ThisAPInterval
*= 2;
2556 rr
->LastAPTime
= m
->timenow
;
2557 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv4
)
2559 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2560 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2561 SendARP(m
, 1, rr
, &rr
->AddressProxy
.ip
.v4
, &zeroEthAddr
, &rr
->AddressProxy
.ip
.v4
, &onesEthAddr
);
2563 else if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
2565 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2566 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2567 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2573 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2574 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
2575 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
2576 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
2582 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2583 // Eligible records that are more than half-way to their announcement time are accelerated
2584 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2585 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
2586 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
2587 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
2588 !rr
->AddressProxy
.type
&& // Don't include ARP Annoucements when considering which records to accelerate
2589 ResourceRecordIsValidAnswer(rr
)))
2590 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2592 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2593 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2594 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2595 // then all that means is that it won't get sent -- which would not be the end of the world.
2596 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2598 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
2599 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
2600 if (RRTypeIsAddressType(r2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2601 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
2602 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
2603 rr
->resrec
.rdatahash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2604 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, r2
->resrec
.name
) &&
2605 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
2606 r2
->ImmedAdditional
= r2
->resrec
.InterfaceID
; // ... then mark this address record for sending too
2607 // We also make sure we send the DeviceInfo TXT record too, if necessary
2608 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2609 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2610 if (rr
->ImmedAnswer
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->resrec
.rrtype
== kDNSType_PTR
)
2611 if (ResourceRecordIsValidAnswer(&m
->DeviceInfo
) && SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2613 if (!m
->DeviceInfo
.ImmedAnswer
) m
->DeviceInfo
.ImmedAnswer
= rr
->ImmedAnswer
;
2614 else m
->DeviceInfo
.ImmedAnswer
= mDNSInterfaceMark
;
2618 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2619 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2620 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2621 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2622 // -- 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
2623 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2624 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2625 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2627 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
2629 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2631 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2632 (r2
->ImmedAnswer
!= mDNSInterfaceMark
) && (r2
->ImmedAnswer
!= rr
->ImmedAnswer
) &&
2633 SameResourceRecordSignature(r2
, rr
) &&
2634 ((rr
->ImmedAnswer
== mDNSInterfaceMark
) || IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAnswer
)))
2636 r2
->ImmedAnswer
= !r2
->ImmedAnswer
? rr
->ImmedAnswer
: mDNSInterfaceMark
;
2640 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
2642 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2644 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2645 (r2
->ImmedAdditional
!= rr
->ImmedAdditional
) &&
2646 SameResourceRecordSignature(r2
, rr
) &&
2647 IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAdditional
))
2649 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
2655 // Now set SendRNow state appropriately
2656 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2658 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
2660 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
2661 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
2662 rr
->LastMCTime
= m
->timenow
;
2663 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2664 rr
->ProbeRestartCount
= 0; // Reset the probe restart count
2665 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2666 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
2668 rr
->AnnounceCount
--;
2669 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
2670 rr
->ThisAPInterval
*= 2;
2671 rr
->LastAPTime
= m
->timenow
;
2672 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
2675 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
2677 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
2678 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
2679 rr
->LastMCTime
= m
->timenow
;
2680 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2682 SetNextAnnounceProbeTime(m
, rr
);
2683 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2687 // *** 2. Loop through interface list, sending records as appropriate
2692 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
2693 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
2695 int numAnnounce
= 0;
2697 int AnoninfoSpace
= 0;
2698 mDNSu8
*responseptr
= m
->omsg
.data
;
2700 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2702 // First Pass. Look for:
2703 // 1. Deregistering records that need to send their goodbye packet
2704 // 2. Updated records that need to retract their old data
2705 // 3. Answers and announcements we need to send
2706 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2709 // Skip this interface if the record InterfaceID is *Any and the record is not
2710 // appropriate for the interface type.
2711 if ((rr
->SendRNow
== intf
->InterfaceID
) &&
2712 ((rr
->resrec
.InterfaceID
== mDNSInterface_Any
) && !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
)))
2714 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2716 else if (rr
->SendRNow
== intf
->InterfaceID
)
2718 RData
*OldRData
= rr
->resrec
.rdata
;
2719 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
2720 mDNSu8 active
= (mDNSu8
)
2721 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& !ShouldSendGoodbyesBeforeSleep(m
, intf
, rr
));
2723 if (rr
->NewRData
&& active
)
2725 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2726 if (ResourceRecordIsValidAnswer(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
2728 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, 0);
2729 if (newptr
) { responseptr
= newptr
; numDereg
++; rr
->RequireGoodbye
= mDNSfalse
; }
2730 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
2732 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
2735 if (rr
->resrec
.AnonInfo
)
2737 int tmp
= AnonInfoSpace(rr
->resrec
.AnonInfo
);
2739 AnoninfoSpace
+= tmp
;
2740 // Adjust OwnerRecordSpace/TraceRecordSpace which is used by PutRR_OS_TTL below so that
2741 // we have space to put in the NSEC3 record in the authority section.
2742 OwnerRecordSpace
+= tmp
;
2743 TraceRecordSpace
+= tmp
;
2746 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2747 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2748 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, active
? rr
->resrec
.rroriginalttl
: 0);
2749 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2752 responseptr
= newptr
;
2753 rr
->RequireGoodbye
= active
;
2754 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) numDereg
++;
2755 else if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++;else numAnswer
++;
2758 if (rr
->NewRData
&& active
)
2759 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
2761 // The first time through (pktcount==0), if this record is verified unique
2762 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2763 if (!pktcount
&& active
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2764 rr
->SendNSECNow
= mDNSInterfaceMark
;
2766 if (newptr
) // If succeeded in sending, advance to next interface
2768 if (rr
->resrec
.AnonInfo
)
2770 debugf("SendResponses: Marking %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m
, rr
), OwnerRecordSpace
,
2771 TraceRecordSpace
, m
->omsg
.data
+ AllowedRRSpace(&m
->omsg
) - OwnerRecordSpace
- TraceRecordSpace
);
2772 rr
->resrec
.AnonInfo
->SendNow
= intf
->InterfaceID
;
2775 // If sending on all interfaces, go to next interface; else we're finished now
2776 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
2777 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2779 rr
->SendRNow
= mDNSNULL
;
2784 // Get the reserved space back
2785 OwnerRecordSpace
-= AnoninfoSpace
;
2786 TraceRecordSpace
-= AnoninfoSpace
;
2787 newptr
= responseptr
;
2788 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2790 if (rr
->resrec
.AnonInfo
&& rr
->resrec
.AnonInfo
->SendNow
== intf
->InterfaceID
)
2792 ResourceRecord
*nsec3RR
= rr
->resrec
.AnonInfo
->nsec3RR
;
2794 newptr
= PutRR_OS_TTL(newptr
, &m
->omsg
.h
.numAuthorities
, nsec3RR
, nsec3RR
->rroriginalttl
);
2797 responseptr
= newptr
;
2798 debugf("SendResponses: Added NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m
, rr
), OwnerRecordSpace
,
2799 TraceRecordSpace
, m
->omsg
.data
+ AllowedRRSpace(&m
->omsg
) - OwnerRecordSpace
- TraceRecordSpace
);
2803 LogMsg("SendResponses: Cannot add NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m
, rr
), OwnerRecordSpace
,
2804 TraceRecordSpace
, m
->omsg
.data
+ AllowedRRSpace(&m
->omsg
) - OwnerRecordSpace
- TraceRecordSpace
);
2806 rr
->resrec
.AnonInfo
->SendNow
= mDNSNULL
;
2809 // Second Pass. Add additional records, if there's space.
2810 newptr
= responseptr
;
2811 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2812 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
2813 if (ResourceRecordIsValidAnswer(rr
))
2815 // If we have at least one answer already in the packet, then plan to add additionals too
2816 mDNSBool SendAdditional
= (m
->omsg
.h
.numAnswers
> 0);
2818 // If we're not planning to send any additionals, but this record is a unique one, then
2819 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2820 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2821 if (!SendAdditional
&& (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
2823 const AuthRecord
*a
;
2824 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
2825 if (a
->LastMCTime
== m
->timenow
&&
2826 a
->LastMCInterface
== intf
->InterfaceID
&&
2827 SameResourceRecordSignature(a
, rr
)) { SendAdditional
= mDNStrue
; break; }
2829 if (!SendAdditional
) // If we don't want to send this after all,
2830 rr
->ImmedAdditional
= mDNSNULL
; // then cancel its ImmedAdditional field
2831 else if (newptr
) // Else, try to add it if we can
2833 // The first time through (pktcount==0), if this record is verified unique
2834 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2835 if (!pktcount
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2836 rr
->SendNSECNow
= mDNSInterfaceMark
;
2838 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2839 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2840 newptr
= PutRR_OS(newptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2841 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2844 responseptr
= newptr
;
2845 rr
->ImmedAdditional
= mDNSNULL
;
2846 rr
->RequireGoodbye
= mDNStrue
;
2847 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2848 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2849 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2850 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2851 rr
->LastMCTime
= m
->timenow
;
2852 rr
->LastMCInterface
= intf
->InterfaceID
;
2857 // Third Pass. Add NSEC records, if there's space.
2858 // When we're generating an NSEC record in response to a specify query for that type
2859 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2860 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2861 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2862 if (rr
->SendNSECNow
== mDNSInterfaceMark
|| rr
->SendNSECNow
== intf
->InterfaceID
)
2867 mDNS_SetupResourceRecord(&nsec
, mDNSNULL
, mDNSInterface_Any
, kDNSType_NSEC
, rr
->resrec
.rroriginalttl
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2868 nsec
.resrec
.rrclass
|= kDNSClass_UniqueRRSet
;
2869 AssignDomainName(&nsec
.namestorage
, rr
->resrec
.name
);
2870 ptr
= nsec
.rdatastorage
.u
.data
;
2871 len
= DomainNameLength(rr
->resrec
.name
);
2872 // We have a nxt name followed by window number, window length and a window bitmap
2873 nsec
.resrec
.rdlength
= len
+ 2 + NSEC_MCAST_WINDOW_SIZE
;
2874 if (nsec
.resrec
.rdlength
<= StandardAuthRDSize
)
2876 mDNSPlatformMemZero(ptr
, nsec
.resrec
.rdlength
);
2877 AssignDomainName((domainname
*)ptr
, rr
->resrec
.name
);
2879 *ptr
++ = 0; // window number
2880 *ptr
++ = NSEC_MCAST_WINDOW_SIZE
; // window length
2881 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2882 if (ResourceRecordIsValidAnswer(r2
) && SameResourceRecordNameClassInterface(r2
, rr
))
2884 if (r2
->resrec
.rrtype
>= kDNSQType_ANY
) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m
, r2
)); break; }
2885 else ptr
[r2
->resrec
.rrtype
>> 3] |= 128 >> (r2
->resrec
.rrtype
& 7);
2887 newptr
= responseptr
;
2888 if (!r2
) // If we successfully built our NSEC record, add it to the packet now
2890 newptr
= PutRR_OS(responseptr
, &m
->omsg
.h
.numAdditionals
, &nsec
.resrec
);
2891 if (newptr
) responseptr
= newptr
;
2894 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec
.resrec
.rdlength
);
2896 // If we successfully put the NSEC record, clear the SendNSECNow flag
2897 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2898 if (newptr
|| rr
->SendNSECNow
== mDNSInterfaceMark
)
2900 rr
->SendNSECNow
= mDNSNULL
;
2901 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2902 for (r2
= rr
->next
; r2
; r2
=r2
->next
)
2903 if (SameResourceRecordNameClassInterface(r2
, rr
))
2904 if (r2
->SendNSECNow
== mDNSInterfaceMark
|| r2
->SendNSECNow
== intf
->InterfaceID
)
2905 r2
->SendNSECNow
= mDNSNULL
;
2909 if (m
->omsg
.h
.numAnswers
|| m
->omsg
.h
.numAdditionals
)
2911 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
2912 if (OwnerRecordSpace
|| TraceRecordSpace
)
2915 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2916 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
2917 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
2918 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
2919 if (OwnerRecordSpace
&& TraceRecordSpace
)
2921 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
2922 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
2923 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
2924 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
2926 else if (OwnerRecordSpace
)
2928 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
2930 else if (TraceRecordSpace
)
2932 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
2934 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
);
2937 responseptr
= newptr
;
2939 else if (m
->omsg
.h
.numAnswers
+ m
->omsg
.h
.numAuthorities
+ m
->omsg
.h
.numAdditionals
== 1)
2941 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
2942 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
2946 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
2947 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
2951 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2952 numDereg
, numDereg
== 1 ? "" : "s",
2953 numAnnounce
, numAnnounce
== 1 ? "" : "s",
2954 numAnswer
, numAnswer
== 1 ? "" : "s",
2955 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
2957 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
2958 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
2959 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
2960 if (++pktcount
>= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
2961 // There might be more things to send on this interface, so go around one more time and try again.
2963 else // Nothing more to send on this interface; go to next
2965 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
2966 #if MDNS_DEBUGMSGS && 0
2967 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2968 debugf(msg
, intf
, next
);
2971 pktcount
= 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2976 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2979 if (m
->CurrentRecord
)
2980 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2981 m
->CurrentRecord
= m
->ResourceRecords
;
2982 while (m
->CurrentRecord
)
2984 rr
= m
->CurrentRecord
;
2985 m
->CurrentRecord
= rr
->next
;
2989 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
)
2990 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
2991 (uint32_t)rr
->SendRNow
, (uint32_t)rr
->resrec
.InterfaceID
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
2992 rr
->SendRNow
= mDNSNULL
;
2995 if (rr
->ImmedAnswer
|| rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2997 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
2999 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->AnnounceCount
== 0)
3001 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3002 if (!AuthRecord_uDNS(rr
)) CompleteDeregistration(m
, rr
); // Don't touch rr after this
3006 rr
->ImmedAnswer
= mDNSNULL
;
3007 rr
->ImmedUnicast
= mDNSfalse
;
3008 rr
->v4Requester
= zerov4Addr
;
3009 rr
->v6Requester
= zerov6Addr
;
3013 verbosedebugf("SendResponses: Next in %ld ticks", m
->NextScheduledResponse
- m
->timenow
);
3016 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3017 // so we want to be lazy about how frequently we do it.
3018 // 1. If a cache record is currently referenced by *no* active questions,
3019 // then we don't mind expiring it up to a minute late (who will know?)
3020 // 2. Else, if a cache record is due for some of its final expiration queries,
3021 // we'll allow them to be late by up to 2% of the TTL
3022 // 3. Else, if a cache record has completed all its final expiration queries without success,
3023 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3024 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3025 // so allow at most 1/10 second lateness
3026 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3027 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3028 #define CacheCheckGracePeriod(RR) ( \
3029 ((RR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3030 ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50) : \
3031 ((RR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3032 ((RR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3034 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
3036 mDNSexport
void ScheduleNextCacheCheckTime(mDNS
*const m
, const mDNSu32 slot
, const mDNSs32 event
)
3038 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3039 m
->rrcache_nextcheck
[slot
] = event
;
3040 if (m
->NextCacheCheck
- event
> 0)
3041 m
->NextCacheCheck
= event
;
3044 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3046 // rr->resrec.rroriginalttl
3047 // rr->UnansweredQueries
3048 // rr->CRActiveQuestion
3049 mDNSexport
void SetNextCacheCheckTimeForRecord(mDNS
*const m
, CacheRecord
*const rr
)
3051 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3053 // If we have an active question, then see if we want to schedule a refresher query for this record.
3054 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3055 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3057 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3058 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3059 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3060 (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
,rr
));
3062 ScheduleNextCacheCheckTime(m
, HashSlot(rr
->resrec
.name
), NextCacheCheckEvent(rr
));
3065 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3066 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3067 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3068 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 5)
3070 mDNSexport mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3072 if (interval
< kMinimumReconfirmTime
)
3073 interval
= kMinimumReconfirmTime
;
3074 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3075 interval
= 0x10000000;
3077 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3078 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3080 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3081 // For all the reconfirmations in a given batch, we want to use the same random value
3082 // so that the reconfirmation questions can be grouped into a single query packet
3083 if (!m
->RandomReconfirmDelay
) m
->RandomReconfirmDelay
= 1 + mDNSRandom(0x3FFFFFFF);
3084 interval
+= m
->RandomReconfirmDelay
% ((interval
/3) + 1);
3085 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3086 rr
->resrec
.rroriginalttl
= (interval
* 4 + mDNSPlatformOneSecond
- 1) / mDNSPlatformOneSecond
;
3087 SetNextCacheCheckTimeForRecord(m
, rr
);
3089 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3090 RRExpireTime(rr
) - m
->timenow
, CRDisplayString(m
, rr
), rr
->CRActiveQuestion
);
3091 return(mStatus_NoError
);
3094 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3095 // It also appends to the list of known answer records that need to be included,
3096 // and updates the forcast for the size of the known answer section.
3097 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, DNSMessage
*query
, mDNSu8
**queryptr
,
3098 DNSQuestion
*q
, CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3100 mDNSBool ucast
= (q
->LargeAnswers
|| q
->RequestUnicast
) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3101 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3102 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3103 mDNSu8 anoninfo_space
= q
->AnonInfo
? AnonInfoSpace(q
->AnonInfo
) : 0;
3104 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
- *answerforecast
- anoninfo_space
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3107 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3112 mDNSu32 forecast
= *answerforecast
+ anoninfo_space
;
3113 const mDNSu32 slot
= HashSlot(&q
->qname
);
3114 const CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
3116 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3118 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3119 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3120 !(rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && // which is a shared (i.e. not unique) record type
3121 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not already in the known answer list
3122 rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3123 SameNameRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3124 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
> // and its half-way-to-expiry time is at least 1 second away
3125 mDNSPlatformOneSecond
) // (also ensures we never include goodbye records with TTL=1)
3127 // We don't want to include unique records in the Known Answer section. The Known Answer section
3128 // is intended to suppress floods of shared-record replies from many other devices on the network.
3129 // That concept really does not apply to unique records, and indeed if we do send a query for
3130 // which we have a unique record already in our cache, then including that unique record as a
3131 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3133 *ka
= rr
; // Link this record into our known answer chain
3134 ka
= &rr
->NextInKAList
;
3135 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3136 forecast
+= 12 + rr
->resrec
.rdestimate
;
3137 // If we're trying to put more than one question in this packet, and it doesn't fit
3138 // then undo that last question and try again next time
3139 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3141 query
->h
.numQuestions
--;
3142 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3143 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
, query
->h
.numQuestions
);
3144 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3145 while (*ka
) { CacheRecord
*c
= *ka
; *ka
= mDNSNULL
; ka
= &c
->NextInKAList
; }
3146 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3150 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3151 *queryptr
= newptr
; // Update the packet pointer
3152 *answerforecast
= forecast
; // Update the forecast
3153 *kalistptrptr
= ka
; // Update the known answer list pointer
3154 if (ucast
) q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
3156 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // For every resource record in our cache,
3157 if (rr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3158 rr
->NextInKAList
== mDNSNULL
&& ka
!= &rr
->NextInKAList
&& // which is not in the known answer list
3159 SameNameRecordAnswersQuestion(&rr
->resrec
, q
)) // which answers our question
3161 rr
->UnansweredQueries
++; // indicate that we're expecting a response
3162 rr
->LastUnansweredTime
= m
->timenow
;
3163 SetNextCacheCheckTimeForRecord(m
, rr
);
3170 // When we have a query looking for a specified name, but there appear to be no answers with
3171 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3172 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3173 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3174 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3175 // A typical reconfirmation scenario might go like this:
3176 // Depth 0: Name "myhost.local" has no address records
3177 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3178 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3179 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3180 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3181 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3182 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const int depth
)
3187 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth
, name
->c
);
3188 FORALL_CACHERECORDS(slot
, cg
, cr
)
3190 domainname
*crtarget
= GetRRDomainNameTarget(&cr
->resrec
);
3191 if (crtarget
&& cr
->resrec
.rdatahash
== namehash
&& SameDomainName(crtarget
, name
))
3193 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth
, CRDisplayString(m
, cr
));
3194 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
3196 ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, depth
+1);
3201 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3202 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3203 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3204 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3205 mDNSlocal
const CacheRecord
*CacheHasAddressTypeForName(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
3207 CacheGroup
*const cg
= CacheGroupForName(m
, HashSlot(name
), namehash
, name
);
3208 const CacheRecord
*cr
= cg
? cg
->members
: mDNSNULL
;
3209 while (cr
&& !RRTypeIsAddressType(cr
->resrec
.rrtype
)) cr
=cr
->next
;
3214 mDNSlocal
const CacheRecord
*FindSPSInCache1(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*const c0
, const CacheRecord
*const c1
)
3216 #ifndef SPC_DISABLED
3217 CacheGroup
*const cg
= CacheGroupForName(m
, HashSlot(&q
->qname
), q
->qnamehash
, &q
->qname
);
3218 const CacheRecord
*cr
, *bestcr
= mDNSNULL
;
3219 mDNSu32 bestmetric
= 1000000;
3220 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
3221 if (cr
->resrec
.rrtype
== kDNSType_PTR
&& cr
->resrec
.rdlength
>= 6) // If record is PTR type, with long enough name,
3222 if (cr
!= c0
&& cr
!= c1
) // that's not one we've seen before,
3223 if (SameNameRecordAnswersQuestion(&cr
->resrec
, q
)) // and answers our browse query,
3224 if (!IdenticalSameNameRecord(&cr
->resrec
, &m
->SPSRecords
.RR_PTR
.resrec
)) // and is not our own advertised service...
3226 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
3227 if (bestmetric
> metric
) { bestmetric
= metric
; bestcr
= cr
; }
3230 #else // SPC_DISABLED
3237 #endif // SPC_DISABLED
3240 mDNSlocal
void CheckAndSwapSPS(const CacheRecord
**sps1
, const CacheRecord
**sps2
)
3242 const CacheRecord
*swap_sps
;
3243 mDNSu32 metric1
, metric2
;
3245 if (!(*sps1
) || !(*sps2
)) return;
3246 metric1
= SPSMetric((*sps1
)->resrec
.rdata
->u
.name
.c
);
3247 metric2
= SPSMetric((*sps2
)->resrec
.rdata
->u
.name
.c
);
3248 if (!SPSFeatures((*sps1
)->resrec
.rdata
->u
.name
.c
) && SPSFeatures((*sps2
)->resrec
.rdata
->u
.name
.c
) && (metric2
>= metric1
))
3256 mDNSlocal
void ReorderSPSByFeature(const CacheRecord
*sps
[3])
3258 CheckAndSwapSPS(&sps
[0], &sps
[1]);
3259 CheckAndSwapSPS(&sps
[0], &sps
[2]);
3260 CheckAndSwapSPS(&sps
[1], &sps
[2]);
3264 // Finds the three best Sleep Proxies we currently have in our cache
3265 mDNSexport
void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3])
3267 sps
[0] = FindSPSInCache1(m
, q
, mDNSNULL
, mDNSNULL
);
3268 sps
[1] = !sps
[0] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], mDNSNULL
);
3269 sps
[2] = !sps
[1] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], sps
[1]);
3271 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3272 // only if they have equally good metric and support features.
3273 ReorderSPSByFeature(sps
);
3276 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3277 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3280 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3283 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3286 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3289 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3292 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3293 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3294 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3295 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3297 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3298 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3299 if (v4
&& v6
) return(mDNStrue
);
3304 mDNSlocal
void RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3308 // See if we have this one in our list somewhere already
3309 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3311 // If not, find a slot we can re-use
3312 if (i
>= DupSuppressInfoSize
)
3315 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3316 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3320 // Record the info about this query we saw
3322 ds
[i
].InterfaceID
= InterfaceID
;
3326 mDNSlocal
void mDNSSendWakeOnResolve(mDNS
*const m
, DNSQuestion
*q
)
3329 mDNSInterfaceID InterfaceID
= q
->InterfaceID
;
3330 domainname
*d
= &q
->qname
;
3332 // We can't send magic packets without knowing which interface to send it on.
3333 if (InterfaceID
== mDNSInterface_Any
|| LocalOnlyOrP2PInterface(InterfaceID
))
3335 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID
, q
->qname
.c
);
3339 // Split MAC@IPAddress and pass them separately
3342 for (i
= 1; i
< len
; i
++)
3346 char EthAddr
[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3347 char IPAddr
[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3350 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q
->qname
.c
, cnt
);
3353 if ((i
- 1) > (int) (sizeof(EthAddr
) - 1))
3355 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q
->qname
.c
, i
- 1);
3358 if ((len
- i
) > (int)(sizeof(IPAddr
) - 1))
3360 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q
->qname
.c
, len
- i
);
3363 mDNSPlatformMemCopy(EthAddr
, &d
->c
[1], i
- 1);
3365 mDNSPlatformMemCopy(IPAddr
, &d
->c
[i
+ 1], len
- i
);
3366 IPAddr
[len
- i
] = 0;
3367 m
->mDNSStats
.WakeOnResolves
++;
3368 mDNSPlatformSendWakeupPacket(m
, InterfaceID
, EthAddr
, IPAddr
, InitialWakeOnResolveCount
- q
->WakeOnResolveCount
);
3371 else if (d
->c
[i
] == ':')
3374 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q
->qname
.c
);
3378 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3380 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3381 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3384 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3385 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3387 // We forecast: qname (n) type (2) class (2)
3388 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
3389 const mDNSu32 slot
= HashSlot(&q
->qname
);
3390 const CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
3391 const CacheRecord
*rr
;
3392 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
) // If we have a resource record in our cache,
3393 if (rr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3394 SameNameRecordAnswersQuestion(&rr
->resrec
, q
) && // which answers our question
3395 rr
->TimeRcvd
+ TicksTTL(rr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3396 rr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0) // and we'll ask at least once again before NextRequiredQuery
3398 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3399 forecast
+= 12 + rr
->resrec
.rdestimate
;
3400 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3408 // How Standard Queries are generated:
3409 // 1. The Question Section contains the question
3410 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3412 // How Probe Queries are generated:
3413 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3414 // if some other host is already using *any* records with this name, we want to know about it.
3415 // 2. The Authority Section contains the proposed values we intend to use for one or more
3416 // of our records with that name (analogous to the Update section of DNS Update packets)
3417 // because if some other host is probing at the same time, we each want to know what the other is
3418 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3420 mDNSlocal
void SendQueries(mDNS
*const m
)
3428 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3429 mDNSs32 maxExistingQuestionInterval
= 0;
3430 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3431 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3433 // 1. If time for a query, work out what we need to do
3435 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3436 // to their NextRequiredQuery to be worth batching them together with this one
3437 FORALL_CACHERECORDS(slot
, cg
, cr
)
3439 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
3441 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
3443 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
3444 q
= cr
->CRActiveQuestion
;
3445 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(cr
)/20, cr
->resrec
.InterfaceID
);
3446 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3447 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3450 q
->SendQNow
= mDNSInterfaceMark
; // If targeted query, mark it
3452 else if (!mDNSOpaque16IsZero(q
->TargetQID
))
3454 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3455 cr
->UnansweredQueries
++;
3456 m
->mDNSStats
.CacheRefreshQueries
++;
3458 else if (q
->SendQNow
== mDNSNULL
)
3460 q
->SendQNow
= cr
->resrec
.InterfaceID
;
3462 else if (q
->SendQNow
!= cr
->resrec
.InterfaceID
)
3464 q
->SendQNow
= mDNSInterfaceMark
;
3467 // Indicate that this question was marked for sending
3468 // to update an existing cached answer record.
3469 // The browse throttling logic below uses this to determine
3470 // if the query should be sent.
3471 if (mDNSOpaque16IsZero(q
->TargetQID
))
3472 q
->CachedAnswerNeedsUpdate
= mDNStrue
;
3477 // Scan our list of questions to see which:
3478 // *WideArea* queries need to be sent
3479 // *unicast* queries need to be sent
3480 // *multicast* queries we're definitely going to send
3481 if (m
->CurrentQuestion
)
3482 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3483 m
->CurrentQuestion
= m
->Questions
;
3484 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3486 q
= m
->CurrentQuestion
;
3487 if (q
->Target
.type
&& (q
->SendQNow
|| TimeToSendThisQuestion(q
, m
->timenow
)))
3489 mDNSu8
*qptr
= m
->omsg
.data
;
3490 const mDNSu8
*const limit
= m
->omsg
.data
+ sizeof(m
->omsg
.data
);
3492 // 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
3493 if (!q
->LocalSocket
) q
->LocalSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
3496 InitializeDNSMessage(&m
->omsg
.h
, q
->TargetQID
, QueryFlags
);
3497 qptr
= putQuestion(&m
->omsg
, qptr
, limit
, &q
->qname
, q
->qtype
, q
->qclass
);
3498 mDNSSendDNSMessage(m
, &m
->omsg
, qptr
, mDNSInterface_Any
, q
->LocalSocket
, &q
->Target
, q
->TargetPort
, mDNSNULL
, mDNSNULL
, q
->UseBackgroundTrafficClass
);
3499 q
->ThisQInterval
*= QuestionIntervalStep
;
3501 if (q
->ThisQInterval
> MaxQuestionInterval
)
3502 q
->ThisQInterval
= MaxQuestionInterval
;
3503 q
->LastQTime
= m
->timenow
;
3504 q
->LastQTxTime
= m
->timenow
;
3505 q
->RecentAnswerPkts
= 0;
3506 q
->SendQNow
= mDNSNULL
;
3507 q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
3509 else if (mDNSOpaque16IsZero(q
->TargetQID
) && !q
->Target
.type
&& TimeToSendThisQuestion(q
, m
->timenow
))
3511 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3512 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3513 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3514 maxExistingQuestionInterval
= q
->ThisQInterval
;
3516 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3517 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3518 // m->CurrentQuestion point to the right question
3519 if (q
== m
->CurrentQuestion
) m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3521 while (m
->CurrentQuestion
)
3523 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3524 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3526 m
->CurrentQuestion
= mDNSNULL
;
3528 // Scan our list of questions
3529 // (a) to see if there are any more that are worth accelerating, and
3530 // (b) to update the state variables for *all* the questions we're going to send
3531 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3532 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3533 // 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.
3534 m
->NextScheduledQuery
= m
->timenow
+ 0x78000000;
3535 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3537 if (mDNSOpaque16IsZero(q
->TargetQID
)
3538 && (q
->SendQNow
|| (!q
->Target
.type
&& ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
))))
3540 // If at least halfway to next query time, advance to next interval
3541 // If less than halfway to next query time, then
3542 // treat this as logically a repeat of the last transmission, without advancing the interval
3543 if (m
->timenow
- (q
->LastQTime
+ (q
->ThisQInterval
/2)) >= 0)
3545 // If we have reached the answer threshold for this question,
3546 // don't send it again until MaxQuestionInterval unless:
3547 // one of its cached answers needs to be refreshed,
3548 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3549 if (q
->BrowseThreshold
3550 && (q
->CurrentAnswers
>= q
->BrowseThreshold
)
3551 && (q
->CachedAnswerNeedsUpdate
== mDNSfalse
)
3552 && !((q
->flags
& kDNSServiceFlagsThresholdFinder
) && (q
->ThisQInterval
== InitialQuestionInterval
)))
3554 q
->SendQNow
= mDNSNULL
;
3555 q
->ThisQInterval
= MaxQuestionInterval
;
3556 q
->LastQTime
= m
->timenow
;
3557 q
->RequestUnicast
= 0;
3558 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3559 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
3563 // Mark this question for sending on all interfaces
3564 q
->SendQNow
= mDNSInterfaceMark
;
3565 q
->ThisQInterval
*= QuestionIntervalStep
;
3568 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3569 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
/ InitialQuestionInterval
, q
->RequestUnicast
);
3571 if (q
->ThisQInterval
> MaxQuestionInterval
)
3573 q
->ThisQInterval
= MaxQuestionInterval
;
3575 else if (q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* QuestionIntervalStep3
&& !q
->RequestUnicast
&&
3576 !(RRTypeIsAddressType(q
->qtype
) && CacheHasAddressTypeForName(m
, &q
->qname
, q
->qnamehash
)))
3578 // Generally don't need to log this.
3579 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3580 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3581 // and when there simply happen to be no instances of the service the client is looking
3582 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3583 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3584 q
->qname
.c
, DNSTypeName(q
->qtype
));
3585 // Sending third query, and no answers yet; time to begin doubting the source
3586 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
3590 // Mark for sending. (If no active interfaces, then don't even try.)
3591 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3594 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3595 q
->LastQTime
= m
->timenow
;
3598 // If we recorded a duplicate suppression for this question less than half an interval ago,
3599 // then we consider it recent enough that we don't need to do an identical query ourselves.
3600 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3602 q
->LastQTxTime
= m
->timenow
;
3603 q
->RecentAnswerPkts
= 0;
3604 if (q
->RequestUnicast
) q
->RequestUnicast
--;
3606 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3607 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3608 SetNextQueryTime(m
,q
);
3611 // 2. Scan our authoritative RR list to see what probes we might need to send
3613 m
->NextScheduledProbe
= m
->timenow
+ 0x78000000;
3615 if (m
->CurrentRecord
)
3616 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3617 m
->CurrentRecord
= m
->ResourceRecords
;
3618 while (m
->CurrentRecord
)
3620 ar
= m
->CurrentRecord
;
3621 m
->CurrentRecord
= ar
->next
;
3622 if (!AuthRecord_uDNS(ar
) && ar
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3624 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3625 if (m
->timenow
- (ar
->LastAPTime
+ ar
->ThisAPInterval
) < 0)
3627 SetNextAnnounceProbeTime(m
, ar
);
3629 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3630 else if (ar
->ProbeCount
)
3632 if (ar
->AddressProxy
.type
== mDNSAddrType_IPv4
)
3634 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3635 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3636 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3637 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3638 // A similar concern may apply to the NDP Probe too. -- SC
3639 LogSPS("SendQueries ARP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3640 SendARP(m
, 1, ar
, &zerov4Addr
, &zeroEthAddr
, &ar
->AddressProxy
.ip
.v4
, &ar
->WakeUp
.IMAC
);
3642 else if (ar
->AddressProxy
.type
== mDNSAddrType_IPv6
)
3644 LogSPS("SendQueries NDP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3645 // IPv6 source = zero
3646 // No target hardware address
3647 // IPv6 target address is address we're probing
3648 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3649 SendNDP(m
, NDP_Sol
, 0, ar
, &zerov6Addr
, mDNSNULL
, &ar
->AddressProxy
.ip
.v6
, &ar
->WakeUp
.IMAC
);
3651 // Mark for sending. (If no active interfaces, then don't even try.)
3652 ar
->SendRNow
= (!intf
|| ar
->WakeUp
.HMAC
.l
[0]) ? mDNSNULL
: ar
->resrec
.InterfaceID
? ar
->resrec
.InterfaceID
: intf
->InterfaceID
;
3653 ar
->LastAPTime
= m
->timenow
;
3654 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3655 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3656 if (ar
->ProbeCount
> DefaultProbeCountForTypeUnique
)
3657 ar
->ProbeCount
= DefaultProbeCountForTypeUnique
;
3659 SetNextAnnounceProbeTime(m
, ar
);
3660 if (ar
->ProbeCount
== 0)
3662 // If this is the last probe for this record, then see if we have any matching records
3663 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3665 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3666 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, ar
))
3668 // ... then acknowledge this record to the client.
3669 // We do this optimistically, just as we're about to send the third probe.
3670 // This helps clients that both advertise and browse, and want to filter themselves
3671 // from the browse results list, because it helps ensure that the registration
3672 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3673 // A potential downside is that we could deliver a registration confirmation and then find out
3674 // moments later that there's a name conflict, but applications have to be prepared to handle
3675 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3676 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
);
3679 // else, if it has now finished probing, move it to state Verified,
3680 // and update m->NextScheduledResponse so it will be announced
3683 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
); // Defensive, just in case it got missed somehow
3684 ar
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3685 ar
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3686 ar
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3687 SetNextAnnounceProbeTime(m
, ar
);
3691 m
->CurrentRecord
= m
->DuplicateRecords
;
3692 while (m
->CurrentRecord
)
3694 ar
= m
->CurrentRecord
;
3695 m
->CurrentRecord
= ar
->next
;
3696 if (ar
->resrec
.RecordType
== kDNSRecordTypeUnique
&& ar
->ProbeCount
== 0 && !ar
->Acknowledged
)
3697 AcknowledgeRecord(m
, ar
);
3700 // 3. Now we know which queries and probes we're sending,
3701 // go through our interface list sending the appropriate queries on each interface
3704 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
3705 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
3706 mDNSu8
*queryptr
= m
->omsg
.data
;
3707 mDNSBool useBackgroundTrafficClass
= mDNSfalse
; // set if we should use background traffic class
3709 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, QueryFlags
);
3710 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3711 if (!KnownAnswerList
)
3713 // Start a new known-answer list
3714 CacheRecord
**kalistptr
= &KnownAnswerList
;
3715 mDNSu32 answerforecast
= OwnerRecordSpace
+ TraceRecordSpace
; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3717 // Put query questions in this packet
3718 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3720 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
== intf
->InterfaceID
))
3722 mDNSBool Suppress
= mDNSfalse
;
3723 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3724 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3725 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- m
->omsg
.data
, queryptr
+ answerforecast
- m
->omsg
.data
);
3727 // If interface is P2P type, verify that query should be sent over it.
3728 if (!mDNSPlatformValidQuestionForInterface(q
, intf
))
3730 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3732 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3733 else if ((Suppress
= SuppressOnThisInterface(q
->DupSuppress
, intf
)) ||
3734 BuildQuestion(m
, intf
, &m
->omsg
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3736 // We successfully added the question to the packet. Make sure that
3737 // we also send the NSEC3 record if required. BuildQuestion accounted for
3740 // Note: We don't suppress anonymous questions and hence Suppress should always
3744 m
->mDNSStats
.DupQuerySuppressions
++;
3746 if (!Suppress
&& q
->AnonInfo
)
3748 debugf("SendQueries: marking for question %##s, Suppress %d", q
->qname
.c
, Suppress
);
3749 q
->AnonInfo
->SendNow
= intf
->InterfaceID
;
3751 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3752 if (q
->WakeOnResolveCount
)
3754 mDNSSendWakeOnResolve(m
, q
);
3755 q
->WakeOnResolveCount
--;
3758 // use background traffic class if any included question requires it
3759 if (q
->UseBackgroundTrafficClass
)
3761 useBackgroundTrafficClass
= mDNStrue
;
3767 // Put probe questions in this packet
3768 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3770 if (ar
->SendRNow
!= intf
->InterfaceID
)
3773 // If interface is a P2P variant, verify that the probe should be sent over it.
3774 if (!mDNSPlatformValidRecordForInterface(ar
, intf
->InterfaceID
))
3776 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3777 ar
->IncludeInProbe
= mDNSfalse
;
3781 mDNSBool ucast
= (ar
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3782 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3783 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.numQuestions
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3784 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3785 mDNSu32 forecast
= answerforecast
+ 12 + ar
->resrec
.rdestimate
;
3786 mDNSBool putProbe
= mDNStrue
;
3787 mDNSu16 qclass
= ar
->resrec
.rrclass
| ucbit
;
3789 {// Determine if this probe question is already in packet's dns message
3790 const mDNSu8
*questionptr
= m
->omsg
.data
;
3791 DNSQuestion question
;
3793 for (n
= 0; n
< m
->omsg
.h
.numQuestions
&& questionptr
; n
++)
3795 questionptr
= getQuestion(&m
->omsg
, questionptr
, limit
, mDNSInterface_Any
, &question
);
3796 if (questionptr
&& (question
.qtype
== kDNSQType_ANY
) && (question
.qclass
== qclass
) &&
3797 (question
.qnamehash
== ar
->resrec
.namehash
) && SameDomainName(&question
.qname
, ar
->resrec
.name
))
3799 putProbe
= mDNSfalse
; // set to false if already in message
3807 mDNSu8
*newptr
= putQuestion(&m
->omsg
, queryptr
, limit
- forecast
, ar
->resrec
.name
, kDNSQType_ANY
, qclass
);
3811 answerforecast
= forecast
;
3812 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3813 ar
->IncludeInProbe
= mDNStrue
;
3814 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3815 ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
), ar
->ProbeCount
, ar
->resrec
.InterfaceID
, ar
->resrec
.rdestimate
, answerforecast
);
3820 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3821 ar
->IncludeInProbe
= mDNStrue
;
3827 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3828 while (KnownAnswerList
)
3830 CacheRecord
*ka
= KnownAnswerList
;
3831 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- ka
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3832 mDNSu8
*newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAnswers
, &ka
->resrec
, ka
->resrec
.rroriginalttl
- SecsSinceRcvd
,
3833 m
->omsg
.data
+ NormalMaxDNSMessageData
- OwnerRecordSpace
- TraceRecordSpace
);
3836 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3837 ka
->resrec
.name
->c
, DNSTypeName(ka
->resrec
.rrtype
), queryptr
- m
->omsg
.data
, newptr
- m
->omsg
.data
);
3839 KnownAnswerList
= ka
->NextInKAList
;
3840 ka
->NextInKAList
= mDNSNULL
;
3844 // If we ran out of space and we have more than one question in the packet, that's an error --
3845 // we shouldn't have put more than one question if there was a risk of us running out of space.
3846 if (m
->omsg
.h
.numQuestions
> 1)
3847 LogMsg("SendQueries: Put %d answers; No more space for known answers", m
->omsg
.h
.numAnswers
);
3848 m
->omsg
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
3853 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3855 if (ar
->IncludeInProbe
)
3857 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, &ar
->resrec
);
3858 ar
->IncludeInProbe
= mDNSfalse
;
3859 if (newptr
) queryptr
= newptr
;
3860 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m
,ar
));
3864 for (q
= m
->Questions
; q
; q
= q
->next
)
3866 if (q
->AnonInfo
&& q
->AnonInfo
->SendNow
== intf
->InterfaceID
)
3868 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, q
->AnonInfo
->nsec3RR
);
3871 debugf("SendQueries: Added NSEC3 record %s on InterfaceID %p", RRDisplayString(m
, q
->AnonInfo
->nsec3RR
), intf
->InterfaceID
);
3876 LogMsg("SendQueries: ERROR!! Cannot add NSEC3 record %s on InterfaceID %p", RRDisplayString(m
, q
->AnonInfo
->nsec3RR
), intf
->InterfaceID
);
3878 q
->AnonInfo
->SendNow
= mDNSNULL
;
3882 if (queryptr
> m
->omsg
.data
)
3884 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3885 if (OwnerRecordSpace
|| TraceRecordSpace
)
3888 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3889 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3890 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
3891 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3892 if (OwnerRecordSpace
&& TraceRecordSpace
)
3894 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
3895 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
3896 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3897 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
3899 else if (OwnerRecordSpace
)
3901 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3903 else if (TraceRecordSpace
)
3905 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
3907 queryptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAdditionals
,
3908 &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
3911 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3912 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3914 if (queryptr
> m
->omsg
.data
+ NormalMaxDNSMessageData
)
3916 if (m
->omsg
.h
.numQuestions
!= 1 || m
->omsg
.h
.numAnswers
!= 0 || m
->omsg
.h
.numAuthorities
!= 1 || m
->omsg
.h
.numAdditionals
!= 1)
3917 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "",
3918 TraceRecordSpace
? "TRACER" : "", m
->omsg
.data
, m
->omsg
.data
+ NormalMaxDNSMessageData
, queryptr
, m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
,
3919 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3923 if ((m
->omsg
.h
.flags
.b
[0] & kDNSFlag0_TC
) && m
->omsg
.h
.numQuestions
> 1)
3924 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m
->omsg
.h
.numQuestions
);
3925 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %p",
3926 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
3927 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
3928 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAuthorities
== 1 ? "" : "s", intf
->InterfaceID
);
3929 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, useBackgroundTrafficClass
);
3930 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSNULL
, useBackgroundTrafficClass
);
3931 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
3932 if (++pktcount
>= 1000)
3933 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
3934 // There might be more records left in the known answer list, or more questions to send
3935 // on this interface, so go around one more time and try again.
3937 else // Nothing more to send on this interface; go to next
3939 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3940 #if MDNS_DEBUGMSGS && 0
3941 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
3942 debugf(msg
, intf
, next
);
3948 // 4. Final housekeeping
3950 // 4a. Debugging check: Make sure we announced all our records
3951 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3954 if (ar
->ARType
!= AuthRecordLocalOnly
&& ar
->ARType
!= AuthRecordP2P
)
3955 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
3956 (uint32_t)ar
->SendRNow
, (uint32_t)ar
->resrec
.InterfaceID
, ARDisplayString(m
, ar
));
3957 ar
->SendRNow
= mDNSNULL
;
3960 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3961 // that their interface which went away might come back again, the logic will want to send queries
3962 // for those records, but we can't because their interface isn't here any more, so to keep the
3963 // state machine ticking over we just pretend we did so.
3964 // If the interface does not come back in time, the cache record will expire naturally
3965 FORALL_CACHERECORDS(slot
, cg
, cr
)
3967 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
3969 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
3971 cr
->UnansweredQueries
++;
3972 cr
->CRActiveQuestion
->SendQNow
= mDNSNULL
;
3973 SetNextCacheCheckTimeForRecord(m
, cr
);
3978 // 4c. Debugging check: Make sure we sent all our planned questions
3979 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3980 // we legitimately couldn't send because the interface is no longer available
3981 for (q
= m
->Questions
; q
; q
=q
->next
)
3986 for (x
= m
->NewQuestions
; x
; x
=x
->next
) if (x
== q
) break; // Check if this question is a NewQuestion
3987 // There will not be an active interface for questions applied to mDNSInterface_BLE
3988 // so don't log the warning in that case.
3989 if (q
->InterfaceID
!= mDNSInterface_BLE
)
3990 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
3991 (uint32_t)q
->SendQNow
, x
? "new" : "old", (uint32_t)q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3992 q
->SendQNow
= mDNSNULL
;
3994 q
->CachedAnswerNeedsUpdate
= mDNSfalse
;
3998 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
)
4002 mDNSu8
*ptr
= m
->omsg
.data
;
4003 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
4004 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID
); return; }
4006 // 0x00 Destination address
4007 for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4009 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4010 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
4012 // 0x0C Ethertype (0x0842)
4016 // 0x0E Wakeup sync sequence
4017 for (i
=0; i
<6; i
++) *ptr
++ = 0xFF;
4020 for (j
=0; j
<16; j
++) for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4023 for (i
=0; i
<6; i
++) *ptr
++ = password
->b
[i
];
4025 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4029 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4030 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4031 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4032 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4033 // So, we send one of each, unicast first, then broadcast second.
4034 for (i
=0; i
<6; i
++) m
->omsg
.data
[i
] = 0xFF;
4035 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4039 // ***************************************************************************
4040 #if COMPILER_LIKES_PRAGMA_MARK
4042 #pragma mark - RR List Management & Task Management
4045 // Whenever a question is answered, reset its state so that we don't query
4046 // the network repeatedly. This happens first time when we answer the question and
4047 // and later when we refresh the cache.
4048 mDNSlocal
void ResetQuestionState(mDNS
*const m
, DNSQuestion
*q
)
4050 q
->LastQTime
= m
->timenow
;
4051 q
->LastQTxTime
= m
->timenow
;
4052 q
->RecentAnswerPkts
= 0;
4053 q
->ThisQInterval
= MaxQuestionInterval
;
4054 q
->RequestUnicast
= 0;
4055 // Reset unansweredQueries so that we don't penalize this server later when we
4056 // start sending queries when the cache expires.
4057 q
->unansweredQueries
= 0;
4058 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4061 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4062 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4063 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4064 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4065 mDNSexport
void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
)
4067 DNSQuestion
*const q
= m
->CurrentQuestion
;
4068 const mDNSBool followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
4070 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
4071 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", rr
->resrec
.rroriginalttl
, CRDisplayString(m
, rr
));
4073 // When the response for the question was validated, the entire rrset was validated. If we deliver
4074 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
4075 // in the future, we will do the revalidation again.
4077 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
4078 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
4079 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
4080 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
4081 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
4082 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
4083 // a real negative response, we would reset the state here and validate the results at the end of this function.
4084 // or the real response again if we purge the cache.
4085 if (q
->ValidationRequired
&& ((AddRecord
== QC_rmv
) ||
4086 (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
&& (AddRecord
== QC_add
))))
4088 q
->ValidationStatus
= 0;
4089 q
->ValidationState
= DNSSECValRequired
;
4092 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4093 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4094 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4095 // we check to see if that query already has a unique local answer.
4096 if (q
->LOAddressAnswers
)
4098 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4099 "LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
),
4100 q
->LOAddressAnswers
);
4104 if (QuerySuppressed(q
))
4106 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4107 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4108 // that are timing out, which we know are answered with negative cache record when timing out.
4109 if (!q
->TimeoutQuestion
|| rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| (m
->timenow
- q
->StopTime
< 0))
4113 #if TARGET_OS_EMBEDDED
4114 if ((AddRecord
== QC_add
) && Question_uDNS(q
) && !followcname
)
4116 const domainname
* queryName
;
4117 mDNSu32 responseLatencyMs
;
4118 mDNSBool isForCellular
;
4120 queryName
= q
->metrics
.originalQName
? q
->metrics
.originalQName
: &q
->qname
;
4121 isForCellular
= (q
->qDNSServer
&& q
->qDNSServer
->cellIntf
);
4122 if (!q
->metrics
.answered
)
4124 if (q
->metrics
.querySendCount
> 0)
4126 responseLatencyMs
= ((m
->timenow
- q
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
4130 responseLatencyMs
= 0;
4133 MetricsUpdateUDNSQueryStats(queryName
, q
->qtype
, &rr
->resrec
, q
->metrics
.querySendCount
, responseLatencyMs
, isForCellular
);
4134 q
->metrics
.answered
= mDNStrue
;
4136 if (q
->metrics
.querySendCount
> 0)
4138 MetricsUpdateUDNSResolveStats(queryName
, &rr
->resrec
, isForCellular
);
4142 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4143 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4144 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4146 rr
->LastUsed
= m
->timenow
;
4147 if (AddRecord
== QC_add
&& !q
->DuplicateOf
&& rr
->CRActiveQuestion
!= q
)
4149 if (!rr
->CRActiveQuestion
) m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4150 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4151 rr
->CRActiveQuestion
, q
, CRDisplayString(m
,rr
), q
->CurrentAnswers
);
4152 rr
->CRActiveQuestion
= q
; // We know q is non-null
4153 SetNextCacheCheckTimeForRecord(m
, rr
);
4157 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4158 // (b) a normal add, where we have at least one unique-type answer,
4159 // then there's no need to keep polling the network.
4160 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4161 // We do this for mDNS questions and uDNS one-shot questions, but not for
4162 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4163 if ((AddRecord
== QC_addnocache
&& !q
->RequestUnicast
) ||
4164 (AddRecord
== QC_add
&& (q
->ExpectUnique
|| (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))))
4165 if (ActiveQuestion(q
) && (mDNSOpaque16IsZero(q
->TargetQID
) || !q
->LongLived
))
4167 ResetQuestionState(m
, q
);
4170 if (rr
->DelayDelivery
) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4173 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) // If negative answer, check if we need to try Punycode conversion
4176 if (PerformNextPunycodeConversion(q
, &newname
)) // Itertative Punycode conversion succeeded, so reissue question with new name
4178 UDPSocket
*const sock
= q
->LocalSocket
; // Save old socket and transaction ID
4179 const mDNSOpaque16 id
= q
->TargetQID
;
4180 q
->LocalSocket
= mDNSNULL
;
4181 mDNS_StopQuery_internal(m
, q
); // Stop old query
4182 AssignDomainName(&q
->qname
, &newname
); // Update qname
4183 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
4184 mDNS_StartQuery_internal(m
, q
); // Start new query
4186 if (sock
) // Transplant saved socket, if appropriate
4188 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
4189 else { q
->LocalSocket
= sock
; q
->TargetQID
= id
; }
4191 return; // All done for now; wait until we get the next answer
4194 #endif // USE_LIBIDN
4196 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4197 // for the purpose of retrying search domains/timeout OR the question is suppressed
4198 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
|| (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
)))
4199 if (!AddRecord
|| (AddRecord
!= QC_suppressed
&& AddRecord
!= QC_forceresponse
&& !q
->ReturnIntermed
)) return;
4201 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4202 if (q
->QuestionCallback
&& !q
->NoAnswer
&& (!followcname
|| q
->ReturnIntermed
))
4204 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4205 if (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
))
4208 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->qDNSServer
);
4209 q
->QuestionCallback(m
, q
, &neg
.resrec
, AddRecord
);
4212 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4213 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4215 // If this is an "Add" operation and this question needs validation, validate the response.
4216 // In the case of negative responses, extra care should be taken. Negative cache records are
4217 // used for many purposes. For example,
4219 // 1) Suppressing questions (SuppressUnusable)
4220 // 2) Timeout questions
4221 // 3) The name does not exist
4222 // 4) No DNS servers are available and we need a quick response for the application
4224 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4225 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4226 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4227 // signature for (4) and hence the explicit check for q->qDNSServer.
4229 if (m
->CurrentQuestion
== q
&& (AddRecord
== QC_add
) && !q
->ValidatingResponse
&& q
->ValidationRequired
&&
4230 q
->ValidationState
== DNSSECValRequired
&& q
->qDNSServer
)
4232 q
->ValidationState
= DNSSECValInProgress
;
4233 // Treat it as callback call as that's what dnssec code expects
4234 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4235 VerifySignature(m
, mDNSNULL
, q
);
4236 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4240 // Note: Proceed with caution here because client callback function is allowed to do anything,
4241 // including starting/stopping queries, registering/deregistering records, etc.
4243 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4244 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4245 // first before following it
4246 if ((m
->CurrentQuestion
== q
) && followcname
&& !ValidatingQuestion(q
))
4247 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
4250 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*rr
)
4252 rr
->DelayDelivery
= 0;
4253 if (m
->CurrentQuestion
)
4254 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4255 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4256 m
->CurrentQuestion
= m
->Questions
;
4257 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4259 DNSQuestion
*q
= m
->CurrentQuestion
;
4260 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4261 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
4262 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4263 m
->CurrentQuestion
= q
->next
;
4265 m
->CurrentQuestion
= mDNSNULL
;
4268 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSu32 slot
, mDNSBool
*purge
)
4270 const mDNSs32 threshhold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
4271 const mDNSs32 start
= m
->timenow
- 0x10000000;
4272 mDNSs32 delay
= start
;
4273 CacheGroup
*cg
= CacheGroupForName(m
, slot
, namehash
, name
);
4274 const CacheRecord
*rr
;
4278 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4280 // If there are records that will expire soon, there are cases that need delayed
4281 // delivery of events:
4283 // 1) A new cache entry is about to be added as a replacement. The caller needs to
4284 // deliver a RMV (for the current old entry) followed by ADD (for the new entry).
4285 // It needs to schedule the timer for the next cache expiry (ScheduleNextCacheCheckTime),
4286 // so that the cache entry can be purged (purging causes the RMV followed by ADD)
4288 // 2) A new question is about to be answered and the caller needs to know whether it's
4289 // scheduling should be delayed so that the question is not answered with this record.
4290 // Instead of delivering an ADD (old entry) followed by RMV (old entry) and another ADD
4291 // (new entry), a single ADD can be delivered by delaying the scheduling of the question
4294 // When the unicast cache record is created, it's TTL has been extended beyond its value
4295 // given in the resource record (See RRAdjustTTL). If it is in the "extended" time, the
4296 // cache is already expired and we set "purge" to indicate that. When "purge" is set, the
4297 // return value of the function should be ignored by the callers.
4299 // Note: For case (1), "purge" argument is NULL and hence the following checks are skipped.
4300 // It is okay to skip in that case because the cache records have been set to expire almost
4301 // immediately and the extended time does not apply.
4303 // Also, if there is already an active question we don't try to optimize as purging the cache
4304 // would end up delivering RMV for the active question and hence we avoid that.
4306 if (purge
&& !rr
->resrec
.InterfaceID
&& !rr
->CRActiveQuestion
&& rr
->resrec
.rroriginalttl
)
4308 mDNSu32 uTTL
= RRUnadjustedTTL(rr
->resrec
.rroriginalttl
);
4309 if (m
->timenow
- (rr
->TimeRcvd
+ ((mDNSs32
)uTTL
* mDNSPlatformOneSecond
)) >= 0)
4311 LogInfo("CheckForSoonToExpireRecords: %s: rroriginalttl %u, unadjustedTTL %u, currentTTL %u",
4312 CRDisplayString(m
, rr
), rr
->resrec
.rroriginalttl
, uTTL
, (m
->timenow
- rr
->TimeRcvd
)/mDNSPlatformOneSecond
);
4317 if (threshhold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
4319 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
4320 delay
= RRExpireTime(rr
);
4323 if (delay
- start
> 0)
4324 return(NonZeroTime(delay
));
4329 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4330 // If new questions are created as a result of invoking client callbacks, they will be added to
4331 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4332 // rr is a new CacheRecord just received into our cache
4333 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4334 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4335 // which may change the record list and/or question list.
4336 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4337 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*rr
)
4341 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4342 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4343 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
4345 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4347 // If this question is one that's actively sending queries, and it's received ten answers within one
4348 // second of sending the last query packet, then that indicates some radical network topology change,
4349 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4350 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4351 // because we will anyway send another query within a few seconds. The first reset query is sent out
4352 // randomized over the next four seconds to reduce possible synchronization between machines.
4353 if (q
->LastAnswerPktNum
!= m
->PktNum
)
4355 q
->LastAnswerPktNum
= m
->PktNum
;
4356 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
4357 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4359 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4360 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
4361 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4362 q
->ThisQInterval
= InitialQuestionInterval
;
4363 SetNextQueryTime(m
,q
);
4366 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr
, rr
->resrec
.name
->c
,
4367 DNSTypeName(rr
->resrec
.rrtype
), rr
->resrec
.rroriginalttl
, rr
->resrec
.rDNSServer
?
4368 &rr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(rr
->resrec
.rDNSServer
?
4369 rr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
4370 q
->CurrentAnswers
++;
4372 q
->unansweredQueries
= 0;
4373 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4374 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4375 if (q
->CurrentAnswers
> 4000)
4377 static int msgcount
= 0;
4378 if (msgcount
++ < 10)
4379 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4380 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
4381 rr
->resrec
.rroriginalttl
= 0;
4382 rr
->UnansweredQueries
= MaxUnansweredQueries
;
4387 if (!rr
->DelayDelivery
)
4389 if (m
->CurrentQuestion
)
4390 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4391 m
->CurrentQuestion
= m
->Questions
;
4392 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4394 q
= m
->CurrentQuestion
;
4395 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4396 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
4397 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4398 m
->CurrentQuestion
= q
->next
;
4400 m
->CurrentQuestion
= mDNSNULL
;
4403 SetNextCacheCheckTimeForRecord(m
, rr
);
4406 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4407 // If new questions are created as a result of invoking client callbacks, they will be added to
4408 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4409 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4410 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4411 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4412 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4413 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4414 // which may change the record list and/or question list.
4415 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4416 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*rr
)
4418 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
4419 if (m
->CurrentQuestion
)
4420 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4421 m
->CurrentQuestion
= m
->Questions
;
4422 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4423 // since we're not caching the record and we'll get no opportunity to do this later
4424 while (m
->CurrentQuestion
)
4426 DNSQuestion
*q
= m
->CurrentQuestion
;
4427 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4428 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
4429 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4430 m
->CurrentQuestion
= q
->next
;
4432 m
->CurrentQuestion
= mDNSNULL
;
4435 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4436 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4437 // If new questions are created as a result of invoking client callbacks, they will be added to
4438 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4439 // rr is an existing cache CacheRecord that just expired and is being deleted
4440 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4441 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4442 // which may change the record list and/or question list.
4443 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4444 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*rr
)
4446 if (m
->CurrentQuestion
)
4447 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4448 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4449 m
->CurrentQuestion
= m
->Questions
;
4451 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4452 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4453 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4455 DNSQuestion
*q
= m
->CurrentQuestion
;
4456 // When a question enters suppressed state, we generate RMV events and generate a negative
4457 // response. A cache may be present that answers this question e.g., cache entry generated
4458 // before the question became suppressed. We need to skip the suppressed questions here as
4459 // the RMV event has already been generated.
4460 if (!QuerySuppressed(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4462 verbosedebugf("CacheRecordRmv %p %s", rr
, CRDisplayString(m
, rr
));
4463 q
->FlappingInterface1
= mDNSNULL
;
4464 q
->FlappingInterface2
= mDNSNULL
;
4466 if (q
->CurrentAnswers
== 0)
4467 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4468 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
4469 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
4472 q
->CurrentAnswers
--;
4473 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4474 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4477 // If we have dropped below the answer threshold for this mDNS question,
4478 // restart the queries at InitialQuestionInterval.
4479 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->BrowseThreshold
> 0) && (q
->CurrentAnswers
< q
->BrowseThreshold
))
4481 q
->ThisQInterval
= InitialQuestionInterval
;
4482 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4483 SetNextQueryTime(m
,q
);
4484 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4485 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
4487 if (rr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
4489 if (q
->CurrentAnswers
== 0)
4491 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4492 q
->qname
.c
, DNSTypeName(q
->qtype
));
4493 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, 0);
4495 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
4498 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4499 m
->CurrentQuestion
= q
->next
;
4501 m
->CurrentQuestion
= mDNSNULL
;
4504 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
4506 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
4508 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
4510 e
->next
= m
->rrcache_free
;
4511 m
->rrcache_free
= e
;
4512 m
->rrcache_totalused
--;
4515 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
4517 CacheEntity
*e
= (CacheEntity
*)(*cp
);
4518 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4519 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
4520 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4521 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4522 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4523 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
4524 (*cp
)->name
= mDNSNULL
;
4525 *cp
= (*cp
)->next
; // Cut record from list
4526 ReleaseCacheEntity(m
, e
);
4529 mDNSlocal
void ReleaseAdditionalCacheRecords(mDNS
*const m
, CacheRecord
**rp
)
4533 CacheRecord
*rr
= *rp
;
4534 *rp
= (*rp
)->next
; // Cut record from list
4535 if (rr
->resrec
.rdata
&& rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
)
4537 mDNSPlatformMemFree(rr
->resrec
.rdata
);
4538 rr
->resrec
.rdata
= mDNSNULL
;
4540 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4541 // of the CacheGroup.
4542 if (rr
->resrec
.name
)
4544 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
4545 mDNSPlatformMemFree((void *)rr
->resrec
.name
);
4546 rr
->resrec
.name
= mDNSNULL
;
4548 // Don't count the NSEC3 records used by anonymous browse/reg
4549 if (!rr
->resrec
.InterfaceID
)
4551 m
->rrcache_totalused_unicast
-= rr
->resrec
.rdlength
;
4552 if (DNSSECRecordType(rr
->resrec
.rrtype
))
4553 BumpDNSSECStats(m
, kStatsActionDecrement
, kStatsTypeMemoryUsage
, rr
->resrec
.rdlength
);
4555 ReleaseCacheEntity(m
, (CacheEntity
*)rr
);
4559 mDNSexport
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
4562 const mDNSu32 slot
= HashSlot(r
->resrec
.name
);
4564 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4565 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
4566 r
->resrec
.rdata
= mDNSNULL
;
4568 cg
= CacheGroupForRecord(m
, slot
, &r
->resrec
);
4572 // It is okay to have this printed for NSEC/NSEC3s
4573 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4575 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4576 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4577 // (which is handled below) and in that case it should be freed here.
4578 if (r
->resrec
.name
&& cg
&& r
->resrec
.name
!= cg
->name
)
4580 debugf("ReleaseCacheRecord: freeing %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4581 mDNSPlatformMemFree((void *)r
->resrec
.name
);
4583 r
->resrec
.name
= mDNSNULL
;
4585 if (r
->resrec
.AnonInfo
)
4587 debugf("ReleaseCacheRecord: freeing AnonInfo for %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4588 FreeAnonInfo((void *)r
->resrec
.AnonInfo
);
4590 r
->resrec
.AnonInfo
= mDNSNULL
;
4592 if (!r
->resrec
.InterfaceID
)
4594 m
->rrcache_totalused_unicast
-= r
->resrec
.rdlength
;
4595 if (DNSSECRecordType(r
->resrec
.rrtype
))
4596 BumpDNSSECStats(m
, kStatsActionDecrement
, kStatsTypeMemoryUsage
, r
->resrec
.rdlength
);
4599 ReleaseAdditionalCacheRecords(m
, &r
->nsec
);
4600 ReleaseAdditionalCacheRecords(m
, &r
->soa
);
4602 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
4605 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4606 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4607 // callbacks for old records are delivered before callbacks for newer records.
4608 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
4610 CacheRecord
**rp
= &cg
->members
;
4612 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4613 m
->lock_rrcache
= 1;
4617 CacheRecord
*const rr
= *rp
;
4618 mDNSs32 event
= RRExpireTime(rr
);
4619 if (m
->timenow
- event
>= 0) // If expired, delete it
4621 *rp
= rr
->next
; // Cut it from the list
4623 verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
4624 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4625 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4627 DNSQuestion
*q
= rr
->CRActiveQuestion
;
4628 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4629 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4630 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4631 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4632 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4633 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4634 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4635 if (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
&& ActiveQuestion(q
))
4637 q
->ThisQInterval
= InitialQuestionInterval
;
4638 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4639 SetNextQueryTime(m
, q
);
4641 CacheRecordRmv(m
, rr
);
4642 m
->rrcache_active
--;
4644 ReleaseCacheRecord(m
, rr
);
4646 else // else, not expired; see if we need to query
4648 // If waiting to delay delivery, do nothing until then
4649 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
4650 event
= rr
->DelayDelivery
;
4653 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
4654 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4656 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4657 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
4658 else // else trigger our question to go out now
4660 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4661 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4662 m
->NextScheduledQuery
= m
->timenow
;
4663 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4664 // which will correctly update m->NextCacheCheck for us.
4665 event
= m
->timenow
+ 0x3FFFFFFF;
4669 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4670 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
4671 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
4672 m
->rrcache_nextcheck
[slot
] = event
;
4676 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
4677 cg
->rrcache_tail
= rp
;
4678 m
->lock_rrcache
= 0;
4681 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4683 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4684 // returns true if there is an answer.
4686 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4687 // returns true to indicate the same.
4688 mDNSlocal mDNSBool
AnswerQuestionWithLORecord(mDNS
*const m
, DNSQuestion
*q
, mDNSBool checkOnly
)
4694 if (m
->CurrentRecord
)
4695 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4697 slot
= AuthHashSlot(&q
->qname
);
4698 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
4701 m
->CurrentRecord
= ag
->members
;
4702 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
4704 AuthRecord
*rr
= m
->CurrentRecord
;
4705 m
->CurrentRecord
= rr
->next
;
4707 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4708 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4710 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4711 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4712 // we handle both mDNSInterface_Any and scoped questions.
4714 if (rr
->ARType
== AuthRecordLocalOnly
|| (rr
->ARType
== AuthRecordP2P
&& (q
->InterfaceID
== mDNSInterface_Any
|| q
->InterfaceID
== mDNSInterface_BLE
)))
4715 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
4719 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q
->qname
.c
, DNSTypeName(q
->qtype
),
4720 ARDisplayString(m
, rr
));
4721 m
->CurrentRecord
= mDNSNULL
;
4724 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, mDNStrue
);
4725 if (m
->CurrentQuestion
!= q
)
4726 break; // If callback deleted q, then we're finished here
4730 m
->CurrentRecord
= mDNSNULL
;
4732 if (m
->CurrentQuestion
!= q
)
4734 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4738 if (q
->LOAddressAnswers
)
4740 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4741 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4745 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4746 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4747 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4748 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4749 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4752 lr
= ag
->NewLocalOnlyRecords
;
4755 if (UniqueLocalOnlyRecord(lr
) && LocalOnlyRecordAnswersQuestion(lr
, q
))
4757 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4758 " LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4767 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4768 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4769 // DNS requests. We need to temporarily suspend the suppress status so that we can
4770 // deliver a negative response (AnswerCurrentQuestionWithResourceRecord does not answer
4771 // suppressed questions) and reset it back. In the future, if there are other
4772 // reasons for suppressing the query, this function should be updated.
4773 mDNSlocal
void AnswerSuppressedQuestion(mDNS
*const m
, DNSQuestion
*q
)
4775 mDNSBool SuppressQuery
= q
->SuppressQuery
;
4776 mDNSBool DisallowPID
= q
->DisallowPID
;
4778 // make sure that QuerySuppressed() returns false
4779 q
->SuppressQuery
= mDNSfalse
;
4780 q
->DisallowPID
= mDNSfalse
;
4782 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_suppressed
);
4784 q
->SuppressQuery
= SuppressQuery
;
4785 q
->DisallowPID
= DisallowPID
;
4788 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4790 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4791 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
4792 mDNSu32 slot
= HashSlot(&q
->qname
);
4793 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
4794 mDNSBool AnsweredFromCache
= mDNSfalse
;
4796 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4798 if (cg
) CheckCacheExpiration(m
, slot
, cg
);
4799 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
4800 m
->NewQuestions
= q
->next
;
4801 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4802 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4804 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4805 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4806 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4807 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4808 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4809 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4810 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4811 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4813 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4814 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4815 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4816 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4818 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4819 // This should be safe, because calling the client's question callback may cause the
4820 // question list to be modified, but should not ever cause the rrcache list to be modified.
4821 // If the client's question callback deletes the question, then m->CurrentQuestion will
4822 // be advanced, and we'll exit out of the loop
4823 m
->lock_rrcache
= 1;
4824 if (m
->CurrentQuestion
)
4825 LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4826 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4827 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4829 if (q
->NoAnswer
== NoAnswer_Fail
)
4831 LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4832 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
4833 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
4834 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
4835 // Don't touch the question if it has been stopped already
4836 if (m
->CurrentQuestion
== q
) q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
4837 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4840 if (m
->CurrentQuestion
!= q
)
4842 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4846 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4847 // or P2P record, then we are done.
4848 if (AnswerQuestionWithLORecord(m
, q
, mDNSfalse
))
4851 // If we are not supposed to answer this question, generate a negative response.
4852 // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4854 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4855 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4856 // the question out.
4857 if (QuerySuppressed(q
))
4859 AnswerSuppressedQuestion(m
, q
);
4861 else if (!q
->ValidatingResponse
)
4864 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4865 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
4867 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4868 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- rr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
4869 if (rr
->resrec
.rroriginalttl
<= SecsSinceRcvd
)
4871 LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
4872 rr
->resrec
.rroriginalttl
, SecsSinceRcvd
, CRDisplayString(m
, rr
), m
->timenow
, rr
->TimeRcvd
);
4873 continue; // Go to next one in loop
4876 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4877 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4878 if ((rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
4879 ShouldQueryImmediately
= mDNSfalse
;
4880 q
->CurrentAnswers
++;
4881 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4882 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4883 AnsweredFromCache
= mDNStrue
;
4884 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_add
);
4885 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4887 else if (mDNSOpaque16IsZero(q
->TargetQID
) && RRTypeIsAddressType(rr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
4888 ShouldQueryImmediately
= mDNSfalse
;
4890 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4891 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4892 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
4894 // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4895 // with search domains, generate a negative response which will now retry after appending search domains.
4896 // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4897 // we will retry with search domains.
4898 if (!QuerySuppressed(q
) && !AnsweredFromCache
&& q
->RetryWithSearchDomains
)
4900 LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4901 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_forceresponse
);
4904 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit
; }
4906 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4907 // Hence we don't execute the following block of code for those cases.
4908 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
4910 debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4911 q
->ThisQInterval
= InitialQuestionInterval
;
4912 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4913 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
4915 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4916 if (!m
->RandomQueryDelay
)
4917 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
4918 q
->LastQTime
+= m
->RandomQueryDelay
;
4922 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
4923 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
4924 // answers for this question until *after* its scheduled transmission time, in which case
4925 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
4926 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
4927 SetNextQueryTime(m
,q
);
4930 m
->CurrentQuestion
= mDNSNULL
;
4931 m
->lock_rrcache
= 0;
4934 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
4935 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
4936 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
4940 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
4941 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
4942 mDNSBool retEv
= mDNSfalse
;
4944 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4946 if (m
->CurrentQuestion
)
4947 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4948 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4949 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4951 if (m
->CurrentRecord
)
4952 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4954 // 1. First walk the LocalOnly records answering the LocalOnly question
4955 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
4956 // walk the ResourceRecords list delivering the answers
4957 slot
= AuthHashSlot(&q
->qname
);
4958 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
4961 m
->CurrentRecord
= ag
->members
;
4962 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
4964 AuthRecord
*rr
= m
->CurrentRecord
;
4965 m
->CurrentRecord
= rr
->next
;
4966 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
4969 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, mDNStrue
);
4970 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4975 if (m
->CurrentQuestion
== q
)
4977 m
->CurrentRecord
= m
->ResourceRecords
;
4979 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
4981 AuthRecord
*rr
= m
->CurrentRecord
;
4982 m
->CurrentRecord
= rr
->next
;
4983 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
4986 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, mDNStrue
);
4987 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
4992 // The local host is the authoritative source for LocalOnly questions
4993 // so if no records exist and client requested intermediates, then generate a negative response
4994 if (!retEv
&& (m
->CurrentQuestion
== q
) && q
->ReturnIntermed
)
4995 GenerateNegativeResponse(m
, mDNSInterface_LocalOnly
, QC_forceresponse
);
4997 m
->CurrentQuestion
= mDNSNULL
;
4998 m
->CurrentRecord
= mDNSNULL
;
5001 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
5003 CacheEntity
*e
= mDNSNULL
;
5005 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
5006 m
->lock_rrcache
= 1;
5008 // If we have no free records, ask the client layer to give us some more memory
5009 if (!m
->rrcache_free
&& m
->MainCallback
)
5011 if (m
->rrcache_totalused
!= m
->rrcache_size
)
5012 LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
5013 m
->rrcache_totalused
, m
->rrcache_size
);
5015 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5016 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5017 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5018 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5019 // and recycle them, instead of allocating more memory.
5020 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
5021 LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
5022 m
->rrcache_size
, m
->rrcache_active
);
5025 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5026 m
->MainCallback(m
, mStatus_GrowCache
);
5027 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5031 // If we still have no free records, recycle all the records we can.
5032 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5033 if (!m
->rrcache_free
)
5035 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
5037 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5039 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5042 CacheRecord
**rp
= &(*cp
)->members
;
5045 // Records that answer still-active questions are not candidates for recycling
5046 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5047 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
5051 CacheRecord
*rr
= *rp
;
5052 *rp
= (*rp
)->next
; // Cut record from list
5053 ReleaseCacheRecord(m
, rr
);
5056 if ((*cp
)->rrcache_tail
!= rp
)
5057 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
5058 (*cp
)->rrcache_tail
= rp
;
5059 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
5060 else ReleaseCacheGroup(m
, cp
);
5063 LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
5064 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
5067 if (m
->rrcache_free
) // If there are records in the free list, take one
5069 e
= m
->rrcache_free
;
5070 m
->rrcache_free
= e
->next
;
5071 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
5073 LogInfo("RR Cache now using %ld objects", m
->rrcache_totalused
);
5074 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
5075 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
5076 else m
->rrcache_report
+= 1000;
5078 mDNSPlatformMemZero(e
, sizeof(*e
));
5081 m
->lock_rrcache
= 0;
5086 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
5088 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
5091 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
5092 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
5094 r
->resrec
.rdata
= (RData
*)mDNSPlatformMemAllocate(sizeofRDataHeader
+ RDLength
);
5095 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
5096 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
5102 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
5104 mDNSu16 namelen
= DomainNameLength(rr
->name
);
5105 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
5106 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
5107 cg
->next
= m
->rrcache_hash
[slot
];
5108 cg
->namehash
= rr
->namehash
;
5109 cg
->members
= mDNSNULL
;
5110 cg
->rrcache_tail
= &cg
->members
;
5111 if (namelen
> sizeof(cg
->namestorage
))
5112 cg
->name
= mDNSPlatformMemAllocate(namelen
);
5114 cg
->name
= (domainname
*)cg
->namestorage
;
5117 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
5118 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
5121 AssignDomainName(cg
->name
, rr
->name
);
5123 if (CacheGroupForRecord(m
, slot
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
5124 m
->rrcache_hash
[slot
] = cg
;
5125 if (CacheGroupForRecord(m
, slot
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
5130 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
5134 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5135 // a positive answer using an expired record (e.g. from an interface that has gone away).
5136 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5137 // summary deletion without giving the proper callback to any questions that are monitoring it.
5138 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5139 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
5140 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5141 rr
->resrec
.rroriginalttl
= 0;
5142 SetNextCacheCheckTimeForRecord(m
, rr
);
5145 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
5148 mDNSPlatformLock(m
);
5151 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5152 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
5155 if (m
->timenow
) time
= m
->timenow
;
5156 else time
= mDNS_TimeNow_NoLock(m
);
5157 mDNSPlatformUnlock(m
);
5161 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5162 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5163 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5164 #define SetSPSProxyListChanged(X) do { \
5165 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
5166 m->SPSProxyListChanged = (X); } while(0)
5168 // Called from mDNS_Execute() to expire stale proxy records
5169 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
5171 m
->CurrentRecord
= list
;
5172 while (m
->CurrentRecord
)
5174 AuthRecord
*rr
= m
->CurrentRecord
;
5175 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
5177 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5178 // so we need to cease proxying for *all* records we may have, expired or not.
5179 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
5181 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
5182 m
->NextScheduledSPS
= rr
->TimeExpire
;
5184 else // else proxy record expired, so remove it
5186 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5187 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
5188 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
5189 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
5190 // Don't touch rr after this -- memory may have been free'd
5193 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5194 // new records could have been added to the end of the list as a result of that call.
5195 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
5196 m
->CurrentRecord
= rr
->next
;
5200 mDNSlocal
void CheckRmvEventsForLocalRecords(mDNS
*const m
)
5202 while (m
->CurrentRecord
)
5204 AuthRecord
*rr
= m
->CurrentRecord
;
5205 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
5207 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m
, rr
));
5208 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
5209 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNSfalse
);
5210 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
5212 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
5213 rr
->AnsweredLocalQ
= mDNSfalse
;
5214 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5215 // For LocalOnly records, we don't do that and hence we need to do that here.
5216 if (RRLocalOnly(rr
)) CompleteDeregistration(m
, rr
);
5219 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5220 m
->CurrentRecord
= rr
->next
;
5224 mDNSlocal
void TimeoutQuestions(mDNS
*const m
)
5226 m
->NextScheduledStopTime
= m
->timenow
+ 0x3FFFFFFF;
5227 if (m
->CurrentQuestion
)
5228 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
,
5229 DNSTypeName(m
->CurrentQuestion
->qtype
));
5230 m
->CurrentQuestion
= m
->Questions
;
5231 while (m
->CurrentQuestion
)
5233 DNSQuestion
*const q
= m
->CurrentQuestion
;
5236 if (!q
->TimeoutQuestion
)
5237 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5239 if (m
->timenow
- q
->StopTime
>= 0)
5241 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q
, q
->qname
.c
, m
->timenow
- q
->StopTime
);
5242 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_forceresponse
);
5243 if (m
->CurrentQuestion
== q
) q
->StopTime
= 0;
5247 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
5248 m
->NextScheduledStopTime
= q
->StopTime
;
5251 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5252 // We can't do this at the start of the loop because GenerateNegativeResponse
5253 // depends on having m->CurrentQuestion point to the right question
5254 if (m
->CurrentQuestion
== q
)
5255 m
->CurrentQuestion
= q
->next
;
5257 m
->CurrentQuestion
= mDNSNULL
;
5260 mDNSlocal
void mDNSCoreFreeProxyRR(mDNS
*const m
)
5262 AuthRecord
*rrPtr
= m
->SPSRRSet
, *rrNext
= mDNSNULL
;
5263 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__
);
5266 rrNext
= rrPtr
->next
;
5267 mDNSPlatformMemFree(rrPtr
);
5270 m
->SPSRRSet
= mDNSNULL
;
5273 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
5275 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
5277 #if APPLE_OSX_mDNSResponder
5278 mDNSLogStatistics(m
);
5279 #endif // APPLE_OSX_mDNSResponder
5281 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
5284 AuthRecord
*head
, *tail
;
5288 verbosedebugf("mDNS_Execute");
5290 if (m
->CurrentQuestion
)
5291 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5292 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5294 if (m
->CurrentRecord
)
5295 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
5297 // 1. If we're past the probe suppression time, we can clear it
5298 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
5300 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5301 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
5303 // 3. Purge our cache of stale old records
5304 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
5306 mDNSu32 numchecked
= 0;
5307 m
->NextCacheCheck
= m
->timenow
+ 0x3FFFFFFF;
5308 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5310 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
5312 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5313 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ 0x3FFFFFFF;
5316 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
5318 CheckCacheExpiration(m
, slot
, *cp
);
5319 if ((*cp
)->members
) cp
=&(*cp
)->next
;
5320 else ReleaseCacheGroup(m
, cp
);
5323 // Even if we didn't need to actually check this slot yet, still need to
5324 // factor its nextcheck time into our overall NextCacheCheck value
5325 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
5326 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
5328 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
5331 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
5333 m
->NextScheduledSPS
= m
->timenow
+ 0x3FFFFFFF;
5334 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
5335 CheckProxyRecords(m
, m
->ResourceRecords
);
5338 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
5340 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5341 // as records could have expired during that check
5342 if (m
->timenow
- m
->NextScheduledKA
>= 0)
5344 m
->NextScheduledKA
= m
->timenow
+ 0x3FFFFFFF;
5345 mDNS_SendKeepalives(m
);
5348 #if BONJOUR_ON_DEMAND
5349 if (m
->NextBonjourDisableTime
&& (m
->timenow
- m
->NextBonjourDisableTime
>= 0))
5351 // Schedule immediate network change processing to leave the multicast group
5352 // since the delay time has expired since the previous active registration or query.
5353 m
->NetworkChanged
= m
->timenow
;
5354 m
->NextBonjourDisableTime
= 0;
5355 m
->BonjourEnabled
= 0;
5357 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5359 #endif // BONJOUR_ON_DEMAND
5361 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5362 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0)
5364 m
->AnnounceOwner
= 0;
5366 // This is a good time to reset the delay counter used to prevent spurious conflicts
5367 m
->DelayConflictProcessing
= 0;
5370 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
5373 if (m
->SleepState
== SleepState_Transferring
)
5375 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5376 BeginSleepProcessing(m
);
5380 // 4. See if we can answer any of our new local questions from the cache
5381 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
5383 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
5384 AnswerNewQuestion(m
);
5386 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5388 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5389 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5390 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
5392 m
->LocalRemoveEvents
= mDNSfalse
;
5393 m
->CurrentRecord
= m
->ResourceRecords
;
5394 CheckRmvEventsForLocalRecords(m
);
5395 // Walk the LocalOnly records and deliver the RMV events
5396 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5397 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5399 m
->CurrentRecord
= ag
->members
;
5400 if (m
->CurrentRecord
) CheckRmvEventsForLocalRecords(m
);
5404 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5406 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
5407 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5409 head
= tail
= mDNSNULL
;
5410 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
5412 AuthRecord
*rr
= m
->NewLocalRecords
;
5413 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
5414 if (LocalRecordReady(rr
))
5416 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5417 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNStrue
);
5421 // If we have just one record that is not ready, we don't have to unlink and
5422 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5423 // terminate and set the NewLocalRecords to rr.
5424 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
5425 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
5426 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
5432 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
5433 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
5434 // if this is the first record we are skipping, move to the end of the list.
5435 // if we have already skipped records before, append it at the end.
5436 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
5437 if (*p
) *p
= rr
->next
; // Cut this record from the list
5438 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
5441 while (*p
) p
=&(*p
)->next
;
5450 rr
->next
= mDNSNULL
;
5453 m
->NewLocalRecords
= head
;
5454 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
5456 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5458 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5459 // to our local questions
5460 if (m
->NewLocalOnlyRecords
)
5462 m
->NewLocalOnlyRecords
= mDNSfalse
;
5463 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5464 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5466 for (i
=0; i
<100 && ag
->NewLocalOnlyRecords
; i
++)
5468 AuthRecord
*rr
= ag
->NewLocalOnlyRecords
;
5469 ag
->NewLocalOnlyRecords
= ag
->NewLocalOnlyRecords
->next
;
5470 // LocalOnly records should always be ready as they never probe
5471 if (LocalRecordReady(rr
))
5473 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5474 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, mDNStrue
);
5476 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m
, rr
));
5478 // We limit about 100 per AuthGroup that can be serviced at a time
5479 if (i
>= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5483 // 5. See what packets we need to send
5484 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
5485 DiscardDeregistrations(m
);
5486 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
5488 // If the platform code is ready, and we're not suppressing packet generation right now
5489 // then send our responses, probes, and questions.
5490 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5491 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5492 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5493 // Finally, we send responses, including the previously mentioned records that just completed probing.
5494 m
->SuppressSending
= 0;
5496 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5497 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
5498 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
5501 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5502 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
5503 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
5504 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
5505 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
5506 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5508 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
5510 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5511 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
5512 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
5515 // 7. Send Response packets, including probing records just advanced to announcing state
5516 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
5517 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
5519 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5520 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
5524 // Clear RandomDelay values, ready to pick a new different value next time
5525 m
->RandomQueryDelay
= 0;
5526 m
->RandomReconfirmDelay
= 0;
5528 if (m
->NextScheduledStopTime
&& m
->timenow
- m
->NextScheduledStopTime
>= 0) TimeoutQuestions(m
);
5529 #ifndef UNICAST_DISABLED
5530 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
5531 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
5532 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
5534 #if APPLE_OSX_mDNSResponder
5535 extern void serviceBLE();
5536 if (m
->NextBLEServiceTime
&& (m
->timenow
- m
->NextBLEServiceTime
>= 0)) serviceBLE();
5537 #endif // APPLE_OSX_mDNSResponder
5540 // Note about multi-threaded systems:
5541 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5542 // performing mDNS API operations that change our next scheduled event time.
5544 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5545 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5546 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5547 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5548 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5549 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5550 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5551 // without blocking. This avoids the race condition between the signal from the other thread arriving
5552 // just *before* or just *after* the main thread enters the blocking primitive.
5554 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5555 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5556 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5557 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5558 // by the time it gets to the timer callback function).
5560 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5561 return(m
->NextScheduledEvent
);
5564 #ifndef UNICAST_DISABLED
5565 mDNSlocal
void SuspendLLQs(mDNS
*m
)
5568 for (q
= m
->Questions
; q
; q
= q
->next
)
5569 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
5570 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
5572 #endif // UNICAST_DISABLED
5574 mDNSlocal mDNSBool
QuestionHasLocalAnswers(mDNS
*const m
, DNSQuestion
*q
)
5580 slot
= AuthHashSlot(&q
->qname
);
5581 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
5584 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
5585 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5586 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
5588 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
));
5595 // ActivateUnicastQuery() is called from three places:
5596 // 1. When a new question is created
5597 // 2. On wake from sleep
5598 // 3. When the DNS configuration changes
5599 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5600 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5601 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
5603 // For now this AutoTunnel stuff is specific to Mac OS X.
5604 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
5605 #if APPLE_OSX_mDNSResponder
5606 // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
5607 // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
5608 // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
5609 // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
5610 // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
5611 // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
5613 if (RRTypeIsAddressType(question
->qtype
) && PrivateQuery(question
) &&
5614 !SameDomainLabel(question
->qname
.c
, (const mDNSu8
*)"\x0c_autotunnel6")&& question
->QuestionCallback
!= AutoTunnelCallback
)
5616 question
->NoAnswer
= NoAnswer_Suspended
;
5617 AddNewClientTunnel(m
, question
);
5620 #endif // APPLE_OSX_mDNSResponder
5622 if (!question
->DuplicateOf
)
5624 debugf("ActivateUnicastQuery: %##s %s%s%s",
5625 question
->qname
.c
, DNSTypeName(question
->qtype
), PrivateQuery(question
) ? " (Private)" : "", ScheduleImmediately
? " ScheduleImmediately" : "");
5626 question
->CNAMEReferrals
= 0;
5627 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
5628 if (question
->LongLived
)
5630 question
->state
= LLQ_InitialRequest
;
5631 question
->id
= zeroOpaque64
;
5632 question
->servPort
= zeroIPPort
;
5633 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
5635 // If the question has local answers, then we don't want answers from outside
5636 if (ScheduleImmediately
&& !QuestionHasLocalAnswers(m
, question
))
5638 question
->ThisQInterval
= InitialQuestionInterval
;
5639 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
5640 SetNextQueryTime(m
, question
);
5645 // Caller should hold the lock
5646 mDNSexport
void mDNSCoreRestartAddressQueries(mDNS
*const m
, mDNSBool SearchDomainsChanged
, FlushCache flushCacheRecords
,
5647 CallbackBeforeStartQuery BeforeStartCallback
, void *context
)
5650 DNSQuestion
*restart
= mDNSNULL
;
5654 // 1. Flush the cache records
5655 if (flushCacheRecords
) flushCacheRecords(m
);
5657 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5658 // we are going to stop the question. Hence we need to deliver the RMV event before we
5659 // stop the question.
5661 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5662 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5663 // *any* other question which could be the next one that we may process here. RestartQuestion
5664 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5665 // if the "next" question is stopped while the CurrentQuestion is stopped
5667 if (m
->RestartQuestion
)
5668 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5669 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
5671 m
->RestartQuestion
= m
->Questions
;
5672 while (m
->RestartQuestion
)
5674 q
= m
->RestartQuestion
;
5675 m
->RestartQuestion
= q
->next
;
5676 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5677 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5678 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5679 // question followed by the original query that refers to this GetZoneData question, we will end up
5680 // freeing the GetZoneData question and then start the "freed" question at the end.
5682 if (IsGetZoneDataQuestion(q
))
5684 DNSQuestion
*refq
= q
->next
;
5685 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5686 // debug stuff, we just try to find the referencing question and don't do much with it
5689 if (q
== &refq
->nta
->question
)
5691 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq
, refq
->qname
.c
, DNSTypeName(refq
->qtype
), q
);
5698 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5699 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
&& q
->qtype
!= kDNSType_CNAME
) continue;
5701 // If the search domains did not change, then we restart all the queries. Otherwise, only
5702 // for queries for which we "might" have appended search domains ("might" because we may
5703 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5704 if (!SearchDomainsChanged
|| q
->AppendSearchDomains
)
5706 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5707 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5708 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5709 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5710 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5711 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5712 // for the original query using these cache entries as ADDs were never delivered using these cache
5713 // entries and hence this order is needed.
5715 // If the query is suppressed, the RMV events won't be delivered
5716 if (!CacheRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5718 // SuppressQuery status does not affect questions that are answered using local records
5719 if (!LocalRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5721 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q
,
5722 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->AppendSearchDomains
, q
->qnameOrig
);
5723 mDNS_StopQuery_internal(m
, q
);
5724 // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
5725 // and then search domains should be appended. At the beginning, qnameOrig was NULL.
5728 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q
->qnameOrig
);
5729 AssignDomainName(&q
->qname
, q
->qnameOrig
);
5730 mDNSPlatformMemFree(q
->qnameOrig
);
5731 q
->qnameOrig
= mDNSNULL
;
5732 q
->RetryWithSearchDomains
= ApplySearchDomainsFirst(q
) ? 1 : 0;
5734 q
->SearchListIndex
= 0;
5740 // 3. Callback before we start the query
5741 if (BeforeStartCallback
) BeforeStartCallback(m
, context
);
5743 // 4. Restart all the stopped queries
5747 restart
= restart
->next
;
5749 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5750 mDNS_StartQuery_internal(m
, q
);
5754 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
5758 #ifndef UNICAST_DISABLED
5759 // Retrigger all our uDNS questions
5760 if (m
->CurrentQuestion
)
5761 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5762 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5763 m
->CurrentQuestion
= m
->Questions
;
5764 while (m
->CurrentQuestion
)
5766 q
= m
->CurrentQuestion
;
5767 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
5768 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
)) ActivateUnicastQuery(m
, q
, mDNStrue
);
5772 // Retrigger all our mDNS questions
5773 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5774 mDNSCoreRestartQuestion(m
, q
);
5777 // restart question if it's multicast and currently active
5778 mDNSexport
void mDNSCoreRestartQuestion(mDNS
*const m
, DNSQuestion
*q
)
5780 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
5782 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
5783 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
5784 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5785 q
->RecentAnswerPkts
= 0;
5786 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
5787 m
->NextScheduledQuery
= m
->timenow
;
5791 // restart the probe/announce cycle for multicast record
5792 mDNSexport
void mDNSCoreRestartRegistration(mDNS
*const m
, AuthRecord
*rr
, int announceCount
)
5794 if (!AuthRecord_uDNS(rr
))
5796 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5797 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
5799 if (mDNS_KeepaliveRecord(&rr
->resrec
))
5801 rr
->AnnounceCount
= 0; // Do not announce keepalive records
5805 // announceCount < 0 indicates default announce count should be used
5806 if (announceCount
< 0)
5807 announceCount
= InitialAnnounceCount
;
5808 if (rr
->AnnounceCount
< (mDNSu8
)announceCount
)
5809 rr
->AnnounceCount
= (mDNSu8
)announceCount
;
5812 rr
->SendNSECNow
= mDNSNULL
;
5813 InitializeLastAPTime(m
, rr
);
5817 // ***************************************************************************
5818 #if COMPILER_LIKES_PRAGMA_MARK
5820 #pragma mark - Power Management (Sleep/Wake)
5823 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
5825 #ifndef IDLESLEEPCONTROL_DISABLED
5826 mDNSBool allowSleep
= mDNStrue
;
5831 if (m
->SystemSleepOnlyIfWakeOnLAN
)
5833 // Don't sleep if we are a proxy for any services
5834 if (m
->ProxyRecords
)
5836 allowSleep
= mDNSfalse
;
5837 mDNS_snprintf(reason
, sizeof(reason
), "sleep proxy for %d records", m
->ProxyRecords
);
5838 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
5841 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
5843 // Scan the list of active interfaces
5844 NetworkInterfaceInfo
*intf
;
5845 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5847 if (intf
->McastTxRx
&& !intf
->Loopback
&& !mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
5849 // Disallow sleep if this interface doesn't support NetWake
5852 allowSleep
= mDNSfalse
;
5853 mDNS_snprintf(reason
, sizeof(reason
), "%s does not support NetWake", intf
->ifname
);
5854 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf
->ifname
);
5858 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5859 // that will be offloaded. If not, we should prevent sleep.
5860 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5861 #if APPLE_OSX_mDNSResponder
5862 if (!SupportsInNICProxy(intf
))
5865 // Disallow sleep if there is no sleep proxy server
5866 const CacheRecord
*cr
= FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
);
5867 if ( cr
== mDNSNULL
)
5869 allowSleep
= mDNSfalse
;
5870 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server on %s", intf
->ifname
);
5871 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf
->ifname
);
5874 else if (m
->SPSType
!= 0)
5876 mDNSu32 mymetric
= LocalSPSMetric(m
);
5877 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
5878 if (metric
>= mymetric
)
5880 allowSleep
= mDNSfalse
;
5881 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server with better metric on %s", intf
->ifname
);
5882 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf
->ifname
);
5892 // Call the platform code to enable/disable sleep
5893 mDNSPlatformSetAllowSleep(m
, allowSleep
, reason
);
5896 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5899 mDNSlocal mDNSBool
mDNSUpdateOkToSend(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSu32 scopeid
)
5901 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5902 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5904 if (AuthRecord_uDNS(rr
) || (rr
->AuthFlags
& AuthFlagsWakeOnly
) || mDNSOpaque16IsZero(rr
->updateid
) ||
5905 m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
5910 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5911 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5912 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5913 // updateid and we should have returned from above.
5915 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5916 // platform function to extract the value from "intf" every time.
5918 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
5919 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
5925 mDNSexport
void UpdateRMAC(mDNS
*const m
, void *context
)
5927 IPAddressMACMapping
*addrmap
= (IPAddressMACMapping
*)context
;
5928 m
->CurrentRecord
= m
->ResourceRecords
;
5932 LogMsg("UpdateRMAC: Address mapping is NULL");
5936 while (m
->CurrentRecord
)
5938 AuthRecord
*rr
= m
->CurrentRecord
;
5939 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
5940 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
5943 getKeepaliveRaddr(m
, rr
, &raddr
);
5944 if (mDNSSameAddress(&raddr
, &addrmap
->ipaddr
))
5946 // Update the MAC address only if it is not a zero MAC address
5947 mDNSEthAddr macAddr
;
5948 mDNSu8
*ptr
= GetValueForMACAddr((mDNSu8
*)(addrmap
->ethaddr
), (mDNSu8
*) (addrmap
->ethaddr
+ sizeof(addrmap
->ethaddr
)), &macAddr
);
5949 if (ptr
!= mDNSNULL
&& !mDNSEthAddressIsZero(macAddr
))
5951 UpdateKeepaliveRData(m
, rr
, mDNSNULL
, mDNStrue
, (char *)(addrmap
->ethaddr
));
5955 m
->CurrentRecord
= rr
->next
;
5959 mDNSPlatformMemFree(addrmap
);
5963 mDNSexport mStatus
UpdateKeepaliveRData(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSBool updateMac
, char *ethAddr
)
5965 mDNSu16 newrdlength
;
5966 mDNSAddr laddr
= zeroAddr
;
5967 mDNSAddr raddr
= zeroAddr
;
5968 mDNSEthAddr eth
= zeroEthAddr
;
5969 mDNSIPPort lport
= zeroIPPort
;
5970 mDNSIPPort rport
= zeroIPPort
;
5971 mDNSu32 timeout
= 0;
5981 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
5982 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
5983 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
5984 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
5986 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, &raddr
, rport
.NotAnInteger
);
5987 return mStatus_UnknownErr
;
5992 if (laddr
.type
== mDNSAddrType_IPv4
)
5993 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%s", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ethAddr
);
5995 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%s", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ethAddr
);
6000 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6001 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6002 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6003 mDNSPlatformMemZero(&mti
, sizeof (mDNSTCPInfo
));
6004 ret
= mDNSPlatformRetrieveTCPInfo(m
, &laddr
, &lport
, &raddr
, &rport
, &mti
);
6005 if (ret
!= mStatus_NoError
)
6007 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret
);
6010 if ((intf
!= mDNSNULL
) && (mti
.IntfId
!= intf
->InterfaceID
))
6012 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti
.IntfId
, intf
->InterfaceID
);
6013 return mStatus_BadParamErr
;
6016 if (laddr
.type
== mDNSAddrType_IPv4
)
6017 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ð
, mti
.seq
, mti
.ack
, mti
.window
);
6019 newrdlength
= mDNS_snprintf((char *)&txt
.c
[1], sizeof(txt
.c
) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout
, kKeepaliveRetryInterval
, kKeepaliveRetryCount
, &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
), ð
, mti
.seq
, mti
.ack
, mti
.window
);
6022 // Did we insert a null byte at the end ?
6023 if (newrdlength
== (sizeof(txt
.c
) - 1))
6025 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m
, rr
));
6026 return mStatus_NoMemoryErr
;
6029 // Include the length for the null byte at the end
6030 txt
.c
[0] = newrdlength
+ 1;
6031 // Account for the first length byte and the null byte at the end
6034 rdsize
= newrdlength
> sizeof(RDataBody
) ? newrdlength
: sizeof(RDataBody
);
6035 newrd
= mDNSPlatformMemAllocate(sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
6036 if (!newrd
) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr
; }
6038 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
6039 mDNSPlatformMemCopy(&newrd
->u
, txt
.c
, newrdlength
);
6041 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6042 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6043 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6044 // free that memory here before copying in the new data.
6045 if ( rr
->resrec
.rdata
!= &rr
->rdatastorage
)
6047 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m
, rr
));
6048 mDNSPlatformMemFree(rr
->resrec
.rdata
);
6050 SetNewRData(&rr
->resrec
, newrd
, newrdlength
); // Update our rdata
6052 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m
, rr
));
6053 return mStatus_NoError
;
6056 mDNSlocal
void SendSPSRegistrationForOwner(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
, const OwnerOptData
*const owner
)
6058 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
6059 const int sps
= intf
->NextSPSAttempt
/ 3;
6064 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6065 if (!intf
->SPSAddr
[sps
].type
)
6067 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6068 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
6069 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
6070 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6074 // Mark our mDNS records (not unicast records) for transfer to SPS
6075 if (mDNSOpaque16IsZero(id
))
6077 // We may have to register this record over multiple interfaces and we don't want to
6078 // overwrite the id. We send the registration over interface X with id "IDX" and before
6079 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6080 // for "IDX". Hence, we want to use the same ID across all interfaces.
6082 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6083 // option check below will set the same ID across the records from the same owner. Records
6084 // with different owner option gets different ID.
6085 msgid
= mDNS_NewMessageID(m
);
6086 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6088 if (!(rr
->AuthFlags
& AuthFlagsWakeOnly
) && rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
6090 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
6092 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6094 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
6095 // When we are registering on the first interface, rr->updateid is zero in which case
6096 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6097 // At the end, all the updates sent across all the interfaces with the same ID.
6098 if (mDNSOpaque16IsZero(rr
->updateid
))
6099 rr
->updateid
= msgid
;
6101 msgid
= rr
->updateid
;
6112 mDNSu8
*p
= m
->omsg
.data
;
6113 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6114 // For now we follow that same logic for SPS registrations too.
6115 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6116 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6117 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
6119 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6120 if (rr
->SendRNow
|| mDNSUpdateOkToSend(m
, rr
, intf
, scopeid
))
6122 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6125 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
6127 // If we can't update the keepalive record, don't send it
6128 if (mDNS_KeepaliveRecord(&rr
->resrec
) && (UpdateKeepaliveRData(m
, rr
, intf
, mDNSfalse
, mDNSNULL
) != mStatus_NoError
))
6130 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
6132 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
6134 rr
->SendRNow
= mDNSNULL
;
6138 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
6139 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6140 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
6141 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
6143 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
6146 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
));
6147 rr
->SendRNow
= mDNSNULL
;
6148 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
6149 rr
->LastAPTime
= m
->timenow
;
6150 // should be initialized above
6151 if (mDNSOpaque16IsZero(rr
->updateid
)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m
, rr
));
6152 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6153 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
6159 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
6163 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
6164 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
6165 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
6166 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
6167 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
6168 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
6169 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
6170 if (!owner
->HMAC
.l
[0]) // If no owner data,
6171 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]); // use our own interface information
6172 else // otherwise, use the owner data we were given
6174 opt
.resrec
.rdata
->u
.opt
[1].u
.owner
= *owner
;
6175 opt
.resrec
.rdata
->u
.opt
[1].opt
= kDNSOpt_Owner
;
6176 opt
.resrec
.rdata
->u
.opt
[1].optlen
= DNSOpt_Owner_Space(&owner
->HMAC
, &owner
->IMAC
) - 4;
6178 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
6179 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
6181 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
6186 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
6187 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
6188 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6189 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSNULL
, mDNSfalse
);
6190 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
6191 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv4
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
6193 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6194 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_AAAA
;
6195 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
6202 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
6205 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
6208 mDNSlocal mDNSBool
RecordIsFirstOccurrenceOfOwner(mDNS
*const m
, const AuthRecord
*const rr
)
6211 for (ar
= m
->ResourceRecords
; ar
&& ar
!= rr
; ar
=ar
->next
)
6212 if (mDNSPlatformMemSame(&rr
->WakeUp
, &ar
->WakeUp
, sizeof(rr
->WakeUp
))) return mDNSfalse
;
6216 mDNSlocal
void mDNSCoreStoreProxyRR(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, AuthRecord
*const rr
)
6218 AuthRecord
*newRR
= mDNSPlatformMemAllocate(sizeof(AuthRecord
));
6220 if (newRR
== mDNSNULL
)
6222 LogSPS("%s : could not allocate memory for new resource record", __func__
);
6226 mDNSPlatformMemZero(newRR
, sizeof(AuthRecord
));
6227 mDNS_SetupResourceRecord(newRR
, mDNSNULL
, InterfaceID
, rr
->resrec
.rrtype
,
6228 rr
->resrec
.rroriginalttl
, rr
->resrec
.RecordType
,
6229 rr
->ARType
, mDNSNULL
, mDNSNULL
);
6231 AssignDomainName(&newRR
->namestorage
, &rr
->namestorage
);
6232 newRR
->resrec
.rdlength
= DomainNameLength(rr
->resrec
.name
);
6233 newRR
->resrec
.namehash
= DomainNameHashValue(newRR
->resrec
.name
);
6234 newRR
->resrec
.rrclass
= rr
->resrec
.rrclass
;
6236 if (rr
->resrec
.rrtype
== kDNSType_A
)
6238 newRR
->resrec
.rdata
->u
.ipv4
= rr
->resrec
.rdata
->u
.ipv4
;
6240 else if (rr
->resrec
.rrtype
== kDNSType_AAAA
)
6242 newRR
->resrec
.rdata
->u
.ipv6
= rr
->resrec
.rdata
->u
.ipv6
;
6244 SetNewRData(&newRR
->resrec
, mDNSNULL
, 0);
6246 // Insert the new node at the head of the list.
6247 newRR
->next
= m
->SPSRRSet
;
6248 m
->SPSRRSet
= newRR
;
6249 LogSPS("%s : Storing proxy record : %s ", __func__
, ARDisplayString(m
, rr
));
6252 // Some records are interface specific and some are not. The ones that are supposed to be registered
6253 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6254 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6255 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6256 // registration on all the interfaces
6257 mDNSlocal
void SPSInitRecordsBeforeUpdate(mDNS
*const m
, mDNSOpaque64 updateIntID
, mDNSBool
*WakeOnlyService
)
6260 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID
.l
[1], updateIntID
.l
[0]);
6262 *WakeOnlyService
= mDNSfalse
;
6264 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6265 // make sure that the old sleep proxy records are removed.
6266 mDNSCoreFreeProxyRR(m
);
6268 // For records that are registered only on a specific interface, mark only that bit as it will
6269 // never be registered on any other interface. For others, it should be sent on all interfaces.
6270 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6272 ar
->updateIntID
= zeroOpaque64
;
6273 ar
->updateid
= zeroID
;
6274 if (AuthRecord_uDNS(ar
))
6278 if (ar
->AuthFlags
& AuthFlagsWakeOnly
)
6280 if (ar
->resrec
.RecordType
== kDNSRecordTypeShared
&& ar
->RequireGoodbye
)
6282 ar
->ImmedAnswer
= mDNSInterfaceMark
;
6283 *WakeOnlyService
= mDNStrue
;
6287 if (!ar
->resrec
.InterfaceID
)
6289 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID
.l
[1], updateIntID
.l
[0], ARDisplayString(m
, ar
));
6290 ar
->updateIntID
= updateIntID
;
6294 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6296 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, ar
->resrec
.InterfaceID
, mDNStrue
);
6297 if ((scopeid
< (sizeof(updateIntID
) * mDNSNBBY
)) && bit_get_opaque64(updateIntID
, scopeid
))
6299 bit_set_opaque64(ar
->updateIntID
, scopeid
);
6300 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid
, ar
->updateIntID
.l
[1],
6301 ar
->updateIntID
.l
[0], ARDisplayString(m
, ar
));
6305 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid
);
6308 // Store the A and AAAA records that we registered with the sleep proxy.
6309 // We will use this to prevent spurious name conflicts that may occur when we wake up
6310 if (ar
->resrec
.rrtype
== kDNSType_A
|| ar
->resrec
.rrtype
== kDNSType_AAAA
)
6312 mDNSCoreStoreProxyRR(m
, ar
->resrec
.InterfaceID
, ar
);
6317 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
)
6320 OwnerOptData owner
= zeroOwner
;
6322 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6324 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6326 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)) && RecordIsFirstOccurrenceOfOwner(m
, ar
))
6329 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6334 // RetrySPSRegistrations is called from SendResponses, with the lock held
6335 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
6338 NetworkInterfaceInfo
*intf
;
6340 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6341 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6342 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
6343 intf
->NextSPSAttemptTime
++;
6345 // Retry any record registrations that are due
6346 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6347 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6349 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6351 // If we still have registrations pending on this interface, send it now
6352 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6353 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6354 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6356 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
6357 SendSPSRegistration(m
, intf
, rr
->updateid
);
6362 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6363 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6364 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
6365 intf
->NextSPSAttempt
++;
6368 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
6370 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
6371 int sps
= (int)(question
- intf
->NetWakeResolve
);
6373 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
6375 if (!AddRecord
) return; // Don't care about REMOVE events
6376 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
6378 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6380 if (answer
->rrtype
== kDNSType_SRV
)
6382 // 1. Got the SRV record; now look up the target host's IP address
6383 mDNS_StopQuery(m
, question
);
6384 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
6385 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
6386 question
->qtype
= kDNSType_A
;
6387 mDNS_StartQuery(m
, question
);
6389 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
6391 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6392 mDNS_StopQuery(m
, question
);
6393 question
->ThisQInterval
= -1;
6394 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
6395 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
6397 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6400 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== 0)
6402 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6403 mDNS_StopQuery(m
, question
);
6404 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps
, question
->qname
.c
);
6405 question
->qtype
= kDNSType_AAAA
;
6406 mDNS_StartQuery(m
, question
);
6408 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
6410 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6411 mDNS_StopQuery(m
, question
);
6412 question
->ThisQInterval
= -1;
6413 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
6414 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
6416 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6421 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
6424 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6425 if (mDNS_KeepaliveRecord(&rr
->resrec
) || (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
)))
6430 #define WAKE_ONLY_SERVICE 1
6431 #define AC_ONLY_SERVICE 2
6433 #ifdef APPLE_OSX_mDNSResponder
6434 mDNSlocal
void SendGoodbyesForSelectServices(mDNS
*const m
, mDNSBool
*servicePresent
, mDNSu32 serviceType
)
6437 *servicePresent
= mDNSfalse
;
6439 // Mark all the records we need to deregister and send them
6440 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6442 // If the service type is wake only service and the auth flags match and requires a goodbye
6443 // OR if the service type is AC only and it is not a keepalive record,
6444 // mark the records we need to deregister and send them
6445 if ((serviceType
== WAKE_ONLY_SERVICE
&& (rr
->AuthFlags
& AuthFlagsWakeOnly
) &&
6446 rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
) ||
6447 (serviceType
== AC_ONLY_SERVICE
&& !mDNS_KeepaliveRecord(&rr
->resrec
)))
6449 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6450 *servicePresent
= mDNStrue
;
6456 #ifdef APPLE_OSX_mDNSResponder
6457 // This function is used only in the case of local NIC proxy. For external
6458 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6459 // walk the resource records.
6460 mDNSlocal
void SendGoodbyesForWakeOnlyService(mDNS
*const m
, mDNSBool
*WakeOnlyService
)
6462 return SendGoodbyesForSelectServices(m
, WakeOnlyService
, WAKE_ONLY_SERVICE
);
6464 #endif // APPLE_OSX_mDNSResponder
6467 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
, mDNSBool AllInterfaces
, mDNSBool unicast
)
6470 m
->SleepState
= SleepState_Sleeping
;
6472 // If AllInterfaces is not set, the caller has already marked it appropriately
6473 // on which interfaces this should be sent.
6476 NetworkInterfaceInfo
*intf
;
6477 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6479 intf
->SendGoodbyes
= 1;
6484 #ifndef UNICAST_DISABLED
6485 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
6486 #endif /* UNICAST_DISABLED */
6489 // Mark all the records we need to deregister and send them
6490 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6491 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
6492 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6497 * This function attempts to detect if multiple interfaces are on the same subnet.
6498 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6499 * IPv6 link local addresses that are configured by default on all interfaces make
6500 * it hard to make this determination
6502 * The 'real' fix for this would be to send out multicast packets over one interface
6503 * and conclude that multiple interfaces are on the same subnet only if these packets
6504 * are seen on other interfaces on the same system
6506 mDNSlocal mDNSBool
skipSameSubnetRegistration(mDNS
*const m
, mDNSInterfaceID
*regID
, mDNSu32 count
, mDNSInterfaceID intfid
)
6508 NetworkInterfaceInfo
*intf
;
6509 NetworkInterfaceInfo
*newIntf
;
6512 for (newIntf
= FirstInterfaceForID(m
, intfid
); newIntf
; newIntf
= newIntf
->next
)
6514 if ((newIntf
->InterfaceID
!= intfid
) ||
6515 (newIntf
->ip
.type
!= mDNSAddrType_IPv4
))
6519 for ( i
= 0; i
< count
; i
++)
6521 for (intf
= FirstInterfaceForID(m
, regID
[i
]); intf
; intf
= intf
->next
)
6523 if ((intf
->InterfaceID
!= regID
[i
]) ||
6524 (intf
->ip
.type
!= mDNSAddrType_IPv4
))
6528 if ((intf
->ip
.ip
.v4
.NotAnInteger
& intf
->mask
.ip
.v4
.NotAnInteger
) == (newIntf
->ip
.ip
.v4
.NotAnInteger
& newIntf
->mask
.ip
.v4
.NotAnInteger
))
6530 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__
, intf
->ifname
);
6539 mDNSlocal
void DoKeepaliveCallbacks(mDNS
*m
)
6541 // Loop through the keepalive records and callback with an error
6542 m
->CurrentRecord
= m
->ResourceRecords
;
6543 while (m
->CurrentRecord
)
6545 AuthRecord
*const rr
= m
->CurrentRecord
;
6546 if ((mDNS_KeepaliveRecord(&rr
->resrec
)) && (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
))
6548 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m
, rr
));
6549 if (rr
->RecordCallback
)
6550 rr
->RecordCallback(m
, rr
, mStatus_BadStateErr
);
6552 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
6553 m
->CurrentRecord
= rr
->next
;
6557 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6558 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
6560 mDNSBool SendGoodbyes
= mDNStrue
;
6561 mDNSBool WakeOnlyService
= mDNSfalse
;
6562 mDNSBool invokeKACallback
= mDNStrue
;
6563 const CacheRecord
*sps
[3] = { mDNSNULL
};
6564 mDNSOpaque64 updateIntID
= zeroOpaque64
;
6565 mDNSInterfaceID registeredIntfIDS
[128] = { 0 };
6566 mDNSu32 registeredCount
= 0;
6567 int skippedRegistrations
= 0;
6569 m
->NextScheduledSPRetry
= m
->timenow
;
6571 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6572 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
6573 else // If we have at least one advertised service
6575 NetworkInterfaceInfo
*intf
;
6577 // Clear out the SCDynamic entry that stores the external SPS information
6578 mDNSPlatformClearSPSData();
6580 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6582 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6583 intf
->SendGoodbyes
= 0;
6585 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6587 if (!intf
->McastTxRx
|| mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
6589 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf
->ifname
);
6593 // If we are not capable of WOMP, then don't register with sleep proxy.
6595 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6596 // We might find sleep proxy servers in the cache and start a resolve on them.
6597 // But then if the interface goes away, we won't stop these questions because
6598 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6599 // to stop both the browse and resolve questions.
6602 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
6603 intf
->SendGoodbyes
= 1;
6604 skippedRegistrations
++;
6608 // Check if we have already registered with a sleep proxy for this subnet
6609 if (skipSameSubnetRegistration(m
, registeredIntfIDS
, registeredCount
, intf
->InterfaceID
))
6611 LogSPS("%s : Skipping sleep proxy registration on %s", __func__
, intf
->ifname
);
6615 #if APPLE_OSX_mDNSResponder
6616 else if (SupportsInNICProxy(intf
))
6618 mDNSBool keepaliveOnly
= mDNSfalse
;
6619 if (ActivateLocalProxy(m
, intf
, &keepaliveOnly
) == mStatus_NoError
)
6621 SendGoodbyesForWakeOnlyService(m
, &WakeOnlyService
);
6623 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6624 SendGoodbyes
= (keepaliveOnly
) ? mDNStrue
: mDNSfalse
;
6625 invokeKACallback
= mDNSfalse
;
6626 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
6627 // This will leave m->SleepState set to SleepState_Transferring,
6628 // which is okay because with no outstanding resolves, or updates in flight,
6629 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6631 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6635 #endif // APPLE_OSX_mDNSResponder
6638 #if APPLE_OSX_mDNSResponder
6639 // If on battery, do not attempt to offload to external sleep proxies
6640 if (m
->SystemWakeOnLANEnabled
== mDNS_WakeOnBattery
)
6642 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6645 #endif // APPLE_OSX_mDNSResponder
6646 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
6647 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6648 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
6653 SendGoodbyes
= mDNSfalse
;
6654 intf
->NextSPSAttempt
= 0;
6655 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6657 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6658 // Now we know for sure that we have to wait for registration to complete on this interface.
6659 if (scopeid
< (sizeof(updateIntID
) * mDNSNBBY
))
6660 bit_set_opaque64(updateIntID
, scopeid
);
6662 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6666 if (intf
->SPSAddr
[i
].type
)
6667 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
);
6668 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
6669 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
);
6671 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
6672 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
6673 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
6676 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
6677 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
6678 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
6679 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
6681 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6682 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6691 // If we have at least one interface on which we are registering with an external sleep proxy,
6692 // initialize all the records appropriately.
6693 if (!mDNSOpaque64IsZero(&updateIntID
))
6694 SPSInitRecordsBeforeUpdate(m
, updateIntID
, &WakeOnlyService
);
6696 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6697 // the records to a sleep proxy.
6698 if (invokeKACallback
)
6700 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6701 DoKeepaliveCallbacks(m
);
6704 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6705 // interfaces and also deregister unicast registrations.
6707 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6708 // for both multicast and unicast.
6710 // - If we skipped registrations on some interfaces, then we have already marked
6711 // them appropriately above. We don't need to send goodbyes for unicast as
6712 // we have registered with at least one sleep proxy.
6714 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6716 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6717 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6718 // at WakeOnlyServices first.
6721 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6722 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
6724 else if (skippedRegistrations
)
6726 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6727 SendSleepGoodbyes(m
, mDNSfalse
, mDNSfalse
);
6729 else if (WakeOnlyService
)
6731 // If we saw WakeOnly service above, send the goodbyes now.
6732 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6737 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6738 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6739 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6740 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
6744 LogSPS("%s (old state %d) at %ld", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
6746 if (sleep
&& !m
->SleepState
) // Going to sleep
6749 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6752 mDNSu8 oldstate
= m
->SPSState
;
6753 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6755 #ifndef SPC_DISABLED
6756 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
6760 mDNS_ReclaimLockAfterCallback();
6763 m
->SleepState
= SleepState_Transferring
;
6764 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
6766 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6767 LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
6768 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
6773 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
6774 m
->mDNSStats
.Sleeps
++;
6775 BeginSleepProcessing(m
);
6778 #ifndef UNICAST_DISABLED
6781 #if APPLE_OSX_mDNSResponder
6782 RemoveAutoTunnel6Record(m
);
6784 LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m
->SleepState
,
6785 m
->SleepState
== SleepState_Transferring
? "Transferring" :
6786 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
6789 else if (!sleep
) // Waking up
6794 NetworkInterfaceInfo
*intf
;
6795 mDNSs32 currtime
, diff
;
6798 // Reset SleepLimit back to 0 now that we're awake again.
6801 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6802 if (m
->SleepState
!= SleepState_Awake
)
6804 m
->SleepState
= SleepState_Awake
;
6806 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6807 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6808 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6809 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6810 m
->DelaySleep
= NonZeroTime(m
->timenow
+ kDarkWakeDelaySleep
);
6813 if (m
->SPSState
== 3)
6816 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
);
6818 m
->mDNSStats
.Wakes
++;
6819 m
->DelayConflictProcessing
= MAX_CONFLICT_PROCESSING_DELAYS
;
6820 // ... and the same for NextSPSAttempt
6821 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
6823 // Restart unicast and multicast queries
6824 mDNSCoreRestartQueries(m
);
6826 // and reactivtate service registrations
6827 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
6828 LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
6830 // 2. Re-validate our cache records
6831 currtime
= mDNSPlatformUTC();
6833 #if APPLE_OSX_mDNSResponder
6834 // start time of this statistics gathering interval
6835 m
->StatStartTime
= currtime
;
6836 #endif // APPLE_OSX_mDNSResponder
6838 diff
= currtime
- m
->TimeSlept
;
6839 FORALL_CACHERECORDS(slot
, cg
, cr
)
6841 // Temporary fix: For unicast cache records, look at how much time we slept.
6842 // Adjust the RecvTime by the amount of time we slept so that we age the
6843 // cache record appropriately. If it is expired already, purge. If there
6844 // is a network change that happens after the wakeup, we might purge the
6845 // cache anyways and this helps only in the case where there are no network
6846 // changes across sleep/wakeup transition.
6848 // Note: If there is a network/DNS server change that already happened and
6849 // these cache entries are already refreshed and we are getting a delayed
6850 // wake up notification, we might adjust the TimeRcvd based on the time slept
6851 // now which can cause the cache to purge pre-maturely. As this is not a very
6852 // common case, this should happen rarely.
6853 if (!cr
->resrec
.InterfaceID
)
6857 mDNSu32 uTTL
= RRUnadjustedTTL(cr
->resrec
.rroriginalttl
);
6858 const mDNSs32 remain
= uTTL
- (m
->timenow
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
6860 // -if we have slept longer than the remaining TTL, purge and start fresh.
6861 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6862 // a sufficiently big value which could cause the value to go into the future
6863 // because of the signed comparison of time. For this to happen, we should have been
6864 // sleeping really long (~24 days). For now, we want to be conservative and flush even
6865 // if we have slept for more than two days.
6867 if (diff
>= remain
|| diff
> (2 * 24 * 3600))
6869 LogInfo("mDNSCoreMachineSleep: %s: Purging cache entry SleptTime %d, Remaining TTL %d",
6870 CRDisplayString(m
, cr
), diff
, remain
);
6871 mDNS_PurgeCacheResourceRecord(m
, cr
);
6874 cr
->TimeRcvd
-= (diff
* mDNSPlatformOneSecond
);
6875 if (m
->timenow
- (cr
->TimeRcvd
+ ((mDNSs32
)uTTL
* mDNSPlatformOneSecond
)) >= 0)
6877 LogInfo("mDNSCoreMachineSleep: %s: Purging after adjusting the remaining TTL %d by %d seconds",
6878 CRDisplayString(m
, cr
), remain
, diff
);
6879 mDNS_PurgeCacheResourceRecord(m
, cr
);
6883 LogInfo("mDNSCoreMachineSleep: %s: Adjusted the remain ttl %u by %d seconds", CRDisplayString(m
, cr
), remain
, diff
);
6889 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
6893 // 3. Retrigger probing and announcing for all our authoritative records
6894 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6896 if (AuthRecord_uDNS(rr
))
6898 ActivateUnicastRegistration(m
, rr
);
6902 mDNSCoreRestartRegistration(m
, rr
, -1);
6906 // 4. Refresh NAT mappings
6907 // We don't want to have to assume that all hardware can necessarily keep accurate
6908 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
6909 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
6910 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
6911 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
6912 // than five seconds from now.
6913 LogInfo("mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
6914 RecreateNATMappings(m
, mDNSPlatformOneSecond
* 5);
6919 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
6923 NetworkInterfaceInfo
*intf
;
6927 if (m
->DelaySleep
) goto notready
;
6929 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
6930 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
6932 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
6934 // See if we might need to retransmit any lost Sleep Proxy Registrations
6935 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6936 if (intf
->NextSPSAttempt
>= 0)
6938 if (now
- intf
->NextSPSAttemptTime
>= 0)
6940 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
6941 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
6942 SendSPSRegistration(m
, intf
, zeroID
);
6943 // Don't need to "goto notready" here, because if we do still have record registrations
6944 // that have not been acknowledged yet, we'll catch that in the record list scan below.
6947 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
6948 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
6951 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
6952 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6954 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
6955 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
6957 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
6958 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
6963 // Scan list of registered records
6964 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
6965 if (!AuthRecord_uDNS(rr
))
6966 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
6967 { 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
; }
6969 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
6970 for (q
= m
->Questions
; q
; q
= q
->next
)
6971 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
6973 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
6977 // Scan list of registered records
6978 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
6979 if (AuthRecord_uDNS(rr
))
6981 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
6982 { 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
; }
6983 #if APPLE_OSX_mDNSResponder
6984 if (!RecordReadyForSleep(m
, rr
)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m
, rr
)); goto notready
; }
6993 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
6994 // and allow up to ten seconds more to complete wide-area deregistration instead
6995 if (now
- m
->SleepLimit
>= 0)
6997 LogMsg("Failed to register with SPS, now sending goodbyes");
6999 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7000 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
7002 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7003 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
7004 mDNS_DeactivateNetWake_internal(m
, intf
);
7007 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7008 if (!AuthRecord_uDNS(rr
))
7009 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7011 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
));
7012 rr
->updateIntID
= zeroOpaque64
;
7015 // We'd really like to allow up to ten seconds more here,
7016 // but if we don't respond to the sleep notification within 30 seconds
7017 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7018 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7019 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7020 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7021 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
7023 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
7031 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
)
7035 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7036 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7037 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7038 // and if that happens we don't want to just give up and go back to sleep and never try again.
7039 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
7041 NATTraversalInfo
*nat
;
7042 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
7043 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
7045 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
7046 if (e
- t
> 0) e
= t
;
7047 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7048 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
7049 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
7050 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
7051 nat
->retryInterval
/ mDNSPlatformOneSecond
,
7052 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
7053 (t
- now
) / mDNSPlatformOneSecond
);
7056 // This loop checks both the time we need to renew wide-area registrations,
7057 // and the time we need to renew Sleep Proxy registrations
7058 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
7059 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
7061 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
7062 if (e
- t
> 0) e
= t
;
7063 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7064 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
7065 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
7066 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
7067 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
7073 // ***************************************************************************
7074 #if COMPILER_LIKES_PRAGMA_MARK
7076 #pragma mark - Packet Reception Functions
7079 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7081 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
7082 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
7084 mDNSu8
*responseptr
= response
->data
;
7085 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
7086 const mDNSu8
*ptr
= query
->data
;
7088 mDNSu32 maxttl
= 0x70000000;
7091 // Initialize the response fields so we can answer the questions
7092 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
7095 // *** 1. Write out the list of questions we are actually going to answer with this packet
7099 maxttl
= kStaticCacheTTL
;
7100 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7103 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
7104 if (!ptr
) return(mDNSNULL
);
7106 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
7108 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
7109 { // then put the question in the question section
7110 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
7111 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
7112 break; // break out of the ResponseRecords loop, and go on to the next question
7117 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
7121 // *** 2. Write Answers
7123 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7124 if (rr
->NR_AnswerTo
)
7126 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
7127 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7128 if (p
) responseptr
= p
;
7129 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
7133 // *** 3. Write Additionals
7135 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7136 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
7138 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
7139 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7140 if (p
) responseptr
= p
;
7141 else debugf("GenerateUnicastResponse: No more space for additionals");
7144 return(responseptr
);
7147 // AuthRecord *our is our Resource Record
7148 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7149 // Returns 0 if there is no conflict
7150 // Returns +1 if there was a conflict and we won
7151 // Returns -1 if there was a conflict and we lost and have to rename
7152 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
7154 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
7155 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
7156 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7157 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7159 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
7160 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
7161 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
7162 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
7164 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
7165 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
7166 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
7167 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
7169 LogMsg("CompareRData ERROR: Invalid state");
7173 // See if we have an authoritative record that's identical to this packet record,
7174 // whose canonical DependentOn record is the specified master record.
7175 // The DependentOn pointer is typically used for the TXT record of service registrations
7176 // It indicates that there is no inherent conflict detection for the TXT record
7177 // -- it depends on the SRV record to resolve name conflicts
7178 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7179 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7180 // If the record has no DependentOn, then just return that record's pointer
7181 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7182 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7184 const AuthRecord
*r1
;
7185 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
7187 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
7189 const AuthRecord
*r2
= r1
;
7190 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
7191 if (r2
== master
) return(mDNStrue
);
7194 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
7196 if (IdenticalResourceRecord(&r1
->resrec
, &pktrr
->resrec
))
7198 const AuthRecord
*r2
= r1
;
7199 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
7200 if (r2
== master
) return(mDNStrue
);
7206 // Find the canonical RRSet pointer for this RR received in a packet.
7207 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7208 // pointers (if any) to make sure we return the canonical member of this name/type/class
7209 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7210 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
7212 const AuthRecord
*rr
;
7213 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7215 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7217 while (rr
->RRSet
&& rr
!= rr
->RRSet
) rr
= rr
->RRSet
;
7224 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7225 // as one of our records (our) but different rdata.
7226 // 1. If our record is not a type that's supposed to be unique, we don't care.
7227 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7228 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7229 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7230 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7231 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7232 // are members of the same RRSet, then this is not a conflict.
7233 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
7235 // If not supposed to be unique, not a conflict
7236 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
7238 // If a dependent record, not a conflict
7239 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
7242 // If the pktrr matches a member of ourset, not a conflict
7243 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
7244 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
7245 if (pktset
== ourset
) return(mDNSfalse
);
7247 // For records we're proxying, where we don't know the full
7248 // relationship between the records, having any matching record
7249 // in our AuthRecords list is sufficient evidence of non-conflict
7250 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
7253 // Okay, this is a conflict
7257 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7258 // the record list and/or question list.
7259 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7260 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7261 DNSQuestion
*q
, AuthRecord
*our
)
7264 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
7265 mDNSBool FoundUpdate
= mDNSfalse
;
7267 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
7269 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
7271 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
7273 FoundUpdate
= mDNStrue
;
7274 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
7276 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
7277 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
7278 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
7281 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
7282 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7283 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7285 // 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.
7286 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7287 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7290 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
7291 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
7292 our
->AnnounceCount
= InitialAnnounceCount
;
7293 InitializeLastAPTime(m
, our
);
7300 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7301 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7305 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7308 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
7310 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7313 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
7315 mDNSu32 slot
= HashSlot(pktrr
->name
);
7316 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, pktrr
);
7319 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7321 if (!pktrr
->InterfaceID
)
7323 mDNSu16 id1
= (pktrr
->rDNSServer
? pktrr
->rDNSServer
->resGroupID
: 0);
7324 mDNSu16 id2
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
7325 match
= (id1
== id2
);
7327 else match
= (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
);
7329 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
7333 mDNSlocal
void DeregisterProxyRecord(mDNS
*const m
, AuthRecord
*const rr
)
7335 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7336 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
7337 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7338 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7341 mDNSlocal
void ClearKeepaliveProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
, const mDNSInterfaceID InterfaceID
)
7343 if (m
->CurrentRecord
)
7344 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7345 m
->CurrentRecord
= thelist
;
7347 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7348 // clean up the keepalive record.
7349 while (m
->CurrentRecord
)
7351 AuthRecord
*const rr
= m
->CurrentRecord
;
7352 if (InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7354 if (mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
7356 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7357 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7358 DeregisterProxyRecord(m
, rr
);
7361 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7362 // new records could have been added to the end of the list as a result of that call.
7363 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7364 m
->CurrentRecord
= rr
->next
;
7368 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7369 // to check our lists and discard any stale duplicates of this record we already have
7370 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7372 if (m
->CurrentRecord
)
7373 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7374 m
->CurrentRecord
= thelist
;
7375 while (m
->CurrentRecord
)
7377 AuthRecord
*const rr
= m
->CurrentRecord
;
7378 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7379 if (IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
7381 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7382 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7383 DeregisterProxyRecord(m
, rr
);
7385 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7386 // new records could have been added to the end of the list as a result of that call.
7387 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7388 m
->CurrentRecord
= rr
->next
;
7392 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7393 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7395 if (m
->CurrentRecord
)
7396 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7397 m
->CurrentRecord
= thelist
;
7398 while (m
->CurrentRecord
)
7400 AuthRecord
*const rr
= m
->CurrentRecord
;
7401 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7402 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
7404 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
7406 // We don't do this here because we know that the host is waking up at this point, so we don't send
7407 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7408 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7409 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7410 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7411 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
7412 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
7415 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7416 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
7417 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7418 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
7419 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7420 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
7421 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7422 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7424 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7425 // new records could have been added to the end of the list as a result of that call.
7426 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7427 m
->CurrentRecord
= rr
->next
;
7431 // ProcessQuery examines a received query to see if we have any answers to give
7432 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7433 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
7434 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
7436 mDNSBool FromLocalSubnet
= srcaddr
&& mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
7437 AuthRecord
*ResponseRecords
= mDNSNULL
;
7438 AuthRecord
**nrp
= &ResponseRecords
;
7441 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
7442 CacheRecord
**eap
= &ExpectedAnswers
;
7443 #endif // POOF_ENABLED
7445 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
7446 DNSQuestion
**dqp
= &DupQuestions
;
7447 mDNSs32 delayresponse
= 0;
7448 mDNSBool SendLegacyResponse
= mDNSfalse
;
7450 mDNSu8
*responseptr
= mDNSNULL
;
7453 CacheRecord
*McastNSEC3Records
= mDNSNULL
;
7456 // *** 1. Look in Additional Section for an OPT record
7458 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
7461 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
7462 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
7464 const rdataOPT
*opt
;
7465 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
7466 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7467 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7468 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
7469 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
7471 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
7472 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
7475 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7479 // Look in Authority Section for NSEC3 record
7482 mDNSParseNSEC3Records(m
, query
, end
, InterfaceID
, &McastNSEC3Records
);
7485 // *** 2. Parse Question Section and mark potential answers
7488 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7490 mDNSBool QuestionNeedsMulticastResponse
;
7491 int NumAnswersForThisQuestion
= 0;
7492 AuthRecord
*NSECAnswer
= mDNSNULL
;
7493 DNSQuestion pktq
, *q
;
7494 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
7495 if (!ptr
) goto exit
;
7497 pktq
.AnonInfo
= mDNSNULL
;
7498 if (McastNSEC3Records
)
7499 InitializeAnonInfoForQuestion(m
, &McastNSEC3Records
, &pktq
);
7500 // The only queries that *need* a multicast response are:
7501 // * Queries sent via multicast
7503 // * that don't have the kDNSQClass_UnicastResponse bit set
7504 // These queries need multicast responses because other clients will:
7505 // * suppress their own identical questions when they see these questions, and
7506 // * expire their cache records if they don't see the expected responses
7507 // For other queries, we may still choose to send the occasional multicast response anyway,
7508 // to keep our neighbours caches warm, and for ongoing conflict detection.
7509 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
7511 if (pktq
.qclass
& kDNSQClass_UnicastResponse
)
7512 m
->mDNSStats
.UnicastBitInQueries
++;
7514 m
->mDNSStats
.NormalQueries
++;
7516 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7517 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
7519 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7520 // can result in user callbacks which may change the record list and/or question list.
7521 // Also note: we just mark potential answer records here, without trying to build the
7522 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7523 // from that list while we're in the middle of trying to build it.
7524 if (m
->CurrentRecord
)
7525 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7526 m
->CurrentRecord
= m
->ResourceRecords
;
7527 while (m
->CurrentRecord
)
7529 rr
= m
->CurrentRecord
;
7530 m
->CurrentRecord
= rr
->next
;
7531 if (AnyTypeRecordAnswersQuestion(&rr
->resrec
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
7533 m
->mDNSStats
.MatchingAnswersForQueries
++;
7534 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
7536 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
7537 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
7538 else if (ResourceRecordIsValidAnswer(rr
))
7540 NumAnswersForThisQuestion
++;
7541 // As we have verified this question to be part of the same subset,
7542 // set the anonymous data which is needed below when walk the cache
7543 // records to see what answers we should be expecting. The cache records
7544 // may cache only the nsec3RR and not the anonymous data itself.
7545 if (pktq
.AnonInfo
&& rr
->resrec
.AnonInfo
)
7546 SetAnonData(&pktq
, &rr
->resrec
, mDNStrue
);
7548 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7549 // unicast answer back to the source, because timeliness in answering probes is important.
7552 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7553 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7554 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7555 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7556 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7557 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7558 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
7560 // We only mark this question for sending if it is at least one second since the last time we multicast it
7561 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7562 // This is to guard against the case where someone blasts us with queries as fast as they can.
7563 if (m
->timenow
- (rr
->LastMCTime
+ mDNSPlatformOneSecond
) >= 0 ||
7564 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
7565 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7567 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: NR_AnswerUnicast
;
7570 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
7572 // If we don't have any answers for this question, but we do own another record with the same name,
7573 // then we'll want to mark it to generate an NSEC record on this interface
7574 if (!NSECAnswer
) NSECAnswer
= rr
;
7579 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
7581 NumAnswersForThisQuestion
++;
7582 NSECAnswer
->SendNSECNow
= InterfaceID
;
7583 m
->NextScheduledResponse
= m
->timenow
;
7586 // If we couldn't answer this question, someone else might be able to,
7587 // so use random delay on response to reduce collisions
7588 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7590 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
)
7591 m
->mDNSStats
.KnownAnswerMultiplePkts
++;
7592 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7593 if (QuestionNeedsMulticastResponse
)
7595 // We only do the following accelerated cache expiration and duplicate question suppression processing
7596 // for non-truncated multicast queries with multicast responses.
7597 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7598 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7599 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7600 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7604 const mDNSu32 slot
= HashSlot(&pktq
.qname
);
7605 CacheGroup
*cg
= CacheGroupForName(m
, slot
, pktq
.qnamehash
, &pktq
.qname
);
7608 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7609 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7610 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7611 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7612 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7613 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
7614 if (SameNameRecordAnswersQuestion(&cr
->resrec
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
7615 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
7618 eap
= &cr
->NextInKAList
;
7619 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7620 if (cr
->MPUnansweredQ
== 0 || m
->timenow
- cr
->MPLastUnansweredQT
>= mDNSPlatformOneSecond
)
7622 // Although MPUnansweredQ is only really used for multi-packet query processing,
7623 // we increment it for both single-packet and multi-packet queries, so that it stays in sync
7624 // with the MPUnansweredKA value, which by necessity is incremented for both query types.
7625 cr
->MPUnansweredQ
++;
7626 cr
->MPLastUnansweredQT
= m
->timenow
;
7627 cr
->MPExpectingKA
= mDNStrue
;
7629 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7631 #endif // POOF_ENABLED
7633 // Check if this question is the same as any of mine.
7634 // We only do this for non-truncated queries. Right now it would be too complicated to try
7635 // to keep track of duplicate suppression state between multiple packets, especially when we
7636 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7637 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7638 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7640 // For anonymous question, the duplicate suppressesion should happen if the
7641 // question belongs in the same group. As the group is expected to be
7642 // small, we don't do the optimization for now.
7645 for (q
= m
->Questions
; q
; q
=q
->next
)
7646 if (!q
->Target
.type
&& ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
7647 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
7648 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
7649 if (q
->qtype
== pktq
.qtype
&&
7650 q
->qclass
== pktq
.qclass
&&
7651 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
7652 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
7657 FreeAnonInfo(pktq
.AnonInfo
);
7662 // *** 3. Now we can safely build the list of marked answers
7664 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
7665 if (rr
->NR_AnswerTo
) // If we marked the record...
7666 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
7669 // *** 4. Add additional records
7671 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
7674 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7676 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
7678 // Get the record...
7679 CacheRecord
*ourcacherr
;
7680 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
7681 if (!ptr
) goto exit
;
7682 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
7684 // See if this Known-Answer suppresses any of our currently planned answers
7685 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7687 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7689 m
->mDNSStats
.KnownAnswerSuppressions
++;
7690 rr
->NR_AnswerTo
= mDNSNULL
;
7691 rr
->NR_AdditionalTo
= mDNSNULL
;
7695 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7696 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
7698 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7699 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7701 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7703 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
7705 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7707 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
7709 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
7711 m
->mDNSStats
.KnownAnswerSuppressions
++;
7712 rr
->ImmedAnswer
= mDNSNULL
;
7713 rr
->ImmedUnicast
= mDNSfalse
;
7714 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7715 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
7721 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
7723 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7724 // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
7725 // 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).
7726 if (ourcacherr
&& ourcacherr
->MPExpectingKA
&& m
->timenow
- ourcacherr
->MPLastUnansweredQT
< mDNSPlatformOneSecond
)
7728 ourcacherr
->MPUnansweredKA
++;
7729 ourcacherr
->MPExpectingKA
= mDNSfalse
;
7734 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7735 // any records that are suppressed by the Known Answer list in this packet.
7736 eap
= &ExpectedAnswers
;
7739 CacheRecord
*cr
= *eap
;
7740 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
7741 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
7742 else eap
= &cr
->NextInKAList
;
7744 #endif // POOF_ENABLED
7746 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7749 dqp
= &DupQuestions
;
7752 DNSQuestion
*q
= *dqp
;
7753 if (ResourceRecordAnswersQuestion(&m
->rec
.r
.resrec
, q
))
7754 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
7755 else dqp
= &q
->NextInDQList
;
7759 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7763 // *** 6. Cancel any additionals that were added because of now-deleted records
7765 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7766 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
7767 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
7770 // *** 7. Mark the send flags on the records we plan to send
7772 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7774 if (rr
->NR_AnswerTo
)
7776 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
7777 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
7779 #if !TARGET_OS_EMBEDDED
7780 // always honor kDNSQClass_UnicastResponse in embedded environment to increase reliability
7781 // in high multicast packet loss environments.
7783 // If it's been one TTL/4 since we multicast this, then send a multicast response
7784 // for conflict detection, etc.
7785 if (m
->timenow
- (rr
->LastMCTime
+ TicksTTL(rr
)/4) >= 0)
7787 SendMulticastResponse
= mDNStrue
;
7788 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7789 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7790 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7791 if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7793 m
->mDNSStats
.UnicastDemotedToMulticast
++;
7794 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7797 #endif // !TARGET_OS_EMBEDDED
7799 // If the client insists on a multicast response, then we'd better send one
7800 if (rr
->NR_AnswerTo
== NR_AnswerMulticast
)
7802 m
->mDNSStats
.MulticastResponses
++;
7803 SendMulticastResponse
= mDNStrue
;
7805 else if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7807 m
->mDNSStats
.UnicastResponses
++;
7808 SendUnicastResponse
= mDNStrue
;
7810 else if (rr
->NR_AnswerTo
)
7812 SendLegacyResponse
= mDNStrue
;
7815 if (SendMulticastResponse
|| SendUnicastResponse
)
7817 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7818 rr
->ImmedAnswerMarkTime
= m
->timenow
;
7820 m
->NextScheduledResponse
= m
->timenow
;
7821 // If we're already planning to send this on another interface, just send it on all interfaces
7822 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
7823 rr
->ImmedAnswer
= mDNSInterfaceMark
;
7826 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
7827 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
7828 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7830 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
7831 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
7833 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7835 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
7836 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
7840 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7841 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7842 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7843 // else, for a simple unique record reply, we can reply immediately; no need for delay
7844 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
7845 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7847 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== NR_AnswerMulticast
)
7849 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7850 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7851 // then the earlier client is out of luck
7852 rr
->ImmedAdditional
= InterfaceID
;
7853 // No need to set m->NextScheduledResponse here
7854 // We'll send these additional records when we send them, or not, as the case may be
7859 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7861 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
7863 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7864 mDNSs32 oldss
= m
->SuppressSending
;
7865 if (oldss
&& delayresponse
)
7866 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
7868 // Pick a random delay:
7869 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7870 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7871 // This is an integer value, with resolution determined by the platform clock rate.
7872 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7873 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7874 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7875 // on platforms where the native clock rate is less than fifty ticks per second,
7876 // we still guarantee that the final calculated delay is at least one platform tick.
7877 // We want to make sure we don't ever allow the delay to be zero ticks,
7878 // because if that happens we'll fail the Bonjour Conformance Test.
7879 // Our final computed delay is 20-120ms for normal delayed replies,
7880 // or 400-500ms in the case of multi-packet known-answer lists.
7881 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
7882 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
7883 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7884 if (oldss
&& delayresponse
)
7885 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
7890 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7892 if (SendLegacyResponse
)
7893 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
7896 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7899 // *** 10. Finally, clear our link chains ready for use next time
7901 while (ResponseRecords
)
7903 rr
= ResponseRecords
;
7904 ResponseRecords
= rr
->NextResponse
;
7905 rr
->NextResponse
= mDNSNULL
;
7906 rr
->NR_AnswerTo
= mDNSNULL
;
7907 rr
->NR_AdditionalTo
= mDNSNULL
;
7911 while (ExpectedAnswers
)
7913 CacheRecord
*cr
= ExpectedAnswers
;
7914 ExpectedAnswers
= cr
->NextInKAList
;
7915 cr
->NextInKAList
= mDNSNULL
;
7917 // For non-truncated queries, we can definitively say that we should expect
7918 // to be seeing a response for any records still left in the ExpectedAnswers list
7919 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7920 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
* 3/4)
7922 cr
->UnansweredQueries
++;
7923 cr
->LastUnansweredTime
= m
->timenow
;
7924 if (cr
->UnansweredQueries
> 1)
7925 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7926 debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
7927 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
7929 debugf("ProcessQuery: UnansweredQueries %lu %s", cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
7930 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7931 SetNextCacheCheckTimeForRecord(m
, cr
);
7934 // If we've seen multiple unanswered queries for this record,
7935 // then mark it to expire in five seconds if we don't get a response by then.
7936 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
7938 // Only show debugging message if this record was not about to expire anyway
7939 if (RRExpireTime(cr
) - m
->timenow
> (mDNSs32
) kDefaultReconfirmTimeForNoAnswer
* 4 / 3 + mDNSPlatformOneSecond
)
7940 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7941 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
7942 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
7944 LogInfo("ProcessQuery: UnansweredQueries %lu TTL %lu mDNS_Reconfirm() for %s",
7945 cr
->UnansweredQueries
, (RRExpireTime(cr
) - m
->timenow
+ mDNSPlatformOneSecond
-1) / mDNSPlatformOneSecond
, CRDisplayString(m
, cr
));
7946 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7948 m
->mDNSStats
.PoofCacheDeletions
++;
7949 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
7951 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7952 // Make a guess, based on the multi-packet query / known answer counts, whether we think we
7953 // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
7954 // possible packet loss of up to 20% of the additional KA packets.)
7955 else if (cr
->MPUnansweredQ
* 4 > cr
->MPUnansweredKA
* 5 + 8)
7957 // We want to do this conservatively.
7958 // If there are so many machines on the network that they have to use multi-packet known-answer lists,
7959 // then we don't want them to all hit the network simultaneously with their final expiration queries.
7960 // By setting the record to expire in four minutes, we achieve two things:
7961 // (a) the 90-95% final expiration queries will be less bunched together
7962 // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
7963 mDNSu32 remain
= (mDNSu32
)(RRExpireTime(cr
) - m
->timenow
) / 4;
7964 if (remain
> 240 * (mDNSu32
)mDNSPlatformOneSecond
)
7965 remain
= 240 * (mDNSu32
)mDNSPlatformOneSecond
;
7967 // Only show debugging message if this record was not about to expire anyway
7968 if (RRExpireTime(cr
) - m
->timenow
> 4 * mDNSPlatformOneSecond
)
7969 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
7970 cr
->UnansweredQueries
, cr
->MPUnansweredQ
, cr
->MPUnansweredKA
, CRDisplayString(m
, cr
));
7972 if (remain
<= 60 * (mDNSu32
)mDNSPlatformOneSecond
)
7973 cr
->UnansweredQueries
++; // Treat this as equivalent to one definite unanswered query
7974 cr
->MPUnansweredQ
= 0; // Clear MPQ/MPKA statistics
7975 cr
->MPUnansweredKA
= 0;
7976 cr
->MPExpectingKA
= mDNSfalse
;
7978 if (remain
< kDefaultReconfirmTimeForNoAnswer
)
7979 remain
= kDefaultReconfirmTimeForNoAnswer
;
7980 mDNS_Reconfirm_internal(m
, cr
, remain
);
7982 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7984 #endif // POOF_ENABLED
7986 while (DupQuestions
)
7988 DNSQuestion
*q
= DupQuestions
;
7989 DupQuestions
= q
->NextInDQList
;
7990 q
->NextInDQList
= mDNSNULL
;
7991 RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
7992 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
7993 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6");
7996 if (McastNSEC3Records
)
7998 debugf("ProcessQuery: McastNSEC3Records not used");
7999 FreeNSECRecords(m
, McastNSEC3Records
);
8002 return(responseptr
);
8005 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
8006 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8007 const mDNSInterfaceID InterfaceID
)
8009 mDNSu8
*responseend
= mDNSNULL
;
8010 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
8011 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8013 if (!dstaddr
|| (!InterfaceID
&& mDNSAddrIsDNSMulticast(dstaddr
)))
8015 const char *const reason
= !dstaddr
? "Received over TCP connection" : "Multicast, but no InterfaceID";
8016 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8017 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8018 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8019 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8020 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8021 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8022 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
, reason
);
8026 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8027 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8028 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8029 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8030 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8031 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8032 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
8034 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
8035 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
8037 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
8039 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8040 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
8041 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
8042 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
8043 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
8044 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
8049 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
8053 (void)srcaddr
; // Unused
8054 for (s
= m
->DNSServers
; s
; s
= s
->next
)
8055 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
8060 struct UDPSocket_struct
8062 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8065 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
, const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
)
8068 for (q
= m
->Questions
; q
; q
=q
->next
)
8070 if (!tcp
&& !q
->LocalSocket
) continue;
8071 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
8072 mDNSSameOpaque16(q
->TargetQID
, id
) &&
8073 q
->qtype
== question
->qtype
&&
8074 q
->qclass
== question
->qclass
&&
8075 q
->qnamehash
== question
->qnamehash
&&
8076 SameDomainName(&q
->qname
, &question
->qname
))
8082 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8083 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8084 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
8085 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
8091 for (q
= m
->Questions
; q
; q
=q
->next
)
8093 if (!q
->DuplicateOf
&& ResourceRecordAnswersUnicastResponse(&rr
->resrec
, q
))
8095 if (!mDNSOpaque16IsZero(q
->TargetQID
))
8097 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
8099 if (mDNSSameOpaque16(q
->TargetQID
, id
))
8104 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
8108 srcp
= q
->tcpSrcPort
;
8110 if (mDNSSameIPPort(srcp
, port
)) return(q
);
8112 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8113 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8114 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8115 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
8116 q
->qname
.c
, DNSTypeName(q
->qtype
), &q
->Target
, mDNSVal16(srcp
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
8122 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
8130 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8131 // Currently this applies only to rdata types containing more than one domainname,
8132 // or types where the domainname is not the last item in the structure.
8133 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
8137 case kDNSType_SOA
: return sizeof(rdataSOA
);
8138 case kDNSType_RP
: return sizeof(rdataRP
);
8139 case kDNSType_PX
: return sizeof(rdataPX
);
8140 default: return rr
->rdlength
;
8144 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
, mDNSBool Add
, const mDNSAddr
*sourceAddress
)
8146 CacheRecord
*rr
= mDNSNULL
;
8147 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
8149 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
8151 //if (RDLength > InlineCacheRDSize)
8152 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8154 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
8155 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
8156 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
8159 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
8160 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
8161 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
8162 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
8164 // We need to add the anonymous info before we call CacheRecordAdd so that
8165 // if it finds a matching question with this record, it bumps up the counters like
8166 // CurrentAnswers etc. Otherwise, when a cache entry gets removed, CacheRecordRmv
8168 if (m
->rec
.r
.resrec
.AnonInfo
)
8170 rr
->resrec
.AnonInfo
= m
->rec
.r
.resrec
.AnonInfo
;
8171 m
->rec
.r
.resrec
.AnonInfo
= mDNSNULL
;
8173 rr
->DelayDelivery
= delay
;
8175 // If this is an oversized record with external storage allocated, copy rdata to external storage
8176 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
8177 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8178 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
8179 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8180 if (RDLength
> InlineCacheRDSize
)
8181 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
8183 rr
->next
= mDNSNULL
; // Clear 'next' pointer
8184 rr
->nsec
= mDNSNULL
;
8188 rr
->sourceAddress
= *sourceAddress
;
8190 if (!rr
->resrec
.InterfaceID
)
8192 m
->rrcache_totalused_unicast
+= rr
->resrec
.rdlength
;
8193 if (DNSSECRecordType(rr
->resrec
.rrtype
))
8194 BumpDNSSECStats(m
, kStatsActionIncrement
, kStatsTypeMemoryUsage
, rr
->resrec
.rdlength
);
8199 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
8200 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
8201 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8205 // Can't use the "cg->name" if we are not adding to the cache as the
8206 // CacheGroup may be released anytime if it is empty
8207 domainname
*name
= mDNSPlatformMemAllocate(DomainNameLength(cg
->name
));
8210 AssignDomainName(name
, cg
->name
);
8211 rr
->resrec
.name
= name
;
8215 ReleaseCacheRecord(m
, rr
);
8216 NoCacheAnswer(m
, &m
->rec
.r
);
8224 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
8226 rr
->TimeRcvd
= m
->timenow
;
8227 rr
->resrec
.rroriginalttl
= ttl
;
8228 rr
->UnansweredQueries
= 0;
8229 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
8230 rr
->MPUnansweredQ
= 0;
8231 rr
->MPUnansweredKA
= 0;
8232 rr
->MPExpectingKA
= mDNSfalse
;
8234 SetNextCacheCheckTimeForRecord(m
, rr
);
8237 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
8240 const mDNSu32 slot
= HashSlot(&q
->qname
);
8241 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
8242 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
8243 if (rr
->CRActiveQuestion
== q
)
8245 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8246 RefreshCacheRecord(m
, rr
, lease
);
8250 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
8252 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
8253 else if (LLQType
== uDNS_LLQ_Events
)
8255 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8256 if (ttl
== 0xFFFFFFFF) ttl
= 0;
8257 else ttl
= kLLQ_DefLease
;
8259 else // else not LLQ (standard uDNS response)
8261 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8262 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8263 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
8265 ttl
= RRAdjustTTL(ttl
);
8267 // For mDNS, TTL zero means "delete this record"
8268 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8269 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8270 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8271 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8272 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8273 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8274 // (with the current code) result in the server having even less than three seconds to respond
8275 // before we deleted the record and reported a "remove" event to any active questions.
8276 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8277 // then things really break (e.g. we end up making a negative cache entry).
8278 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8279 if (ttl
< 15) ttl
= 15;
8285 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8287 mDNSlocal mDNSBool
IsResponseAcceptable(mDNS
*const m
, const CacheRecord
*crlist
, DNSQuestion
*q
, mDNSBool
*nseclist
)
8289 CacheRecord
*const newcr
= &m
->rec
.r
;
8290 ResourceRecord
*rr
= &newcr
->resrec
;
8291 const CacheRecord
*cr
;
8293 *nseclist
= mDNSfalse
;
8294 for (cr
= crlist
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
8296 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
8297 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8298 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8299 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8300 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8301 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8303 if (target
&& cr
->resrec
.rdatahash
== rr
->namehash
&& SameDomainName(target
, rr
->name
))
8305 LogInfo("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr
->name
->c
, CRDisplayString(m
, cr
));
8310 // Either the question requires validation or we are validating a response with DNSSEC in which case
8311 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8312 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8313 // too. nseclist is set if they have to be cached as part of the negative cache record.
8314 if (q
&& DNSSECQuestion(q
))
8316 mDNSBool same
= SameDomainName(&q
->qname
, rr
->name
);
8317 if (same
&& (q
->qtype
== rr
->rrtype
|| rr
->rrtype
== kDNSType_CNAME
))
8319 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q
->qtype
),
8320 CRDisplayString(m
, newcr
));
8323 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8324 // "nseclist" is set
8325 if (rr
->rrtype
== kDNSType_RRSIG
)
8327 RDataBody2
*const rdb
= (RDataBody2
*)newcr
->smallrdatastorage
.data
;
8328 rdataRRSig
*rrsig
= &rdb
->rrsig
;
8329 mDNSu16 typeCovered
= swap16(rrsig
->typeCovered
);
8331 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8332 // would match the qtype and they are cached normally as they are not used to prove the
8333 // non-existence of any name. In that case, it is like any other normal dnssec validation
8334 // and hence nseclist should not be set.
8336 if (same
&& ((typeCovered
== q
->qtype
) || (typeCovered
== kDNSType_CNAME
)))
8338 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m
, newcr
),
8339 DNSTypeName(q
->qtype
));
8342 else if (typeCovered
== kDNSType_NSEC
|| typeCovered
== kDNSType_NSEC3
)
8344 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m
, newcr
), DNSTypeName(typeCovered
));
8345 *nseclist
= mDNStrue
;
8348 else if (typeCovered
== kDNSType_SOA
)
8350 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m
, newcr
));
8351 *nseclist
= mDNStrue
;
8354 else return mDNSfalse
;
8356 if (rr
->rrtype
== kDNSType_NSEC
)
8358 if (!UNICAST_NSEC(rr
))
8360 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m
, newcr
));
8363 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8364 *nseclist
= mDNStrue
;
8367 if (rr
->rrtype
== kDNSType_SOA
)
8369 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8370 *nseclist
= mDNStrue
;
8373 else if (rr
->rrtype
== kDNSType_NSEC3
)
8375 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8376 *nseclist
= mDNStrue
;
8383 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
)
8385 CacheRecord
*rp
, *next
;
8387 for (rp
= NSECRecords
; rp
; rp
= next
)
8390 ReleaseCacheRecord(m
, rp
);
8394 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8395 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8396 mDNSlocal
void mDNSCoreReceiveNoDNSSECAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
8397 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
)
8400 const mDNSu8
*ptr
= response
->data
;
8402 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8405 DNSQuestion
*qptr
= mDNSNULL
;
8406 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &pktq
);
8407 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &pktq
, !dstaddr
)) &&
8408 qptr
->ValidatingResponse
)
8410 DNSQuestion
*next
, *q
;
8412 if (qptr
->DuplicateOf
)
8413 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr
->qname
.c
, DNSTypeName(qptr
->qtype
));
8415 // Be careful to call the callback for duplicate questions first and then the original
8416 // question. If we called the callback on the original question, it could stop and
8417 // a duplicate question would become the original question.
8418 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8419 for (q
= qptr
->next
; q
&& q
!= m
->NewQuestions
; q
= next
)
8422 if (q
->DuplicateOf
== qptr
)
8424 if (q
->ValidatingResponse
)
8425 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q
->qname
.c
, DNSTypeName(q
->qtype
));
8427 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q
->qname
.c
, DNSTypeName(q
->qtype
));
8428 if (q
->QuestionCallback
)
8429 q
->QuestionCallback(m
, q
, mDNSNULL
, QC_nodnssec
);
8432 if (qptr
->QuestionCallback
)
8433 qptr
->QuestionCallback(m
, qptr
, mDNSNULL
, QC_nodnssec
);
8434 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8439 mDNSlocal
void mDNSCoreReceiveNoUnicastAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
8440 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
, uDNS_LLQType LLQType
, mDNSu8 rcode
, CacheRecord
*NSECRecords
)
8443 const mDNSu8
*ptr
= response
->data
;
8444 CacheRecord
*SOARecord
= mDNSNULL
;
8446 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8449 DNSQuestion
*qptr
= mDNSNULL
;
8450 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
8451 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
8453 CacheRecord
*rr
, *neg
= mDNSNULL
;
8454 mDNSu32 slot
= HashSlot(&q
.qname
);
8455 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
8456 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
8457 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
8459 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8460 if (RRExpireTime(rr
) - m
->timenow
> 0) break;
8461 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8462 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= rr
;
8464 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8465 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8466 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8467 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8468 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8469 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8470 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8471 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8472 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8473 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8475 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8476 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8477 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8478 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8479 // do the appropriate thing. This negative response is also needed for appending new search domains.
8480 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
8484 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q
.qname
.c
, DNSTypeName(q
.qtype
));
8485 m
->CurrentQuestion
= qptr
;
8486 // We are not creating a cache record in this case, we need to pass back
8487 // the error we got so that the proxy code can return the right one to
8489 if (qptr
->ProxyQuestion
)
8490 qptr
->responseFlags
= response
->h
.flags
;
8491 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_forceresponse
);
8492 m
->CurrentQuestion
= mDNSNULL
;
8496 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for %##s (%s)", q
.qname
.c
, DNSTypeName(q
.qtype
));
8503 // We start off assuming a negative caching TTL of 60 seconds
8504 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8505 mDNSu32 negttl
= 60;
8507 const domainname
*name
= &q
.qname
;
8508 mDNSu32 hash
= q
.qnamehash
;
8510 // Special case for our special Microsoft Active Directory "local SOA" check.
8511 // Some cheap home gateways don't include an SOA record in the authority section when
8512 // they send negative responses, so we don't know how long to cache the negative result.
8513 // Because we don't want to keep hitting the root name servers with our query to find
8514 // if we're on a network using Microsoft Active Directory using "local" as a private
8515 // internal top-level domain, we make sure to cache the negative result for at least one day.
8516 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
8518 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8519 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
8521 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8522 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
8524 const mDNSu32 s
= HashSlot(m
->rec
.r
.resrec
.name
);
8525 CacheGroup
*cgSOA
= CacheGroupForRecord(m
, s
, &m
->rec
.r
.resrec
);
8526 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
8527 mDNSu32 ttl_s
= soa
->min
;
8528 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8529 // for the SOA record for ".", where the record is reported as non-cacheable
8530 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8531 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
8532 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
8533 if (negttl
< ttl_s
) negttl
= ttl_s
;
8535 // Create the SOA record as we may have to return this to the questions
8536 // that we are acting as a proxy for currently or in the future.
8537 SOARecord
= CreateNewCacheEntry(m
, s
, cgSOA
, 1, mDNSfalse
, mDNSNULL
);
8539 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8540 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8541 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8542 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8544 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8545 // along with the negative cache record. For simplicity, we don't create the additional records.
8546 if (!qptr
->ProxyQuestion
&& q
.qtype
== kDNSType_SOA
)
8548 int qcount
= CountLabels(&q
.qname
);
8549 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
8550 if (qcount
- 1 > scount
)
8551 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
8552 repeat
= qcount
- 1 - scount
;
8555 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8558 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8559 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8560 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8561 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8562 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8563 // so that we back off our polling rate and don't keep hitting the server continually.
8566 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
8567 negttl
= neg
->resrec
.rroriginalttl
* 2;
8572 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
8574 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8577 LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
8578 RefreshCacheRecord(m
, neg
, negttl
);
8579 // When we created the cache for the first time and answered the question, the question's
8580 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8581 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8582 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8583 // we should reset its question interval here to MaxQuestionInterval.
8584 ResetQuestionState(m
, qptr
);
8585 if (DNSSECQuestion(qptr
))
8586 neg
->CRDNSSECQuestion
= 1;
8587 // Update the NSEC records again.
8588 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8591 if (!AddNSECSForCacheRecord(m
, NSECRecords
, neg
, rcode
))
8593 // We might just have an SOA record for zones that are not signed and hence don't log
8595 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m
, neg
));
8596 FreeNSECRecords(m
, NSECRecords
);
8597 neg
->CRDNSSECQuestion
= 0;
8599 NSECRecords
= mDNSNULL
;
8604 ReleaseCacheRecord(m
, neg
->soa
);
8605 neg
->soa
= SOARecord
;
8606 SOARecord
= mDNSNULL
;
8612 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
8613 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
8614 m
->rec
.r
.responseFlags
= response
->h
.flags
;
8615 // We create SOA records above which might create new cache groups. Earlier
8616 // in the function we looked up the cache group for the name and it could have
8617 // been NULL. If we pass NULL cg to new cache entries that we create below,
8618 // it will create additional cache groups for the same name. To avoid that,
8619 // look up the cache group again to re-initialize cg again.
8620 cg
= CacheGroupForName(m
, slot
, hash
, name
);
8621 if (NSECRecords
&& DNSSECQuestion(qptr
))
8623 // Create the cache entry with delay and then add the NSEC records
8624 // to it and add it immediately.
8625 negcr
= CreateNewCacheEntry(m
, slot
, cg
, 1, mDNStrue
, mDNSNULL
);
8628 negcr
->CRDNSSECQuestion
= 0;
8629 if (!AddNSECSForCacheRecord(m
, NSECRecords
, negcr
, rcode
))
8631 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s",
8632 CRDisplayString(m
, negcr
));
8633 FreeNSECRecords(m
, NSECRecords
);
8637 negcr
->CRDNSSECQuestion
= 1;
8638 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m
, negcr
));
8640 NSECRecords
= mDNSNULL
;
8641 negcr
->DelayDelivery
= 0;
8642 CacheRecordDeferredAdd(m
, negcr
);
8644 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8649 // Need to add with a delay so that we can tag the SOA record
8650 negcr
= CreateNewCacheEntry(m
, slot
, cg
, 1, mDNStrue
, mDNSNULL
);
8653 negcr
->CRDNSSECQuestion
= 0;
8654 if (DNSSECQuestion(qptr
))
8655 negcr
->CRDNSSECQuestion
= 1;
8656 negcr
->DelayDelivery
= 0;
8661 ReleaseCacheRecord(m
, negcr
->soa
);
8662 negcr
->soa
= SOARecord
;
8663 SOARecord
= mDNSNULL
;
8665 CacheRecordDeferredAdd(m
, negcr
);
8668 m
->rec
.r
.responseFlags
= zeroID
;
8669 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8672 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
8673 hash
= DomainNameHashValue(name
);
8674 slot
= HashSlot(name
);
8675 // For now, we don't need to update cg here, because we'll do it again immediately, back up at the start of this loop
8676 //cg = CacheGroupForName(m, slot, hash, name);
8682 if (NSECRecords
) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m
, NSECRecords
); }
8683 if (SOARecord
) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); ReleaseCacheRecord(m
, SOARecord
); }
8686 mDNSlocal
void mDNSCorePrintStoredProxyRecords(mDNS
*const m
)
8688 AuthRecord
*rrPtr
= mDNSNULL
;
8689 LogSPS("Stored Proxy records :");
8690 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8692 LogSPS("%s", ARDisplayString(m
, rrPtr
));
8696 mDNSlocal mDNSBool
mDNSCoreRegisteredProxyRecord(mDNS
*const m
, AuthRecord
*rr
)
8698 AuthRecord
*rrPtr
= mDNSNULL
;
8700 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8702 if (IdenticalResourceRecord(&rrPtr
->resrec
, &rr
->resrec
))
8704 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m
, rr
));
8708 mDNSCorePrintStoredProxyRecords(m
);
8712 mDNSlocal CacheRecord
* mDNSCoreReceiveCacheCheck(mDNS
*const m
, const DNSMessage
*const response
, uDNS_LLQType LLQType
,
8713 const mDNSu32 slot
, CacheGroup
*cg
, DNSQuestion
*unicastQuestion
, CacheRecord
***cfp
, CacheRecord
**NSECCachePtr
,
8714 mDNSInterfaceID InterfaceID
)
8717 CacheRecord
**cflocal
= *cfp
;
8719 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
8722 // Resource record received via unicast, the resGroupID should match ?
8725 mDNSu16 id1
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
8726 mDNSu16 id2
= (m
->rec
.r
.resrec
.rDNSServer
? m
->rec
.r
.resrec
.rDNSServer
->resGroupID
: 0);
8727 match
= (id1
== id2
);
8730 match
= (rr
->resrec
.InterfaceID
== InterfaceID
);
8731 // If we found this exact resource record, refresh its TTL
8732 if (match
&& IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
8734 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
8735 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8736 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
8738 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8740 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8741 if (rr
->NextInCFList
== mDNSNULL
&& *cfp
!= &rr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
8744 cflocal
= &rr
->NextInCFList
;
8745 *cflocal
= (CacheRecord
*)1;
8746 *cfp
= &rr
->NextInCFList
;
8749 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8750 if (!(rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
8753 for (q
= m
->Questions
; q
; q
=q
->next
)
8755 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
8758 rr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
8762 if (!SameRDataBody(&m
->rec
.r
.resrec
, &rr
->resrec
.rdata
->u
, SameDomainNameCS
))
8764 // If the rdata of the packet record differs in name capitalization from the record in our cache
8765 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8766 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8767 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8768 rr
->resrec
.rroriginalttl
= 0;
8769 rr
->TimeRcvd
= m
->timenow
;
8770 rr
->UnansweredQueries
= MaxUnansweredQueries
;
8771 SetNextCacheCheckTimeForRecord(m
, rr
);
8772 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: %s", CRDisplayString(m
, rr
));
8773 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: %s", CRDisplayString(m
, &m
->rec
.r
));
8774 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8775 NextCacheCheckEvent(rr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
8776 // DO NOT break out here -- we want to continue as if we never found it
8778 else if (!IdenticalAnonInfo(m
->rec
.r
.resrec
.AnonInfo
, rr
->resrec
.AnonInfo
))
8780 // If the NSEC3 record changed, a few possibilities
8782 // 1) the peer reinitialized e.g., after network change and still part of the
8784 // 2) the peer went to a different set but we did not see the goodbyes. If we just
8785 // update the nsec3 record, it would be incorrect. Flush the cache so that we
8786 // can deliver a RMV followed by ADD.
8787 // 3) if the peer is ourselves and we see the goodbye when moving to a different set
8788 // and so we flush the cache and create a new cache record with the new set information.
8789 // Now we move back to the original set. In this case, we can't just update the
8790 // NSEC3 record alone. We need to flush so that we can deliver an RMV followed by ADD
8791 // when we create the new cache entry.
8793 // Note: For case (1), we could avoid flushing the cache but we can't tell the difference
8794 // from the other cases.
8795 rr
->resrec
.rroriginalttl
= 0;
8796 rr
->TimeRcvd
= m
->timenow
;
8797 rr
->UnansweredQueries
= MaxUnansweredQueries
;
8798 SetNextCacheCheckTimeForRecord(m
, rr
);
8799 LogInfo("mDNSCoreReceiveCacheCheck: AnonInfo changed for %s", CRDisplayString(m
, rr
));
8800 // DO NOT break out here -- we want to continue as if we never found it. When we return
8801 // from this function, we will create a new cache entry with the new NSEC3 record
8803 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
8807 m
->mDNSStats
.CacheRefreshed
++;
8809 if (rr
->resrec
.rroriginalttl
== 0) debugf("uDNS rescuing %s", CRDisplayString(m
, rr
));
8810 RefreshCacheRecord(m
, rr
, m
->rec
.r
.resrec
.rroriginalttl
);
8811 rr
->responseFlags
= response
->h
.flags
;
8813 // If we may have NSEC records returned with the answer (which we don't know yet as it
8814 // has not been processed), we need to cache them along with the first cache
8815 // record in the list that answers the question so that it can be used for validation
8816 // later. The "type" check below is to make sure that we cache on the cache record
8817 // that would answer the question. It is possible that we might cache additional things
8818 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8819 // the record that answers the question.
8820 if (response
->h
.numAnswers
&& unicastQuestion
&& unicastQuestion
->qtype
== rr
->resrec
.rrtype
8821 && !(*NSECCachePtr
))
8823 LogInfo("mDNSCoreReceiveCacheCheck: rescuing RR %s", CRDisplayString(m
, rr
));
8826 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8827 // polling the network once we get a valid response back. For the first time when a new
8828 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8829 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8830 // configuration changed, without flushing the cache, we reset the question interval here.
8831 // Currently, we do this for for both multicast and unicast questions as long as the record
8832 // type is unique. For unicast, resource record is always unique and for multicast it is
8833 // true for records like A etc. but not for PTR.
8834 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8836 for (q
= m
->Questions
; q
; q
=q
->next
)
8838 if (!q
->DuplicateOf
&& !q
->LongLived
&&
8839 ActiveQuestion(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
8841 ResetQuestionState(m
, q
);
8842 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
8843 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8851 // If the packet TTL is zero, that means we're deleting this record.
8852 // To give other hosts on the network a chance to protest, we push the deletion
8853 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8854 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8855 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8856 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8857 // If the record is already going to expire in less than one second anyway, we leave it alone --
8858 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8859 debugf("DE for %s", CRDisplayString(m
, rr
));
8860 if (RRExpireTime(rr
) - m
->timenow
> mDNSPlatformOneSecond
)
8862 rr
->resrec
.rroriginalttl
= 1;
8863 rr
->TimeRcvd
= m
->timenow
;
8864 rr
->UnansweredQueries
= MaxUnansweredQueries
;
8865 SetNextCacheCheckTimeForRecord(m
, rr
);
8874 mDNSlocal
void mDNSParseNSEC3Records(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
8875 const mDNSInterfaceID InterfaceID
, CacheRecord
**NSEC3Records
)
8881 if (!response
->h
.numAuthorities
)
8883 ptr
= LocateAuthorities(response
, end
);
8886 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8889 for (i
= 0; i
< response
->h
.numAuthorities
&& ptr
&& ptr
< end
; i
++)
8894 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8895 if (!ptr
|| m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
|| m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC3
)
8897 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr
, CRDisplayString(m
, &m
->rec
.r
));
8898 m
->rec
.r
.resrec
.RecordType
= 0;
8901 slot
= HashSlot(m
->rec
.r
.resrec
.name
);
8902 cg
= CacheGroupForRecord(m
, slot
, &m
->rec
.r
.resrec
);
8903 // Create the cache entry but don't add it to the cache it. We need
8904 // to cache this along with the main cache record.
8905 rr
= CreateNewCacheEntry(m
, slot
, cg
, 0, mDNSfalse
, mDNSNULL
);
8908 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m
, rr
));
8910 NSEC3Records
= &rr
->next
;
8912 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8916 mDNSlocal
void mDNSCoreResetRecord(mDNS
*const m
)
8918 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8919 if (m
->rec
.r
.resrec
.AnonInfo
)
8921 FreeAnonInfo(m
->rec
.r
.resrec
.AnonInfo
);
8922 m
->rec
.r
.resrec
.AnonInfo
= mDNSNULL
;
8926 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8927 // the record list and/or question list.
8928 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8929 // InterfaceID non-NULL tells us the interface this multicast response was received on
8930 // InterfaceID NULL tells us this was a unicast response
8931 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8932 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
8933 const DNSMessage
*const response
, const mDNSu8
*end
,
8934 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8935 const mDNSInterfaceID InterfaceID
)
8938 mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
8939 mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8940 DNSQuestion
*llqMatch
= mDNSNULL
;
8941 DNSQuestion
*unicastQuestion
= mDNSNULL
;
8942 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
8944 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8945 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8946 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8947 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
8948 CacheRecord
**cfp
= &CacheFlushRecords
;
8949 CacheRecord
*NSECRecords
= mDNSNULL
;
8950 CacheRecord
*NSECCachePtr
= mDNSNULL
;
8951 CacheRecord
**nsecp
= &NSECRecords
;
8952 CacheRecord
*McastNSEC3Records
= mDNSNULL
;
8954 mDNSu8 rcode
= '\0';
8955 mDNSBool rrsigsCreated
= mDNSfalse
;
8956 mDNSBool DNSSECQuestion
= mDNSfalse
;
8957 NetworkInterfaceInfo
*llintf
= FirstIPv4LLInterfaceForID(m
, InterfaceID
);
8958 mDNSBool recordAcceptedInResponse
= mDNSfalse
; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8960 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8961 // to guard against spoof responses, then the only credible protection against that is cryptographic
8962 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8963 int firstauthority
= response
->h
.numAnswers
;
8964 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
8965 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
8966 const mDNSu8
*ptr
= response
->data
;
8967 DNSServer
*uDNSServer
= mDNSNULL
;
8969 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8970 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8971 srcaddr
, dstaddr
, InterfaceID
,
8972 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
8973 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
8974 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8975 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
8977 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8978 // When a DNS client receives a reply with TC
8979 // set, it should ignore that response, and query again, using a
8980 // mechanism, such as a TCP connection, that will permit larger replies.
8981 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8982 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8983 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8984 // <rdar://problem/6690034> Can't bind to Active Directory
8985 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8986 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8987 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
8988 // and not even do the TCP query.
8989 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
8990 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
)) return;
8992 if (LLQType
== uDNS_LLQ_Ignore
) return;
8994 // 1. We ignore questions (if any) in mDNS response packets
8995 // 2. If this is an LLQ response, we handle it much the same
8996 // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
8997 // answer as being the authoritative complete RRSet, and respond by deleting all other
8998 // matching cache records that don't appear in this packet.
8999 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9000 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
|| (response
->h
.flags
.b
[0] & kDNSFlag0_TC
))
9001 ptr
= LocateAnswers(response
, end
);
9002 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9003 // in this response packet are immediately deemed to be invalid.
9006 mDNSBool failure
, returnEarly
;
9007 rcode
= (mDNSu8
)(response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
9008 failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
9009 returnEarly
= mDNSfalse
;
9010 // We could possibly combine this with the similar loop at the end of this function --
9011 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9012 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9013 // which it was received (or refreshed), and then at the end if we find any cache records which
9014 // answer questions in this packet's question section, but which aren't tagged with this packet's
9015 // packet number, then we deduce they are old and delete them
9016 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
9018 DNSQuestion q
, *qptr
= mDNSNULL
;
9019 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
9020 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
)))
9025 // Remember the unicast question that we found, which we use to make caching
9026 // decisions later on in this function
9027 const mDNSu32 slot
= HashSlot(&q
.qname
);
9028 CacheGroup
*cg
= CacheGroupForName(m
, slot
, q
.qnamehash
, &q
.qname
);
9029 if (!mDNSOpaque16IsZero(response
->h
.id
))
9031 unicastQuestion
= qptr
;
9032 if (qptr
->qDNSServer
&& DNSSECQuestion(qptr
))
9034 LogInfo("mDNSCoreReceiveResponse: Setting aware for %##s (%s) on %#a", qptr
->qname
.c
,
9035 DNSTypeName(qptr
->qtype
), &qptr
->qDNSServer
->addr
);
9036 qptr
->qDNSServer
->DNSSECAware
= mDNStrue
;
9037 qptr
->qDNSServer
->req_DO
= mDNStrue
;
9039 if (qptr
->ValidatingResponse
)
9040 DNSSECQuestion
= mDNStrue
;
9042 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
9043 if (SameNameRecordAnswersQuestion(&rr
->resrec
, qptr
))
9045 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
9046 rr
->resrec
.InterfaceID
, CRDisplayString(m
, rr
));
9047 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9048 rr
->TimeRcvd
= m
->timenow
- TicksTTL(rr
) - 1;
9049 rr
->UnansweredQueries
= MaxUnansweredQueries
;
9050 rr
->CRDNSSECQuestion
= 0;
9051 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9053 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for record %s, question %##s (%s)", CRDisplayString(m
, rr
),
9054 unicastQuestion
->qname
.c
, DNSTypeName(unicastQuestion
->qtype
));
9055 rr
->CRDNSSECQuestion
= 1;
9063 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
9064 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
9065 // req_DO to false here, the next retransmission for this question will turn off validation
9066 // and hence retransmit without the EDNS0/DOK option.
9067 if (DNSSECOptionalQuestion(qptr
) && qptr
->qDNSServer
&& !qptr
->qDNSServer
->DNSSECAware
)
9069 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query %##s (%s), clear DO flag",
9070 qptr
->qDNSServer
, rcode
, q
.qname
.c
, DNSTypeName(q
.qtype
));
9071 qptr
->qDNSServer
->req_DO
= mDNSfalse
;
9073 // For Unicast DNS Queries, penalize the DNSServer
9076 LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)",
9077 qptr
->qDNSServer
, rcode
, q
.qname
.c
, DNSTypeName(q
.qtype
));
9078 PenalizeDNSServer(m
, qptr
, response
->h
.flags
);
9081 returnEarly
= mDNStrue
;
9087 LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
9088 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
9089 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
9090 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
9091 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9092 // generate negative cache entries (we want to query the next server)
9095 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9097 BumpDNSSECStats(m
, kStatsActionSet
, kStatsTypeMsgSize
, (end
- response
->data
));
9101 // Parse the NSEC3 records from the Authority section before we process
9102 // the Answer section so that we can cache them along with the proper
9103 // cache records we create.
9104 if (mDNSOpaque16IsZero(response
->h
.id
))
9105 mDNSParseNSEC3Records(m
, response
, end
, InterfaceID
, &McastNSEC3Records
);
9107 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
9109 // All responses sent via LL multicast are acceptable for caching
9110 // All responses received over our outbound TCP connections are acceptable for caching
9111 // We accept all records in a unicast response to a multicast query once we find one that
9112 // answers an active question.
9113 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
|| recordAcceptedInResponse
;
9114 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9115 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9117 const mDNSu8 RecordType
=
9118 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
9119 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
9120 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
9121 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9123 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
)
9125 mDNSCoreResetRecord(m
);
9129 // We have already parsed the NSEC3 records and cached them approrpriately for
9130 // multicast responses.
9131 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
== kDNSType_NSEC3
)
9133 mDNSCoreResetRecord(m
);
9136 // Don't want to cache OPT or TSIG pseudo-RRs
9137 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
)
9139 mDNSCoreResetRecord(m
);
9142 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
9144 const rdataOPT
*opt
;
9145 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
9146 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9147 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9148 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
9149 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
9151 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
9152 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
9154 mDNSCoreResetRecord(m
);
9157 // if a CNAME record points to itself, then don't add it to the cache
9158 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
9160 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
9161 mDNSCoreResetRecord(m
);
9165 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9166 // In the case of active LLQs, we'll get remove events when the records actually do go away
9167 // In the case of polling LLQs, we assume the record remains valid until the next poll
9168 if (!mDNSOpaque16IsZero(response
->h
.id
))
9169 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
9171 // If response was not sent via LL multicast,
9172 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9177 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9178 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9179 // queries to get ADD/RMV events. To lookup the question, we can't use
9180 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9181 // has already matched the question using the 64 bit Id in the packet and we use that here.
9183 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
9185 // If this is a DNSSEC question that is also LongLived, don't accept records from the
9186 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
9187 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
9188 // for both negative responses and wildcard expanded positive responses as both of come
9189 // back with NSEC/NSEC3s.
9190 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9191 AcceptableResponse
= mDNSfalse
;
9193 else if (!AcceptableResponse
|| !dstaddr
)
9195 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9196 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9197 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9200 DNSQuestion
*q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
9202 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9205 // We could potentially lookup the DNS server based on the source address, but that may not work always
9206 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9207 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9208 // on the "id" and "source port", then this response answers the question and assume the response
9209 // came from the same DNS server that we sent the query to.
9213 AcceptableResponse
= mDNStrue
;
9216 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9217 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
9221 // Accept all remaining records in this unicast response to an mDNS query.
9222 recordAcceptedInResponse
= mDNStrue
;
9223 LogInfo("mDNSCoreReceiveResponse: Accepting response for query: %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
9228 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9229 // the question. The code below does that. So, make this record unacceptable for now
9232 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
9233 AcceptableResponse
= mDNSfalse
;
9238 else if (llintf
&& llintf
->IgnoreIPv4LL
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_A
)
9240 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9241 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9242 // To work with these broken routers, client devices need to blacklist these broken
9243 // routers and ignore their bogus ARP responses. Some devices implement a technique
9244 // such as the one described in US Patent 7436783, which lets clients detect and
9245 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9247 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9248 // approach of just detecting these broken routers and completely disabling IPv4
9249 // link-local communication on interfaces where a broken router is detected.
9250 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9251 // that are deemed “safe” for IPv4 link-local communication;
9252 // the flag is cleared on interfaces where a broken router is detected.
9254 // OS X and iOS will not even try to communicate with an IPv4
9255 // link-local destination on an interface without the IFEF_ARPLL flag set.
9256 // This can cause some badly written applications to freeze for a long time if they
9257 // attempt to connect to an IPv4 link-local destination address and then wait for
9258 // that connection attempt to time out before trying other candidate addresses.
9260 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9261 // records on interfaces where we know the OS will be unwilling even to attempt
9262 // communication with those IPv4 link-local destination addresses.
9263 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9265 const CacheRecord
*const rr
= &m
->rec
.r
;
9266 const RDataBody2
*const rdb
= (RDataBody2
*)rr
->smallrdatastorage
.data
;
9267 if (mDNSv4AddressIsLinkLocal(&rdb
->ipv4
))
9269 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m
, &m
->rec
.r
));
9270 mDNSCoreResetRecord(m
);
9275 // 1. Check that this packet resource record does not conflict with any of ours
9276 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
9278 if (m
->CurrentRecord
)
9279 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
9280 m
->CurrentRecord
= m
->ResourceRecords
;
9281 while (m
->CurrentRecord
)
9283 AuthRecord
*rr
= m
->CurrentRecord
;
9284 m
->CurrentRecord
= rr
->next
;
9285 // We accept all multicast responses, and unicast responses resulting from queries we issued
9286 // For other unicast responses, this code accepts them only for responses with an
9287 // (apparently) local source address that pertain to a record of our own that's in probing state
9288 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
9290 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
9292 // ... check to see if type and rdata are identical
9293 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
9295 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9296 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
9298 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9299 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
9303 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
9304 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9307 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9308 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
9310 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
9311 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9313 // If this record is marked DependentOn another record for conflict detection purposes,
9314 // then *that* record has to be bumped back to probing state to resolve the conflict
9315 if (rr
->DependentOn
)
9317 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
9318 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9321 // If we've just whacked this record's ProbeCount, don't need to do it again
9322 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
9323 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
9324 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
9325 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
9328 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
9329 // If we'd previously verified this record, put it back to probing state and try again
9330 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
9332 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m
, rr
));
9333 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
9334 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9335 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9336 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9337 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9338 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
9339 rr
->AnnounceCount
= InitialAnnounceCount
;
9340 InitializeLastAPTime(m
, rr
);
9341 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
9343 // If we're probing for this record, we just failed
9344 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
9346 // At this point in the code, we're probing for uniqueness.
9347 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9348 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9349 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9350 if (!mDNSCoreRegisteredProxyRecord(m
, rr
))
9352 // This may be a conflict due to stale packets on the network. Delay probing by a second.
9353 // If there are conflicts after 3 such attempts, then it is a true conflict.
9354 if (m
->DelayConflictProcessing
)
9356 m
->DelayConflictProcessing
--;
9357 LogMsg("Possible spurious conflict for %s. Attempt %d at suppressing probes for one second",
9358 ARDisplayString(m
, rr
), (MAX_CONFLICT_PROCESSING_DELAYS
- m
->DelayConflictProcessing
));
9359 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
9360 rr
->AnnounceCount
= InitialAnnounceCount
;
9361 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
9362 InitializeLastAPTime(m
, rr
);
9363 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
9367 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr
->ProbeCount
, ARDisplayString(m
, rr
));
9368 m
->mDNSStats
.NameConflicts
++;
9369 #if APPLE_OSX_mDNSResponder
9370 // See if this record was also registered with any D2D plugins.
9371 D2D_stop_advertising_record(rr
);
9373 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9378 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9379 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9380 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9381 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9382 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9383 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
9385 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
9386 m
->mDNSStats
.KnownUniqueNameConflicts
++;
9387 #if APPLE_OSX_mDNSResponder
9388 D2D_stop_advertising_record(rr
);
9390 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9393 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
9396 // Else, matching signature, different type or rdata, but not a considered a conflict.
9397 // If the packet record has the cache-flush bit set, then we check to see if we
9398 // have any record(s) of the same type that we should re-assert to rescue them
9399 // (see note about "multi-homing and bridged networks" at the end of this function).
9400 else if (m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
)
9401 if ((m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && m
->timenow
- rr
->LastMCTime
> mDNSPlatformOneSecond
/2)
9402 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9407 nseclist
= mDNSfalse
;
9408 if (!AcceptableResponse
)
9410 AcceptableResponse
= IsResponseAcceptable(m
, CacheFlushRecords
, unicastQuestion
, &nseclist
);
9411 if (AcceptableResponse
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
9414 // 2. See if we want to add this packet resource record to our cache
9415 // We only try to cache answers if we have a cache to put them in
9416 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9417 if (!AcceptableResponse
) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m
, &m
->rec
.r
));
9418 if (m
->rrcache_size
&& AcceptableResponse
)
9420 const mDNSu32 slot
= HashSlot(m
->rec
.r
.resrec
.name
);
9421 CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &m
->rec
.r
.resrec
);
9422 CacheRecord
*rr
= mDNSNULL
;
9424 if (McastNSEC3Records
)
9425 InitializeAnonInfoForCR(m
, &McastNSEC3Records
, &m
->rec
.r
);
9427 // 2a. Check if this packet resource record is already in our cache.
9429 // If this record should go in the nseclist, don't look in the cache for updating it.
9430 // They are supposed to be cached under the "nsec" field of the cache record for
9431 // validation. Just create the cache record.
9434 rr
= mDNSCoreReceiveCacheCheck(m
, response
, LLQType
, slot
, cg
, unicastQuestion
, &cfp
, &NSECCachePtr
, InterfaceID
);
9437 // If packet resource record not in our cache, add it now
9438 // (unless it is just a deletion of a record we never had, in which case we don't care)
9439 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
9441 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
9445 delay
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
9447 delay
= CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
, slot
, mDNSNULL
);
9449 // If unique, assume we may have to delay delivery of this 'add' event.
9450 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9451 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9452 // to schedule an mDNS_Execute task at the appropriate time.
9453 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
, !nseclist
, srcaddr
);
9456 rr
->responseFlags
= response
->h
.flags
;
9457 // If we are not creating signatures, then we need to inform DNSSEC so that
9458 // it does not wait forever. Don't do this if we got NSEC records
9459 // as it indicates that this name does not exist.
9460 if (rr
->resrec
.rrtype
== kDNSType_RRSIG
&& !nseclist
)
9462 rrsigsCreated
= mDNStrue
;
9464 // Remember whether we created a cache record in response to a DNSSEC question.
9465 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9466 rr
->CRDNSSECQuestion
= 0;
9467 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9469 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record %s, question %##s (%s)", CRDisplayString(m
, rr
),
9470 unicastQuestion
->qname
.c
, DNSTypeName(unicastQuestion
->qtype
));
9471 rr
->CRDNSSECQuestion
= 1;
9473 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9474 // which we should be creating below. It is also needed in the wildcard
9475 // expanded answer case and in that case it is cached along with the answer.
9478 rr
->TimeRcvd
= m
->timenow
;
9482 else if (AddToCFList
)
9485 cfp
= &rr
->NextInCFList
;
9486 *cfp
= (CacheRecord
*)1;
9488 else if (rr
->DelayDelivery
)
9490 ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
9496 if (rr
&& rr
->resrec
.AnonInfo
&& m
->rec
.r
.resrec
.AnonInfo
)
9498 CopyAnonInfoForCR(m
, rr
, &m
->rec
.r
);
9502 mDNSCoreResetRecord(m
);
9506 mDNSCoreResetRecord(m
);
9508 // If we've just received one or more records with their cache flush bits set,
9509 // then scan that cache slot to see if there are any old stale records we need to flush
9510 while (CacheFlushRecords
!= (CacheRecord
*)1)
9512 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
9513 const mDNSu32 slot
= HashSlot(r1
->resrec
.name
);
9514 const CacheGroup
*cg
= CacheGroupForRecord(m
, slot
, &r1
->resrec
);
9515 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
9516 r1
->NextInCFList
= mDNSNULL
;
9518 // Look for records in the cache with the same signature as this new one with the cache flush
9519 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9520 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9521 // We make these TTL adjustments *only* for records that still have *more* than one second
9522 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9523 // (and now has half a second remaining) could inadvertently get its life extended, by either
9524 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9525 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9526 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9527 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9528 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9529 // To avoid this, we need to ensure that the cache flushing operation will only act to
9530 // *decrease* a record's remaining lifetime, never *increase* it.
9531 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
9535 if (!r1
->resrec
.InterfaceID
)
9537 id1
= (r1
->resrec
.rDNSServer
? r1
->resrec
.rDNSServer
->resGroupID
: 0);
9538 id2
= (r2
->resrec
.rDNSServer
? r2
->resrec
.rDNSServer
->resGroupID
: 0);
9544 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9545 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9546 // the new RRSIG that we received. Process only if the typeCovered matches.
9547 if ((r1
->resrec
.rrtype
== r2
->resrec
.rrtype
) && (r1
->resrec
.rrtype
== kDNSType_RRSIG
))
9549 rdataRRSig
*rrsig1
= (rdataRRSig
*)(((RDataBody2
*)(r1
->resrec
.rdata
->u
.data
))->data
);
9550 rdataRRSig
*rrsig2
= (rdataRRSig
*)(((RDataBody2
*)(r2
->resrec
.rdata
->u
.data
))->data
);
9551 if (swap16(rrsig1
->typeCovered
) != swap16(rrsig2
->typeCovered
))
9553 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9554 DNSTypeName(swap16(rrsig1
->typeCovered
)), DNSTypeName(swap16(rrsig2
->typeCovered
)));
9559 // For Unicast (null InterfaceID) the resolver IDs should also match
9560 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
9561 (r1
->resrec
.InterfaceID
|| (id1
== id2
)) &&
9562 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
9563 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
)
9565 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9566 // else, if record is old, mark it to be flushed
9567 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9569 // If we find mismatched TTLs in an RRSet, correct them.
9570 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9571 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9572 // which we treat as a goodbye followed by an addition) and in that case it would be
9573 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9575 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9576 // because certain early Bonjour devices are known to have this specific mismatch, and
9577 // there's no point filling syslog with messages about something we already know about.
9578 // We also don't log this for uDNS responses, since a caching name server is obliged
9579 // to give us an aged TTL to correct for how long it has held the record,
9580 // so our received TTLs are expected to vary in that case
9582 // We also suppress log message in the case of SRV records that are received
9583 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9584 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9586 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
9588 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
9589 !(r2
->resrec
.rroriginalttl
== 120 && r1
->resrec
.rroriginalttl
== 4500 && r2
->resrec
.rrtype
== kDNSType_SRV
) &&
9590 mDNSOpaque16IsZero(response
->h
.id
))
9591 LogInfo("Correcting TTL from %4d to %4d for %s",
9592 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
9593 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
9595 r2
->TimeRcvd
= m
->timenow
;
9597 else // else, if record is old, mark it to be flushed
9599 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
9600 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
9601 // We set stale records to expire in one second.
9602 // This gives the owner a chance to rescue it if necessary.
9603 // This is important in the case of multi-homing and bridged networks:
9604 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9605 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9606 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9607 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9608 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9609 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9611 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9612 // final expiration queries for this record.
9614 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9615 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9616 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9617 // <rdar://problem/5636422> Updating TXT records is too slow
9618 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9619 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9620 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
9622 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
9623 r2
->resrec
.rroriginalttl
= 0;
9625 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9627 // We only set a record to expire in one second if it currently has *more* than a second to live
9628 // If it's already due to expire in a second or less, we just leave it alone
9629 r2
->resrec
.rroriginalttl
= 1;
9630 r2
->UnansweredQueries
= MaxUnansweredQueries
;
9631 r2
->TimeRcvd
= m
->timenow
- 1;
9632 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9633 // that we marked for deletion via an explicit DE record
9636 SetNextCacheCheckTimeForRecord(m
, r2
);
9640 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
9642 // If we had a unicast question for this response with at least one positive answer and we
9643 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9644 // signatures along with the cache record which will be used for validation later. If
9645 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9646 // use that instead.
9647 if (response
->h
.numAnswers
&& unicastQuestion
&& NSECRecords
)
9651 LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m
, r1
));
9654 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9655 // might start the verification process which needs these NSEC records
9656 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
9658 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
9659 FreeNSECRecords(m
, NSECRecords
);
9661 NSECRecords
= mDNSNULL
;
9662 NSECCachePtr
= mDNSNULL
;
9664 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
, slot
, mDNSNULL
);
9665 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9666 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
9667 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
9671 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9672 // update them now for future validations.
9673 if (NSECRecords
&& NSECCachePtr
)
9675 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m
, NSECCachePtr
));
9676 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
9678 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
9679 FreeNSECRecords(m
, NSECRecords
);
9681 NSECRecords
= mDNSNULL
;
9682 NSECCachePtr
= mDNSNULL
;
9685 // If there is at least one answer and we did not create RRSIGs and there was a
9686 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9687 // were created. We don't need to give a hint:
9689 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9690 // generate a negative response
9692 // - if we have NSECRecords, it means we might have a potential proof for
9693 // non-existence of name that we are looking for
9695 if (response
->h
.numAnswers
&& !rrsigsCreated
&& DNSSECQuestion
&& !NSECRecords
)
9696 mDNSCoreReceiveNoDNSSECAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
);
9698 // See if we need to generate negative cache entries for unanswered unicast questions
9699 mDNSCoreReceiveNoUnicastAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
, LLQType
, rcode
, NSECRecords
);
9701 if (McastNSEC3Records
)
9703 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9704 FreeNSECRecords(m
, McastNSEC3Records
);
9708 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9709 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9710 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9711 // that warrants waking the sleeping host.
9712 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9714 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
9716 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9717 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9718 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9719 // simple, we use the same mechanism for both lists.
9722 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9725 m
->CurrentRecord
= thelist
;
9726 while (m
->CurrentRecord
)
9728 AuthRecord
*const rr
= m
->CurrentRecord
;
9729 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
9731 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m
, rr
));
9732 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
9734 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
9735 m
->CurrentRecord
= rr
->next
;
9739 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
9741 if (!e
->l
[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9742 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
9743 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
9746 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
9748 if (result
&& result
!= mStatus_MemFree
)
9749 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
9751 if (result
== mStatus_NameConflict
)
9754 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
9755 if (ar
->WakeUp
.HMAC
.l
[0])
9757 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
, mDNSfalse
); // Send one wakeup magic packet
9758 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
); // Schedule all other records with the same owner to be woken
9763 if (result
== mStatus_NameConflict
|| result
== mStatus_MemFree
)
9766 mDNSPlatformMemFree(ar
);
9767 mDNS_UpdateAllowSleep(m
);
9771 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
)
9778 for (i
= 0; ptr
< limit
&& *ptr
!= ' ' && i
< 17; i
++, ptr
++)
9780 hval
= HexVal(*ptr
);
9786 else if (*ptr
== ':')
9790 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons
, val
);
9793 eth
->b
[colons
] = val
;
9800 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons
);
9803 eth
->b
[colons
] = val
;
9807 mDNSlocal mDNSu8
*GetValueForIPv6Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv6Addr
*v6
)
9812 int digitsProcessed
;
9817 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9818 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9820 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9821 // the result in "v6"
9823 numColons
= numBytes
= value
= digitsProcessed
= zeroFillStart
= 0;
9824 while (ptr
< limit
&& *ptr
!= ' ')
9826 hval
= HexVal(*ptr
);
9831 digitsProcessed
= 1;
9833 else if (*ptr
== ':')
9835 if (!digitsProcessed
)
9837 // If we have already seen a "::", we should not see one more. Handle the special
9841 // if we never filled any bytes and the next character is space (we have reached the end)
9843 if (!numBytes
&& (ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
9845 mDNSPlatformMemZero(v6
->b
, 16);
9848 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart
);
9852 // We processed "::". We need to fill zeroes later. For now, mark the
9853 // point where we will start filling zeroes from.
9854 zeroFillStart
= numBytes
;
9857 else if ((ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
9859 // We have a trailing ":" i.e., no more characters after ":"
9860 LogMsg("GetValueForIPv6Addr: Trailing colon");
9865 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9866 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9867 // filled here is 12 and 13.
9868 if (numBytes
> 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes
); return mDNSNULL
; }
9870 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
9871 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
9872 digitsProcessed
= value
= 0;
9874 // Make sure that we did not fill the 13th and 14th byte above
9875 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes
); return mDNSNULL
; }
9881 // We should be processing the last set of bytes following the last ":" here
9882 if (!digitsProcessed
)
9884 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes
);
9888 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes
); return mDNSNULL
; }
9889 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
9890 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
9895 for (i
= 0; i
< zeroFillStart
; i
++)
9896 v6
->b
[i
] = v6addr
[i
];
9897 for (j
= i
, n
= 0; n
< 16 - numBytes
; j
++, n
++)
9899 for (; j
< 16; i
++, j
++)
9900 v6
->b
[j
] = v6addr
[i
];
9902 else if (numBytes
== 16)
9903 mDNSPlatformMemCopy(v6
->b
, v6addr
, 16);
9906 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes
);
9912 mDNSlocal mDNSu8
*GetValueForIPv4Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv4Addr
*v4
)
9918 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
9920 if (*ptr
>= '0' && *ptr
<= '9')
9921 val
= val
* 10 + *ptr
- '0';
9922 else if (*ptr
== '.')
9924 if (val
> 255 || dots
>= 3)
9926 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
);
9929 v4
->b
[dots
++] = val
;
9934 // We have a zero at the end and if we reached that, then we are done.
9935 if (*ptr
== 0 && ptr
== limit
- 1 && dots
== 3)
9940 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
); return mDNSNULL
; }
9943 if (dots
!= 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots
); return mDNSNULL
; }
9948 mDNSlocal mDNSu8
*GetValueForKeepalive(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSu32
*value
)
9953 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
9955 if (*ptr
< '0' || *ptr
> '9')
9957 // We have a zero at the end and if we reached that, then we are done.
9958 if (*ptr
== 0 && ptr
== limit
- 1)
9963 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr
, ptr
, limit
, *(ptr
+ 1)); return mDNSNULL
; }
9965 val
= val
* 10 + *ptr
- '0';
9971 mDNSexport mDNSBool
mDNSValidKeepAliveRecord(AuthRecord
*rr
)
9973 mDNSAddr laddr
, raddr
;
9975 mDNSIPPort lport
, rport
;
9976 mDNSu32 timeout
, seq
, ack
;
9979 if (!mDNS_KeepaliveRecord(&rr
->resrec
))
9984 timeout
= seq
= ack
= 0;
9986 laddr
= raddr
= zeroAddr
;
9987 lport
= rport
= zeroIPPort
;
9990 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
9992 if (mDNSAddressIsZero(&laddr
) || mDNSIPPortIsZero(lport
) ||
9993 mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(rport
) ||
9994 mDNSEthAddressIsZero(eth
))
10003 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
, mDNSu32
*seq
,
10004 mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
)
10006 if (ar
->resrec
.rrtype
!= kDNSType_NULL
)
10009 if (mDNS_KeepaliveRecord(&ar
->resrec
))
10011 int len
= ar
->resrec
.rdlength
;
10012 mDNSu8
*ptr
= &ar
->resrec
.rdata
->u
.txt
.c
[1];
10013 mDNSu8
*limit
= ptr
+ len
- 1; // Exclude the first byte that is the length
10016 while (ptr
< limit
)
10018 mDNSu8 param
= *ptr
;
10019 ptr
+= 2; // Skip the letter and the "="
10022 laddr
->type
= mDNSAddrType_IPv4
;
10023 ptr
= GetValueForIPv4Addr(ptr
, limit
, &laddr
->ip
.v4
);
10025 else if (param
== 'd')
10027 raddr
->type
= mDNSAddrType_IPv4
;
10028 ptr
= GetValueForIPv4Addr(ptr
, limit
, &raddr
->ip
.v4
);
10030 else if (param
== 'H')
10032 laddr
->type
= mDNSAddrType_IPv6
;
10033 ptr
= GetValueForIPv6Addr(ptr
, limit
, &laddr
->ip
.v6
);
10035 else if (param
== 'D')
10037 raddr
->type
= mDNSAddrType_IPv6
;
10038 ptr
= GetValueForIPv6Addr(ptr
, limit
, &raddr
->ip
.v6
);
10040 else if (param
== 'm')
10042 ptr
= GetValueForMACAddr(ptr
, limit
, eth
);
10046 ptr
= GetValueForKeepalive(ptr
, limit
, &value
);
10048 if (!ptr
) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10050 // Extract everything in network order so that it is easy for sending a keepalive and also
10051 // for matching incoming TCP packets
10056 //if (*timeout < 120) *timeout = 120;
10067 lport
->NotAnInteger
= swap16((mDNSu16
)value
);
10070 rport
->NotAnInteger
= swap16((mDNSu16
)value
);
10073 *seq
= swap32(value
);
10076 *ack
= swap32(value
);
10079 *win
= swap16((mDNSu16
)value
);
10082 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param
);
10086 ptr
++; // skip the space
10091 // 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
10092 // the clients need not retrieve this information from the auth record again.
10093 mDNSlocal AuthRecord
* mDNS_MatchKeepaliveInfo(mDNS
*const m
, const mDNSAddr
* pladdr
, const mDNSAddr
* praddr
, const mDNSIPPort plport
,
10094 const mDNSIPPort prport
, mDNSu32
*rseq
, mDNSu32
*rack
)
10097 mDNSAddr laddr
, raddr
;
10099 mDNSIPPort lport
, rport
;
10100 mDNSu32 timeout
, seq
, ack
;
10103 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10105 timeout
= seq
= ack
= 0;
10107 laddr
= raddr
= zeroAddr
;
10108 lport
= rport
= zeroIPPort
;
10110 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10112 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10114 // Did we parse correctly ?
10115 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10117 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10121 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10122 &laddr
, pladdr
, &raddr
, praddr
, mDNSVal16(lport
), mDNSVal16(plport
), mDNSVal16(rport
), mDNSVal16(prport
));
10124 // Does it match the incoming TCP packet ?
10125 if (mDNSSameAddress(&laddr
, pladdr
) && mDNSSameAddress(&raddr
, praddr
) && mDNSSameIPPort(lport
, plport
) && mDNSSameIPPort(rport
, prport
))
10127 // returning in network order
10136 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
)
10140 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10142 mDNSu32 timeout
, seq
, ack
;
10144 mDNSAddr laddr
, raddr
;
10146 mDNSIPPort lport
, rport
;
10148 timeout
= seq
= ack
= 0;
10151 laddr
= raddr
= zeroAddr
;
10152 lport
= rport
= zeroIPPort
;
10154 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10156 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10158 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10160 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10163 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10165 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10166 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10167 if (!ar
->KATimeExpire
|| (m
->timenow
- ar
->KATimeExpire
>= 0))
10169 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10170 ar
->KATimeExpire
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
10172 if (m
->NextScheduledKA
- ar
->KATimeExpire
> 0)
10173 m
->NextScheduledKA
= ar
->KATimeExpire
;
10177 mDNSlocal
void mDNS_SendKeepaliveACK(mDNS
*const m
, AuthRecord
*ar
)
10179 mDNSu32 timeout
, seq
, ack
, seqInc
;
10181 mDNSAddr laddr
, raddr
;
10183 mDNSIPPort lport
, rport
;
10186 if (ar
== mDNSNULL
)
10188 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10192 timeout
= seq
= ack
= 0;
10195 laddr
= raddr
= zeroAddr
;
10196 lport
= rport
= zeroIPPort
;
10198 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10200 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10202 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10206 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10207 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10208 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10209 // it's converted to host byte order before incrementing it by one.
10210 ptr
= (mDNSu8
*)&seq
;
10211 seqInc
= (mDNSu32
)((ptr
[0] << 24) | (ptr
[1] << 16) | (ptr
[2] << 8) | ptr
[3]) + 1;
10212 ptr
[0] = (mDNSu8
)((seqInc
>> 24) & 0xFF);
10213 ptr
[1] = (mDNSu8
)((seqInc
>> 16) & 0xFF);
10214 ptr
[2] = (mDNSu8
)((seqInc
>> 8) & 0xFF);
10215 ptr
[3] = (mDNSu8
)((seqInc
) & 0xFF);
10216 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10217 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10220 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
10221 const DNSMessage
*const msg
, const mDNSu8
*end
,
10222 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
10223 const mDNSInterfaceID InterfaceID
)
10227 mDNSu8
*p
= m
->omsg
.data
;
10228 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10229 mDNSu32 updatelease
= 0;
10232 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10233 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10234 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
10235 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
10236 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
10237 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
10238 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
10240 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
10242 if (mDNS_PacketLoggingEnabled
)
10243 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
10245 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
10248 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
10249 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
10252 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
10253 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
10255 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
10256 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
10259 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10262 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
10264 if (!updatelease
|| !owner
.HMAC
.l
[0])
10266 static int msgs
= 0;
10270 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
10271 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
10273 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
10275 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
10277 static int msgs
= 0;
10281 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
10282 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
10284 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10288 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
10290 if (updatelease
> 24 * 60 * 60)
10291 updatelease
= 24 * 60 * 60;
10293 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
10294 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
10296 ptr
= LocateAuthorities(msg
, end
);
10298 // Clear any stale TCP keepalive records that may exist
10299 ClearKeepaliveProxyRecords(m
, &owner
, m
->DuplicateRecords
, InterfaceID
);
10300 ClearKeepaliveProxyRecords(m
, &owner
, m
->ResourceRecords
, InterfaceID
);
10302 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
10304 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
10305 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
10307 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
10308 AuthRecord
*ar
= mDNSPlatformMemAllocate(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
10311 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10316 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
10317 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
10318 // All stale keepalive records have been flushed prior to this loop.
10319 if (!mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
10321 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
10322 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
10324 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, AuthRecordAny
, SPSRecordCallback
, ar
);
10325 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
10326 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
10327 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
10328 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
10329 ar
->ForceMCast
= mDNStrue
;
10330 ar
->WakeUp
= owner
;
10331 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
10333 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
10334 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10335 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10336 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
10337 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
10339 ar
->TimeRcvd
= m
->timenow
;
10340 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
10341 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
10342 m
->NextScheduledSPS
= ar
->TimeExpire
;
10343 ar
->KATimeExpire
= 0;
10344 mDNS_Register_internal(m
, ar
);
10347 mDNS_UpdateAllowSleep(m
);
10348 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
10351 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10354 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
10356 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
10357 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
10358 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
10362 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10363 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10364 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
10365 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10366 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
10367 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
10368 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
10372 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSNULL
, mDNSfalse
);
10373 mDNS_SendKeepalives(m
);
10376 mDNSlocal mDNSu32
mDNSGenerateOwnerOptForInterface(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, DNSMessage
*msg
)
10378 mDNSu8
*ptr
= msg
->data
;
10379 mDNSu8
*end
= mDNSNULL
;
10380 mDNSu32 length
= 0;
10383 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10384 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10385 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
10386 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10388 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
10389 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
10391 LogSPS("Generated OPT record : %s", ARDisplayString(m
, &opt
));
10392 end
= PutResourceRecord(msg
, ptr
, &msg
->h
.numAdditionals
, &opt
.resrec
);
10393 if (end
!= mDNSNULL
)
10395 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10396 SwapDNSHeaderBytes(msg
);
10397 length
= (end
- msg
->data
);
10400 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10405 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
)
10409 mDNSu32 updatelease
= 60 * 60; // If SPS fails to indicate lease time, assume one hour
10410 const mDNSu8
*ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
);
10415 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
10416 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
10419 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
10420 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
10421 if (o
->opt
== kDNSOpt_Lease
)
10423 updatelease
= o
->u
.updatelease
;
10424 LogSPS("Sleep Proxy granted lease time %4d seconds, updateid %d, InterfaceID %p", updatelease
, mDNSVal16(msg
->h
.id
), InterfaceID
);
10427 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10430 if (m
->CurrentRecord
)
10431 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
10432 m
->CurrentRecord
= m
->ResourceRecords
;
10433 while (m
->CurrentRecord
)
10435 AuthRecord
*const rr
= m
->CurrentRecord
;
10436 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
10437 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
10439 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10440 // Clear the updateid when we are done sending on all interfaces.
10441 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, InterfaceID
, mDNStrue
);
10442 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
10443 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
10444 if (mDNSOpaque64IsZero(&rr
->updateIntID
))
10445 rr
->updateid
= zeroID
;
10446 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
10447 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
));
10448 if (rr
->WakeUp
.HMAC
.l
[0])
10450 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10451 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
10452 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
10455 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10456 // new records could have been added to the end of the list as a result of that call.
10457 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
10458 m
->CurrentRecord
= rr
->next
;
10461 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10462 ifname
= InterfaceNameForID(m
, InterfaceID
);
10463 mDNSPlatformMemCopy(&spsaddr
, srcaddr
, sizeof (mDNSAddr
));
10464 mDNSPlatformStoreSPSMACAddr(&spsaddr
, ifname
);
10466 // Store the Owner OPT record for this interface.
10467 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10470 InitializeDNSMessage(&optMsg
.h
, zeroID
, ResponseFlags
);
10471 length
= mDNSGenerateOwnerOptForInterface(m
, InterfaceID
, &optMsg
);
10474 length
+= sizeof(DNSMessageHeader
);
10475 mDNSPlatformStoreOwnerOptRecord(ifname
, &optMsg
, length
);
10478 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10479 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10480 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
10483 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
10484 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
, DNSServer
*dnsserver
)
10486 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
10487 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
10489 // Create empty resource record
10490 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
10491 cr
->resrec
.InterfaceID
= InterfaceID
;
10492 cr
->resrec
.rDNSServer
= dnsserver
;
10493 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10494 cr
->resrec
.rrtype
= rrtype
;
10495 cr
->resrec
.rrclass
= rrclass
;
10496 cr
->resrec
.rroriginalttl
= ttl_seconds
;
10497 cr
->resrec
.rdlength
= 0;
10498 cr
->resrec
.rdestimate
= 0;
10499 cr
->resrec
.namehash
= namehash
;
10500 cr
->resrec
.rdatahash
= 0;
10501 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
10502 cr
->resrec
.rdata
->MaxRDLength
= 0;
10504 cr
->NextInKAList
= mDNSNULL
;
10505 cr
->TimeRcvd
= m
->timenow
;
10506 cr
->DelayDelivery
= 0;
10507 cr
->NextRequiredQuery
= m
->timenow
;
10508 cr
->LastUsed
= m
->timenow
;
10509 cr
->CRActiveQuestion
= mDNSNULL
;
10510 cr
->UnansweredQueries
= 0;
10511 cr
->LastUnansweredTime
= 0;
10512 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
10513 cr
->MPUnansweredQ
= 0;
10514 cr
->MPLastUnansweredQT
= 0;
10515 cr
->MPUnansweredKA
= 0;
10516 cr
->MPExpectingKA
= mDNSfalse
;
10518 cr
->NextInCFList
= mDNSNULL
;
10519 cr
->nsec
= mDNSNULL
;
10520 cr
->soa
= mDNSNULL
;
10521 cr
->CRDNSSECQuestion
= 0;
10522 // Initialize to the basic one and the caller can set it to more
10523 // specific based on the response if any
10524 cr
->responseFlags
= ResponseFlags
;
10527 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, void *const pkt
, const mDNSu8
*const end
,
10528 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
10529 const mDNSInterfaceID InterfaceID
)
10531 mDNSInterfaceID ifid
= InterfaceID
;
10532 DNSMessage
*msg
= (DNSMessage
*)pkt
;
10533 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
10534 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
10535 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
10536 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
10538 mDNSu8
*ptr
= mDNSNULL
;
10539 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10540 if (TLS
) dstaddr
= mDNSNULL
;
10542 #ifndef UNICAST_DISABLED
10543 if (mDNSSameAddress(srcaddr
, &m
->Router
))
10545 #ifdef _LEGACY_NAT_TRAVERSAL_
10546 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
10549 LNT_ConfigureRouterInfo(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
10554 if (mDNSSameIPPort(srcport
, NATPMPPort
))
10557 uDNS_ReceiveNATPacket(m
, InterfaceID
, pkt
, (mDNSu16
)(end
- (mDNSu8
*)pkt
));
10562 #ifdef _LEGACY_NAT_TRAVERSAL_
10563 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
10567 if ((unsigned)(end
- (mDNSu8
*)pkt
) < sizeof(DNSMessageHeader
))
10569 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
);
10572 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
10573 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10574 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
10575 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
10576 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
10577 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
10578 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
10580 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10582 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10583 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10584 if (srcaddr
&& !mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
10588 if (mDNSOpaque16IsZero(msg
->h
.id
))
10591 #if APPLE_OSX_mDNSResponder
10592 // Track the number of multicast packets received from a source outside our subnet.
10593 // Check the destination address to avoid accounting for spurious packets that
10594 // comes in with message id zero.
10595 if (!mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
) &&
10596 mDNSAddressIsAllDNSLinkGroup(dstaddr
))
10600 #endif // #if APPLE_OSX_mDNSResponder
10603 #ifndef UNICAST_DISABLED
10604 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
10605 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10607 ifid
= mDNSInterface_Any
;
10608 if (mDNS_PacketLoggingEnabled
)
10609 DumpPacket(m
, mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
);
10610 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
10611 // Note: mDNSCore also needs to get access to received unicast responses
10614 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10615 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10616 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
10617 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, srcaddr
, InterfaceID
);
10620 if (mDNS_LoggingEnabled
)
10622 static int msgCount
= 0;
10623 if (msgCount
< 1000) {
10626 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10627 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), end
- (mDNSu8
*)pkt
, InterfaceID
);
10628 while (i
<end
- (mDNSu8
*)pkt
)
10631 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
10632 do if (i
<end
- (mDNSu8
*)pkt
) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", ((mDNSu8
*)pkt
)[i
]);while (++i
& 15);
10633 LogInfo("%s", buffer
);
10638 // Packet reception often causes a change to the task list:
10639 // 1. Inbound queries can cause us to need to send responses
10640 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10641 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10642 // 4. Response packets that answer questions may cause our client to issue new questions
10646 // ***************************************************************************
10647 #if COMPILER_LIKES_PRAGMA_MARK
10649 #pragma mark - Searcher Functions
10652 // Targets are considered the same if both queries are untargeted, or
10653 // if both are targeted to the same address+port
10654 // (If Target address is zero, TargetPort is undefined)
10655 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
10656 (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
10658 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10659 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10660 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10661 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10662 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10664 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10665 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10666 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10667 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10668 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10669 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10670 // breaks this design principle.
10673 // If IsLLQ(Q) is true, it means the question is both:
10674 // (a) long-lived and
10675 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10676 // for multicast questions, we don't want to treat LongLived as anything special
10677 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10678 #define IsAWDLIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10680 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
10683 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10684 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10685 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10686 // further in the list.
10687 for (q
= m
->Questions
; q
&& q
!= question
; q
=q
->next
) // Scan our list for another question
10688 if (q
->InterfaceID
== question
->InterfaceID
&& // with the same InterfaceID,
10689 SameQTarget(q
, question
) && // and same unicast/multicast target settings
10690 q
->qtype
== question
->qtype
&& // type,
10691 q
->qclass
== question
->qclass
&& // class,
10692 IsLLQ(q
) == IsLLQ(question
) && // and long-lived status matches
10693 (!q
->AuthInfo
|| question
->AuthInfo
) && // to avoid deadlock, don't make public query dup of a private one
10694 (q
->AnonInfo
== question
->AnonInfo
) && // Anonymous query not a dup of normal query
10695 (q
->SuppressQuery
== question
->SuppressQuery
) && // Questions that are suppressed/not suppressed
10696 (q
->ValidationRequired
== question
->ValidationRequired
) && // Questions that require DNSSEC validation
10697 (q
->ValidatingResponse
== question
->ValidatingResponse
) && // Questions that are validating responses using DNSSEC
10698 (q
->DisallowPID
== question
->DisallowPID
) && // Disallowing a PID should not affect a PID that is allowed
10699 (q
->BrowseThreshold
== question
->BrowseThreshold
) && // browse thresholds must match
10700 q
->qnamehash
== question
->qnamehash
&&
10701 (IsAWDLIncluded(q
) == IsAWDLIncluded(question
)) && // Inclusion of AWDL interface must match
10702 SameDomainName(&q
->qname
, &question
->qname
)) // and name
10707 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10708 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
10711 DNSQuestion
*first
= mDNSNULL
;
10713 // This is referring to some other question as duplicate. No other question can refer to this
10714 // question as a duplicate.
10715 if (question
->DuplicateOf
)
10717 LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
10718 question
, question
->qname
.c
, DNSTypeName(question
->qtype
),
10719 question
->DuplicateOf
, question
->DuplicateOf
->qname
.c
, DNSTypeName(question
->DuplicateOf
->qtype
));
10723 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
10724 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
10726 q
->DuplicateOf
= first
;
10730 // If q used to be a duplicate, but now is not,
10731 // then inherit the state from the question that's going away
10732 q
->LastQTime
= question
->LastQTime
;
10733 q
->ThisQInterval
= question
->ThisQInterval
;
10734 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
10735 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
10736 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
10737 q
->RequestUnicast
= question
->RequestUnicast
;
10738 q
->LastQTxTime
= question
->LastQTxTime
;
10739 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
10740 q
->nta
= question
->nta
;
10741 q
->servAddr
= question
->servAddr
;
10742 q
->servPort
= question
->servPort
;
10743 q
->qDNSServer
= question
->qDNSServer
;
10744 q
->validDNSServers
= question
->validDNSServers
;
10745 q
->unansweredQueries
= question
->unansweredQueries
;
10746 q
->noServerResponse
= question
->noServerResponse
;
10747 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
10749 q
->TargetQID
= question
->TargetQID
;
10750 q
->LocalSocket
= question
->LocalSocket
;
10751 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10753 q
->state
= question
->state
;
10754 // q->tcp = question->tcp;
10755 q
->ReqLease
= question
->ReqLease
;
10756 q
->expire
= question
->expire
;
10757 q
->ntries
= question
->ntries
;
10758 q
->id
= question
->id
;
10760 question
->LocalSocket
= mDNSNULL
;
10761 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
10762 // question->tcp = mDNSNULL;
10764 if (q
->LocalSocket
)
10765 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10769 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10770 q
->nta
->ZoneDataContext
= q
;
10773 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10774 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10776 if (question
->state
== LLQ_Established
)
10778 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10779 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10782 SetNextQueryTime(m
,q
);
10787 mDNSexport McastResolver
*mDNS_AddMcastResolver(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, mDNSu32 timeout
)
10789 McastResolver
**p
= &m
->McastResolvers
;
10790 McastResolver
*tmp
= mDNSNULL
;
10792 if (!d
) d
= (const domainname
*)"";
10794 LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d
->c
, interface
, timeout
);
10798 while (*p
) // Check if we already have this {interface, domain} tuple registered
10800 if ((*p
)->interface
== interface
&& SameDomainName(&(*p
)->domain
, d
))
10802 if (!((*p
)->flags
& McastResolver_FlagDelete
)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d
->c
, interface
);
10803 (*p
)->flags
&= ~McastResolver_FlagDelete
;
10806 tmp
->next
= mDNSNULL
;
10812 if (tmp
) *p
= tmp
; // move to end of list, to ensure ordering from platform layer
10815 // allocate, add to list
10816 *p
= mDNSPlatformMemAllocate(sizeof(**p
));
10817 if (!*p
) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10820 (*p
)->interface
= interface
;
10821 (*p
)->flags
= McastResolver_FlagNew
;
10822 (*p
)->timeout
= timeout
;
10823 AssignDomainName(&(*p
)->domain
, d
);
10824 (*p
)->next
= mDNSNULL
;
10830 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
10833 if (server
->penaltyTime
!= 0)
10835 ptime
= server
->penaltyTime
- m
->timenow
;
10838 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10839 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10841 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10842 ptime
, server
->penaltyTime
, m
->timenow
);
10843 server
->penaltyTime
= 0;
10850 //Checks to see whether the newname is a better match for the name, given the best one we have
10851 //seen so far (given in bestcount).
10852 //Returns -1 if the newname is not a better match
10853 //Returns 0 if the newname is the same as the old match
10854 //Returns 1 if the newname is a better match
10855 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
10858 // If the name contains fewer labels than the new server's domain or the new name
10859 // contains fewer labels than the current best, then it can't possibly be a better match
10860 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
10862 // If there is no match, return -1 and the caller will skip this newname for
10865 // If we find a match and the number of labels is the same as bestcount, then
10866 // we return 0 so that the caller can do additional logic to pick one of
10867 // the best based on some other factors e.g., penaltyTime
10869 // If we find a match and the number of labels is more than bestcount, then we
10870 // return 1 so that the caller can pick this over the old one.
10872 // Note: newcount can either be equal or greater than bestcount beause of the
10875 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
10876 return bestcount
== newcount
? 0 : 1;
10881 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10882 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10883 // names. In that case, we give a default timeout of 5 seconds
10884 #define DEFAULT_MCAST_TIMEOUT 5
10885 mDNSlocal mDNSu32
GetTimeoutForMcastQuestion(mDNS
*m
, DNSQuestion
*question
)
10887 McastResolver
*curmatch
= mDNSNULL
;
10888 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
10889 McastResolver
*curr
;
10890 int bettermatch
, currcount
;
10891 for (curr
= m
->McastResolvers
; curr
; curr
= curr
->next
)
10893 currcount
= CountLabels(&curr
->domain
);
10894 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
10895 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10896 // the timeout value from the first one
10897 if (bettermatch
== 1)
10900 bestmatchlen
= currcount
;
10903 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question
->qname
.c
, curmatch
,
10904 curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
10905 return ( curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
10908 // Returns true if it is a Domain Enumeration Query
10909 mDNSexport mDNSBool
DomainEnumQuery(const domainname
*qname
)
10911 const mDNSu8
*mDNS_DEQLabels
[] = { (const mDNSu8
*)"\001b", (const mDNSu8
*)"\002db", (const mDNSu8
*)"\002lb",
10912 (const mDNSu8
*)"\001r", (const mDNSu8
*)"\002dr", (const mDNSu8
*)mDNSNULL
, };
10913 const domainname
*d
= qname
;
10914 const mDNSu8
*label
;
10917 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10918 if (CountLabels(qname
) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname
->c
); return mDNSfalse
; }
10920 label
= (const mDNSu8
*)d
;
10921 while (mDNS_DEQLabels
[i
] != (const mDNSu8
*)mDNSNULL
)
10923 if (SameDomainLabel(mDNS_DEQLabels
[i
], label
)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
); break;}
10926 if (mDNS_DEQLabels
[i
] == (const mDNSu8
*)mDNSNULL
)
10928 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname
->c
);
10931 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
);
10933 // CountLabels already verified the number of labels
10934 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Second Label
10935 label
= (const mDNSu8
*)d
;
10936 if (!SameDomainLabel(label
, (const mDNSu8
*)"\007_dns-sd"))
10938 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname
->c
);
10941 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname
->c
);
10943 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Third Label
10944 label
= (const mDNSu8
*)d
;
10945 if (!SameDomainLabel(label
, (const mDNSu8
*)"\004_udp"))
10947 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname
->c
);
10950 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname
->c
);
10952 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname
->c
);
10957 // Note: InterfaceID is the InterfaceID of the question
10958 mDNSlocal mDNSBool
DNSServerMatch(DNSServer
*d
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
10960 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
10961 // with "scoped" set to kScopeNone)
10963 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
10964 // with "scoped" set to kScopeInterfaceId) and their InterfaceIDs should match.
10966 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
10967 // with "scoped" set to kScopeServiceID) and their ServiceIDs should match.
10969 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
10970 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
10972 // If the first condition fails, following are the possible cases (the notes below are using
10973 // InterfaceID for discussion and the same holds good for ServiceID):
10975 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
10976 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
10978 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
10979 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
10980 // would fail in this case.
10982 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
10983 // should match (Refer to (2) above).
10985 // Note: mDNSInterface_Unicast is used only by .local unicast questions and are treated as unscoped.
10986 // If a question is scoped both to InterfaceID and ServiceID, the question will be scoped to InterfaceID.
10988 if (((d
->scoped
== kScopeNone
) && ((!InterfaceID
&& ServiceID
== -1) || InterfaceID
== mDNSInterface_Unicast
)) ||
10989 ((d
->scoped
== kScopeInterfaceID
) && d
->interface
== InterfaceID
) ||
10990 ((d
->scoped
== kScopeServiceID
) && d
->serviceID
== ServiceID
))
10997 // Sets all the Valid DNS servers for a question
10998 mDNSexport mDNSu32
SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
11000 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
11002 int bettermatch
, currcount
;
11004 mDNSu32 timeout
= 0;
11007 question
->validDNSServers
= zeroOpaque64
;
11008 DEQuery
= DomainEnumQuery(&question
->qname
);
11009 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11011 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scoped
);
11012 // skip servers that will soon be deleted
11013 if (curr
->flags
& DNSServer_FlagDelete
)
11015 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
);
11019 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11020 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11021 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11022 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11023 // match the scoped entries by mistake.
11025 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11027 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11028 if ((curr
->scoped
== kScopeInterfaceID
&& curr
->interface
== mDNSInterface_Any
) || (curr
->scoped
== kScopeServiceID
&& curr
->serviceID
<= 0))
11030 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]", curr
->scoped
, &curr
->addr
, curr
->domain
.c
, curr
->interface
, curr
->serviceID
);
11034 currcount
= CountLabels(&curr
->domain
);
11035 if ((!curr
->cellIntf
|| (!DEQuery
&& !(question
->flags
& kDNSServiceFlagsDenyCellular
))) &&
11036 DNSServerMatch(curr
, question
->InterfaceID
, question
->ServiceID
))
11038 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11040 // If we found a better match (bettermatch == 1) then clear all the bits
11041 // corresponding to the old DNSServers that we have may set before and start fresh.
11042 // If we find an equal match, then include that DNSServer also by setting the corresponding
11044 if ((bettermatch
== 1) || (bettermatch
== 0))
11046 bestmatchlen
= currcount
;
11049 debugf("SetValidDNSServers: Resetting all the bits");
11050 question
->validDNSServers
= zeroOpaque64
;
11053 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11054 " Timeout %d, interface %p", question
->qname
.c
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
, index
, curr
->timeout
,
11056 timeout
+= curr
->timeout
;
11058 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question
->qname
.c
, &curr
->addr
, curr
->cellIntf
);
11059 bit_set_opaque64(question
->validDNSServers
, index
);
11064 question
->noServerResponse
= 0;
11066 debugf("SetValidDNSServers: ValidDNSServer bits 0x%x%x for question %p %##s (%s)",
11067 question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11068 // If there are no matching resolvers, then use the default timeout value.
11069 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
11070 return ((question
->ProxyQuestion
|| question
->ValidatingResponse
) ? DEFAULT_UDNSSEC_TIMEOUT
: timeout
? timeout
: DEFAULT_UDNS_TIMEOUT
);
11073 // Get the Best server that matches a name. If you find penalized servers, look for the one
11074 // that will come out of the penalty box soon
11075 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
, mDNSOpaque64 validBits
,
11076 int *selected
, mDNSBool nameMatch
)
11078 DNSServer
*curmatch
= mDNSNULL
;
11079 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
11081 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
11082 int bettermatch
, currcount
;
11084 int currindex
= -1;
11086 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
11087 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
11088 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11090 // skip servers that will soon be deleted
11091 if (curr
->flags
& DNSServer_FlagDelete
)
11093 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scoped
);
11097 // Check if this is a valid DNSServer
11098 if (!bit_get_opaque64(validBits
, index
))
11100 debugf("GetBestServer: continuing for index %d", index
);
11105 currcount
= CountLabels(&curr
->domain
);
11106 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
11108 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11109 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
11111 // If there are multiple best servers for a given question, we will pick the first one
11112 // if none of them are penalized. If some of them are penalized in that list, we pick
11113 // the least penalized one. BetterMatchForName walks through all best matches and
11114 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11115 // in the list when there are no penalized servers and least one among them
11116 // when there are some penalized servers.
11118 if (DNSServerMatch(curr
, InterfaceID
, ServiceID
))
11121 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11122 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11123 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11124 // part and still do some redundant steps e.g., InterfaceID match
11127 bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11131 // If we found a better match (bettermatch == 1) then we don't need to
11132 // compare penalty times. But if we found an equal match, then we compare
11133 // the penalty times to pick a better match
11135 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
11139 bestmatchlen
= currcount
;
11140 bestPenaltyTime
= currPenaltyTime
;
11145 if (selected
) *selected
= currindex
;
11149 // Look up a DNS Server, matching by name and InterfaceID
11150 mDNSlocal DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11152 DNSServer
*curmatch
= mDNSNULL
;
11153 char *ifname
= mDNSNULL
; // for logging purposes only
11154 mDNSOpaque64 allValid
;
11156 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
11157 InterfaceID
= mDNSNULL
;
11159 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
11161 // By passing in all ones, we make sure that every DNS server is considered
11162 allValid
.l
[0] = allValid
.l
[1] = 0xFFFFFFFF;
11164 curmatch
= GetBestServer(m
, name
, InterfaceID
, ServiceID
, allValid
, mDNSNULL
, mDNStrue
);
11166 if (curmatch
!= mDNSNULL
)
11167 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch
->addr
,
11168 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
11169 InterfaceID
, name
);
11171 LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname
? ifname
: "None", InterfaceID
, name
);
11176 // Look up a DNS Server for a question within its valid DNSServer bits
11177 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
11179 DNSServer
*curmatch
= mDNSNULL
;
11180 char *ifname
= mDNSNULL
; // for logging purposes only
11181 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
11182 const domainname
*name
= &question
->qname
;
11185 if ((InterfaceID
== mDNSInterface_Unicast
) || (InterfaceID
== mDNSInterface_LocalOnly
))
11186 InterfaceID
= mDNSNULL
;
11189 ifname
= InterfaceNameForID(m
, InterfaceID
);
11191 if (!mDNSOpaque64IsZero(&question
->validDNSServers
))
11193 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->ServiceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
11194 if (currindex
!= -1)
11195 bit_clr_opaque64(question
->validDNSServers
, currindex
);
11198 if (curmatch
!= mDNSNULL
)
11200 LogInfo("GetServerForQuestion: %p DNS server (%p) %#a:%d (Penalty Time Left %d) (Scope %s:%p:%d) found for name %##s (%s)",
11201 question
, curmatch
, &curmatch
->addr
, mDNSVal16(curmatch
->port
),
11202 (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
11203 InterfaceID
, question
->ServiceID
, name
, DNSTypeName(question
->qtype
));
11207 LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p:%d) found for name %##s (%s)",
11208 question
, ifname
? ifname
: "None", InterfaceID
, question
->ServiceID
, name
, DNSTypeName(question
->qtype
));
11215 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
11216 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
11218 // Called in normal client context (lock not held)
11219 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
11223 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
11224 n
->clientContext
= mDNSNULL
; // we received at least one callback since starting this NAT-T
11225 for (q
= m
->Questions
; q
; q
=q
->next
)
11226 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
11227 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
11228 #if APPLE_OSX_mDNSResponder
11229 UpdateAutoTunnelDomainStatuses(m
);
11234 mDNSlocal mDNSBool
IsPrivateDomain(mDNS
*const m
, DNSQuestion
*q
)
11236 DomainAuthInfo
*AuthInfo
;
11237 // Skip Private domains as we have special addresses to get the hosts in the Private domain
11238 AuthInfo
= GetAuthInfoForName_internal(m
, &q
->qname
);
11239 if (AuthInfo
&& !AuthInfo
->deltime
&& AuthInfo
->AutoTunnel
)
11241 debugf("IsPrivateDomain: %##s true", q
->qname
.c
);
11246 debugf("IsPrivateDomain: %##s false", q
->qname
.c
);
11251 // This function takes the DNSServer as a separate argument because sometimes the
11252 // caller has not yet assigned the DNSServer, but wants to evaluate the SuppressQuery
11253 // status before switching to it.
11254 mDNSlocal mDNSBool
ShouldSuppressUnicastQuery(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*d
)
11256 // Some callers don't check for the qtype
11257 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
)
11259 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q
->qname
.c
, DNSTypeName(q
->qtype
));
11263 // Private domains are exempted irrespective of what the DNSServer says
11264 if (IsPrivateDomain(m
, q
))
11266 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, Private Domain", q
->qname
.c
, DNSTypeName(q
->qtype
));
11272 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, as the DNS server is NULL", q
->qname
.c
, DNSTypeName(q
->qtype
));
11276 // Check if the DNS Configuration allows A/AAAA queries to be sent
11277 if ((q
->qtype
== kDNSType_A
) && (d
->req_A
))
11279 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows A queries", q
->qname
.c
,
11280 DNSTypeName(q
->qtype
), d
->domain
.c
, &d
->addr
, mDNSVal16(d
->port
));
11283 if ((q
->qtype
== kDNSType_AAAA
) && (d
->req_AAAA
))
11285 LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows AAAA queries", q
->qname
.c
,
11286 DNSTypeName(q
->qtype
), d
->domain
.c
, &d
->addr
, mDNSVal16(d
->port
));
11290 LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, since DNS Configuration does not allow (req_A is %s and req_AAAA is %s)",
11291 q
->qname
.c
, DNSTypeName(q
->qtype
), d
->req_A
? "true" : "false", d
->req_AAAA
? "true" : "false");
11296 mDNSlocal mDNSBool
ShouldSuppressDotLocalQuery(mDNS
*const m
, DNSQuestion
*q
)
11298 NetworkInterfaceInfo
*intf
;
11302 // Check to see if there is at least one interface other than loopback and don't suppress
11303 // .local questions if you find one. If we have at least one interface, it means that
11304 // we can send unicast queries for the .local name and we don't want to suppress
11305 // multicast in that case as upper layers don't know how to handle if we return a
11306 // negative response for multicast followed by a positive response for unicast.
11308 // Note: we used to check for multicast capable interfaces instead of just any interface
11309 // present. That did not work in the case where we have a valid interface for unicast
11310 // but not multicast capable e.g., cellular, as we ended up delivering a negative response
11311 // first and the upper layer did not wait for the positive response that came later.
11312 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
11314 if (intf
->InterfaceActive
&& !intf
->Loopback
)
11316 LogInfo("ShouldSuppressDotLocalQuery: Found interface %s, not suppressing", intf
->ifname
);
11321 // 1. If we find a LocalOnly or P2P record answering this question, then don't suppress it.
11322 // Set m->CurrentQuestion as it is required by AnswerQuestionWithLORecord.
11323 m
->CurrentQuestion
= q
;
11324 ret
= AnswerQuestionWithLORecord(m
, q
, mDNStrue
);
11325 m
->CurrentQuestion
= mDNSNULL
;
11329 LogInfo("ShouldSuppressDotLocalQuery: Found LocalOnly record for %##s (%s), not suppressing", q
->qname
.c
,
11330 DNSTypeName(q
->qtype
));
11334 // 2. If we find a local AuthRecord answering this question, then don't suppress it.
11335 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
11337 if (ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
11339 LogInfo("ShouldSuppressDotLocalQuery: Found resource record %s for %##s (%s) not suppressing", ARDisplayString(m
, rr
),
11340 q
->qname
.c
, DNSTypeName(q
->qtype
));
11347 mDNSlocal mDNSBool
ShouldSuppressQuery(mDNS
*const m
, DNSQuestion
*q
)
11349 if (q
->InterfaceID
== mDNSInterface_LocalOnly
)
11351 LogInfo("ShouldSuppressQuery: LocalOnly query not suppressed for %##s, qtype %s", q
->qname
.c
, DNSTypeName(q
->qtype
));
11355 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
)
11357 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q
->qname
.c
, DNSTypeName(q
->qtype
));
11361 // We still want the ability to be able to listen to the local services and hence
11362 // don't fail .local query if we have local records that can potentially answer
11364 if (q
->InterfaceID
!= mDNSInterface_Unicast
&& IsLocalDomain(&q
->qname
))
11366 if (!ShouldSuppressDotLocalQuery(m
, q
))
11368 LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", q
->qname
.c
, DNSTypeName(q
->qtype
));
11373 LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, Local question", q
->qname
.c
, DNSTypeName(q
->qtype
));
11378 return (ShouldSuppressUnicastQuery(m
, q
, q
->qDNSServer
));
11381 mDNSlocal
void CacheRecordRmvEventsForCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
11387 slot
= HashSlot(&q
->qname
);
11388 cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
11389 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
11391 // Don't deliver RMV events for negative records
11392 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
11394 LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
11395 CRDisplayString(m
, rr
), q
, q
->qname
.c
, DNSTypeName(q
->qtype
), rr
->CRActiveQuestion
, q
->CurrentAnswers
);
11399 if (SameNameRecordAnswersQuestion(&rr
->resrec
, q
))
11401 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11402 q
->qname
.c
, CRDisplayString(m
, rr
), q
->LOAddressAnswers
);
11404 q
->CurrentAnswers
--;
11405 if (rr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
11406 if (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
11408 if (rr
->CRActiveQuestion
== q
)
11411 // If this was the active question for this cache entry, it was the one that was
11412 // responsible for keeping the cache entry fresh when the cache entry was reaching
11413 // its expiry. We need to handover the responsibility to someone else. Otherwise,
11414 // when the cache entry is about to expire, we won't find an active question
11415 // (pointed by CRActiveQuestion) to refresh the cache.
11416 for (qptr
= m
->Questions
; qptr
; qptr
=qptr
->next
)
11417 if (qptr
!= q
&& ActiveQuestion(qptr
) && ResourceRecordAnswersQuestion(&rr
->resrec
, qptr
))
11421 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
11422 "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
11423 qptr
, CRDisplayString(m
,rr
), q
->CurrentAnswers
, qptr
->CurrentAnswers
, qptr
->SuppressUnusable
, qptr
->SuppressQuery
);
11425 rr
->CRActiveQuestion
= qptr
; // Question used to be active; new value may or may not be null
11426 if (!qptr
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
11428 AnswerCurrentQuestionWithResourceRecord(m
, rr
, QC_rmv
);
11429 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
11434 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
11437 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
11438 if (q
== question
) return mDNStrue
;
11442 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11448 if (m
->CurrentQuestion
)
11449 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11450 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11452 if (IsQuestionNew(m
, q
))
11454 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11457 m
->CurrentQuestion
= q
;
11458 slot
= AuthHashSlot(&q
->qname
);
11459 ag
= AuthGroupForName(&m
->rrauth
, slot
, q
->qnamehash
, &q
->qname
);
11462 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
11463 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11464 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
11466 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11467 ARDisplayString(m
, rr
));
11468 if (q
->CurrentAnswers
<= 0 || q
->LOAddressAnswers
<= 0)
11470 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11471 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
11472 q
->CurrentAnswers
, q
->LOAddressAnswers
);
11475 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_rmv
); // MUST NOT dereference q again
11476 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11479 m
->CurrentQuestion
= mDNSNULL
;
11483 // Returns false if the question got deleted while delivering the RMV events
11484 // The caller should handle the case
11485 mDNSlocal mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11487 if (m
->CurrentQuestion
)
11488 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11489 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11491 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11492 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11493 if (!IsQuestionNew(m
, q
) && !q
->LOAddressAnswers
)
11495 m
->CurrentQuestion
= q
;
11496 CacheRecordRmvEventsForCurrentQuestion(m
, q
);
11497 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11498 m
->CurrentQuestion
= mDNSNULL
;
11500 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
11504 mDNSlocal
void SuppressStatusChanged(mDNS
*const m
, DNSQuestion
*q
, DNSQuestion
**restart
)
11506 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11507 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11508 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11509 if (q
->SuppressQuery
)
11511 q
->SuppressQuery
= mDNSfalse
;
11512 if (!CacheRecordRmvEventsForQuestion(m
, q
))
11514 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from cache");
11517 q
->SuppressQuery
= mDNStrue
;
11520 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11521 // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
11522 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11523 // the restart will not be a duplicate ADD
11524 if (!LocalRecordRmvEventsForQuestion(m
, q
))
11526 LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords");
11530 // There are two cases here.
11532 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11533 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11534 // because when we get the response, if we had entries in the cache already, it will not answer
11535 // this question if the cache entry did not change. Hence, we need to restart
11536 // the query so that it can be answered from the cache.
11538 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11539 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11540 // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
11541 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11542 // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
11543 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11544 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11545 // This affects both efficiency and also the current design where there is only one active question
11546 // pointed to from a cache entry.
11548 // We restart queries in a two step process by first calling stop and build a temporary list which we
11549 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11550 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11551 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11552 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11553 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11555 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11557 LogInfo("SuppressStatusChanged: Stop question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
11558 mDNS_StopQuery_internal(m
, q
);
11559 q
->next
= *restart
;
11563 // The caller should hold the lock
11564 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
11567 DNSQuestion
*restart
= mDNSNULL
;
11569 // We look through all questions including new questions. During network change events,
11570 // we potentially restart questions here in this function that ends up as new questions,
11571 // which may be suppressed at this instance. Before it is handled we get another network
11572 // event that changes the status e.g., address becomes available. If we did not process
11573 // new questions, we would never change its SuppressQuery status.
11575 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11576 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11577 // *any* other question which could be the next one that we may process here. RestartQuestion
11578 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11579 // if the "next" question is stopped while the CurrentQuestion is stopped
11580 if (m
->RestartQuestion
)
11581 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11582 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11583 m
->RestartQuestion
= m
->Questions
;
11584 while (m
->RestartQuestion
)
11586 q
= m
->RestartQuestion
;
11587 m
->RestartQuestion
= q
->next
;
11588 if (q
->SuppressUnusable
)
11590 mDNSBool old
= q
->SuppressQuery
;
11591 q
->SuppressQuery
= ShouldSuppressQuery(m
, q
);
11592 if (q
->SuppressQuery
!= old
)
11594 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11595 // followed by a negative cache response. Temporarily turn off suppression so that
11596 // AnswerCurrentQuestionWithResourceRecord can answer the question
11597 SuppressStatusChanged(m
, q
, &restart
);
11604 restart
= restart
->next
;
11605 q
->next
= mDNSNULL
;
11606 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
11607 mDNS_StartQuery_internal(m
, q
);
11611 mDNSlocal
void RestartUnicastQuestions(mDNS
*const m
)
11614 DNSQuestion
*restart
= mDNSNULL
;
11616 if (m
->RestartQuestion
)
11617 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11618 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11619 m
->RestartQuestion
= m
->Questions
;
11620 while (m
->RestartQuestion
)
11622 q
= m
->RestartQuestion
;
11623 m
->RestartQuestion
= q
->next
;
11626 if (mDNSOpaque16IsZero(q
->TargetQID
))
11627 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11630 SuppressStatusChanged(m
, q
, &restart
);
11636 restart
= restart
->next
;
11637 q
->next
= mDNSNULL
;
11638 LogInfo("RestartUnicastQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
11639 mDNS_StartQuery_internal(m
, q
);
11644 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11645 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11646 mDNSlocal mStatus
ValidateParameters(mDNS
*const m
, DNSQuestion
*const question
)
11649 if (question
->Target
.type
&& !ValidQuestionTarget(question
))
11651 LogMsg("ValidateParameters: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
11652 question
->Target
.type
, mDNSVal16(question
->TargetPort
), question
->qname
.c
);
11653 question
->Target
.type
= mDNSAddrType_None
;
11656 // If no question->Target specified, clear TargetPort
11657 if (!question
->Target
.type
)
11658 question
->TargetPort
= zeroIPPort
;
11660 if (!ValidateDomainName(&question
->qname
))
11662 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
11663 return(mStatus_Invalid
);
11666 // If this question is referencing a specific interface, verify it exists
11667 if (question
->InterfaceID
&& !LocalOnlyOrP2PInterface(question
->InterfaceID
) && question
->InterfaceID
!= mDNSInterface_Unicast
)
11669 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
11671 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11672 (uint32_t)question
->InterfaceID
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11675 return(mStatus_NoError
);
11678 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11679 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeForQuestion()
11680 mDNSlocal
void InitDNSConfig(mDNS
*const m
, DNSQuestion
*const question
)
11682 // First reset all DNS Configuration
11683 question
->qDNSServer
= mDNSNULL
;
11684 question
->validDNSServers
= zeroOpaque64
;
11685 question
->triedAllServersOnce
= 0;
11686 question
->noServerResponse
= 0;
11687 question
->StopTime
= 0;
11688 #if TARGET_OS_EMBEDDED
11689 mDNSPlatformMemZero(&question
->metrics
, sizeof(question
->metrics
));
11692 // Need not initialize the DNS Configuration for Local Only OR P2P Questions
11693 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
11695 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11696 if (!mDNSOpaque16IsZero(question
->TargetQID
))
11698 mDNSu32 timeout
= SetValidDNSServers(m
, question
);
11699 // We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
11700 // a networking change/search domain change that calls this function again we keep
11701 // reinitializing the timeout value which means it may never timeout. If this becomes
11702 // a common case in the future, we can easily fix this by adding extra state that
11703 // indicates that we have already set the StopTime.
11705 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11706 // it gets a full timeout value even if the original question times out earlier.
11707 if (question
->TimeoutQuestion
)
11709 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11710 LogInfo("InitDNSConfig: Setting StopTime on question %p %##s (%s)", question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11713 question
->qDNSServer
= GetServerForQuestion(m
, question
);
11714 LogInfo("InitDNSConfig: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
11715 question
, question
->qname
.c
, DNSTypeName(question
->qtype
), timeout
,
11716 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11717 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11721 if (question
->TimeoutQuestion
)
11722 question
->StopTime
= NonZeroTime(m
->timenow
+ GetTimeoutForMcastQuestion(m
, question
) * mDNSPlatformOneSecond
);
11724 // Set StopTime here since it is a part of DNS Configuration
11725 if (question
->StopTime
)
11726 SetNextQueryStopTime(m
, question
);
11727 // SetNextQueryTime() need not be initialized for LocalOnly OR P2P Questions since those questions
11728 // will never be transmitted on the wire. Hence we call SetNextQueryTime() here.
11729 SetNextQueryTime(m
,question
);
11732 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11733 // state fields of the DNS Question. These are independent of the Client layer.
11734 mDNSlocal mDNSBool
InitCommonState(mDNS
*const m
, DNSQuestion
*const question
)
11738 mDNSBool isBlocked
= mDNSfalse
;
11740 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11741 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11742 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11743 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11744 // that to go out immediately.
11745 question
->next
= mDNSNULL
;
11746 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11747 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11748 // the question list to check if ThisQInterval is negative which means the question has been
11749 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11750 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11751 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11752 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11753 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
11754 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
11755 question
->DelayAnswering
= CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
, HashSlot(&question
->qname
), &purge
);
11756 question
->LastQTime
= m
->timenow
;
11757 question
->ExpectUnicastResp
= 0;
11758 question
->LastAnswerPktNum
= m
->PktNum
;
11759 question
->RecentAnswerPkts
= 0;
11760 question
->CurrentAnswers
= 0;
11762 #if APPLE_OSX_mDNSResponder
11764 // Initial browse threshold used by Finder.
11765 #define mDNSFinderBrowseThreshold 20
11767 // Set the threshold at which we move to a passive browse state,
11768 // not actively sending queries.
11769 if (question
->flags
& kDNSServiceFlagsThresholdOne
)
11770 question
->BrowseThreshold
= 1;
11771 else if (question
->flags
& kDNSServiceFlagsThresholdFinder
)
11772 question
->BrowseThreshold
= mDNSFinderBrowseThreshold
;
11774 question
->BrowseThreshold
= 0;
11776 #else // APPLE_OSX_mDNSResponder
11777 question
->BrowseThreshold
= 0;
11778 #endif // APPLE_OSX_mDNSResponder
11779 question
->CachedAnswerNeedsUpdate
= mDNSfalse
;
11781 question
->LargeAnswers
= 0;
11782 question
->UniqueAnswers
= 0;
11783 question
->LOAddressAnswers
= 0;
11784 question
->FlappingInterface1
= mDNSNULL
;
11785 question
->FlappingInterface2
= mDNSNULL
;
11787 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11788 // since we would already have the question->ServiceID in that case.
11789 if (!(question
->flags
& kDNSServiceFlagsServiceIndex
))
11791 #if APPLE_OSX_mDNSResponder
11792 mDNSPlatformGetDNSRoutePolicy(m
, question
, &isBlocked
);
11794 question
->ServiceID
= -1;
11798 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question
->qname
.c
,
11799 DNSTypeName(question
->qtype
), question
->pid
, question
->euid
, question
->ServiceID
);
11801 InitDNSConfig(m
, question
);
11803 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
11804 question
->SuppressQuery
= 0;
11805 if (question
->SuppressUnusable
)
11806 question
->SuppressQuery
= ShouldSuppressQuery(m
, question
);
11808 // If ServiceID is 0 or the policy disallows making DNS requests,
11810 question
->DisallowPID
= (question
->ServiceID
== 0 || isBlocked
);
11811 if (question
->DisallowPID
)
11812 LogInfo("InitCommonState: Query suppressed for %##s (%s), PID %d/ServiceID %d not allowed", question
->qname
.c
,
11813 DNSTypeName(question
->qtype
), question
->pid
, question
->ServiceID
);
11815 question
->NextInDQList
= mDNSNULL
;
11816 question
->SendQNow
= mDNSNULL
;
11817 question
->SendOnAll
= mDNSfalse
;
11818 question
->RequestUnicast
= kDefaultRequestUnicastCount
;
11820 #if APPLE_OSX_mDNSResponder
11821 // Set the QU bit in the first query for the following options.
11822 if ((question
->flags
& kDNSServiceFlagsUnicastResponse
) || (question
->flags
& kDNSServiceFlagsThresholdFinder
))
11824 question
->RequestUnicast
= SET_QU_IN_FIRST_QUERY
;
11825 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question
->RequestUnicast
, question
->qname
.c
,
11826 DNSTypeName(question
->qtype
));
11828 #endif // APPLE_OSX_mDNSResponder
11830 question
->LastQTxTime
= m
->timenow
;
11831 question
->CNAMEReferrals
= 0;
11833 question
->WakeOnResolveCount
= 0;
11834 if (question
->WakeOnResolve
)
11836 question
->WakeOnResolveCount
= InitialWakeOnResolveCount
;
11840 for (i
=0; i
<DupSuppressInfoSize
; i
++)
11841 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
11843 question
->Restart
= 0;
11845 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11846 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
11847 NextQSendTime(question
) - m
->timenow
,
11848 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
11849 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
11851 if (question
->DelayAnswering
)
11852 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11853 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11858 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11859 mDNSlocal
void InitWABState(DNSQuestion
*const question
)
11861 // We'll create our question->LocalSocket on demand, if needed.
11862 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11863 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11864 // NAT mapping for receiving inbound add/remove events.
11865 question
->LocalSocket
= mDNSNULL
;
11866 question
->unansweredQueries
= 0;
11867 question
->nta
= mDNSNULL
;
11868 question
->servAddr
= zeroAddr
;
11869 question
->servPort
= zeroIPPort
;
11870 question
->tcp
= mDNSNULL
;
11871 question
->NoAnswer
= NoAnswer_Normal
;
11874 mDNSlocal
void InitLLQNATState(mDNS
*const m
)
11876 // If we don't have our NAT mapping active, start it now
11877 if (!m
->LLQNAT
.clientCallback
)
11879 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
11880 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
11881 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
11882 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
11883 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal just started
11884 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
11888 mDNSlocal
void InitLLQState(DNSQuestion
*const question
)
11890 question
->state
= LLQ_InitialRequest
;
11891 question
->ReqLease
= 0;
11892 question
->expire
= 0;
11893 question
->ntries
= 0;
11894 question
->id
= zeroOpaque64
;
11897 mDNSlocal
void InitDNSPNState(DNSQuestion
*const question
)
11899 question
->dnsPushState
= DNSPUSH_INIT
;
11902 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11903 // DNSSEC & DNS Proxy fields of the DNS Question.
11904 mDNSlocal
void InitDNSSECProxyState(mDNS
*const m
, DNSQuestion
*const question
)
11908 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11909 // or the request is going over cellular interface.
11911 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11912 // at ValidationRequired setting also.
11913 if (question
->qDNSServer
)
11915 if (question
->qDNSServer
->cellIntf
)
11917 debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question
->qname
.c
, DNSTypeName(question
->qtype
));
11918 question
->ValidationRequired
= mDNSfalse
;
11920 if (DNSSECOptionalQuestion(question
) && !(question
->qDNSServer
->req_DO
))
11922 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11923 question
->qname
.c
, DNSTypeName(question
->qtype
));
11924 question
->ValidationRequired
= DNSSEC_VALIDATION_NONE
;
11927 question
->ValidationState
= (question
->ValidationRequired
? DNSSECValRequired
: DNSSECValNotRequired
);
11928 question
->ValidationStatus
= 0;
11929 question
->responseFlags
= zeroID
;
11932 // Once the question is completely initialized including the duplicate logic, this function
11933 // is called to finalize the unicast question which requires flushing the cache if needed,
11934 // activating the query etc.
11935 mDNSlocal
void FinalizeUnicastQuestion(mDNS
*const m
, DNSQuestion
*question
, mDNSBool purge
)
11937 // Ensure DNS related info of duplicate question is same as the orig question
11938 if (question
->DuplicateOf
)
11940 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
11941 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
11942 LogInfo("FinalizeUnicastQuestion: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
11943 question
, question
->DuplicateOf
, question
->qname
.c
, DNSTypeName(question
->qtype
),
11944 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11945 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11948 ActivateUnicastQuery(m
, question
, mDNSfalse
);
11950 // If purge was set above, flush the cache. Need to do this after we set the
11951 // DNS server on the question
11954 question
->DelayAnswering
= 0;
11955 mDNS_PurgeForQuestion(m
, question
);
11957 else if (!question
->DuplicateOf
&& DNSSECQuestion(question
))
11959 // For DNSSEC questions, we need to have the RRSIGs also for verification.
11960 CheckForDNSSECRecords(m
, question
);
11962 if (question
->LongLived
)
11964 // Unlike other initializations, InitLLQNATState should be done after
11965 // we determine that it is a unicast question. LongLived is set for
11966 // both multicast and unicast browse questions but we should initialize
11967 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11968 // start the NAT traversal that is not needed.
11969 InitLLQNATState(m
);
11970 #if APPLE_OSX_mDNSResponder
11971 UpdateAutoTunnelDomainStatuses(m
);
11976 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
11982 // First check for cache space (can't do queries if there is no cache space allocated)
11983 if (m
->rrcache_size
== 0)
11984 return(mStatus_NoCache
);
11986 vStatus
= ValidateParameters(m
, question
);
11991 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
11992 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
11993 if (IsHighASCIILabel(LastLabel(&question
->qname
)))
11995 domainname newname
;
11996 if (PerformNextPunycodeConversion(question
, &newname
))
11997 AssignDomainName(&question
->qname
, &newname
);
11999 #endif // USE_LIBIDN
12001 question
->TargetQID
=
12002 #ifndef UNICAST_DISABLED
12003 (question
->Target
.type
|| Question_uDNS(question
)) ? mDNS_NewMessageID(m
) :
12004 #endif // UNICAST_DISABLED
12006 debugf("mDNS_StartQuery_internal: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12008 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12010 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12011 q
= &m
->LocalOnlyQuestions
;
12012 while (*q
&& *q
!= question
)
12017 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12018 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
12019 return(mStatus_AlreadyRegistered
);
12023 // Intialize the question. The only ordering constraint we have today is that
12024 // InitDNSSECProxyState should be called after the DNS server is selected (in
12025 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12028 purge
= InitCommonState(m
, question
);
12029 InitWABState(question
);
12030 InitLLQState(question
);
12031 InitDNSPNState(question
);
12032 InitDNSSECProxyState(m
, question
);
12034 // FindDuplicateQuestion should be called last after all the intialization
12035 // as the duplicate logic could be potentially based on any field in the
12037 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
12038 if (question
->DuplicateOf
)
12039 question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
12041 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12043 if (!m
->NewLocalOnlyQuestions
)
12044 m
->NewLocalOnlyQuestions
= question
;
12048 if (!m
->NewQuestions
)
12049 m
->NewQuestions
= question
;
12051 // If the question's id is non-zero, then it's Wide Area
12052 // MUST NOT do this Wide Area setup until near the end of
12053 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12054 // NS, etc.) and if we haven't finished setting up our own question and setting
12055 // m->NewQuestions if necessary then we could end up recursively re-entering
12056 // this routine with the question list data structures in an inconsistent state.
12057 if (!mDNSOpaque16IsZero(question
->TargetQID
))
12059 FinalizeUnicastQuestion(m
, question
, purge
);
12063 #if BONJOUR_ON_DEMAND
12064 m
->NumAllInterfaceQuestions
++;
12065 LogInfo("mDNS_StartQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
12066 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, question
->qname
.c
, DNSTypeName(question
->qtype
));
12067 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12069 m
->NextBonjourDisableTime
= 0;
12070 if (m
->BonjourEnabled
== 0)
12072 // Enable Bonjour immediately by scheduling network changed processing where
12073 // we will join the multicast group on each active interface.
12074 m
->BonjourEnabled
= 1;
12075 m
->NetworkChanged
= m
->timenow
;
12078 #endif // BONJOUR_ON_DEMAND
12081 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question
->qname
.c
);
12082 mDNS_PurgeForQuestion(m
, question
);
12087 return(mStatus_NoError
);
12090 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12091 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
12093 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
12094 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12095 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12097 if (nta
->question
.ThisQInterval
!= -1)
12099 mDNS_StopQuery_internal(m
, &nta
->question
);
12100 if (nta
->question
.ThisQInterval
!= -1)
12101 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
12103 mDNSPlatformMemFree(nta
);
12106 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
12108 const mDNSu32 slot
= HashSlot(&question
->qname
);
12109 CacheGroup
*cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
12111 DNSQuestion
**qp
= &m
->Questions
;
12113 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12115 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12116 qp
= &m
->LocalOnlyQuestions
;
12117 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
12118 if (*qp
) *qp
= (*qp
)->next
;
12122 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
12124 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question
->qname
.c
, DNSTypeName(question
->qtype
));
12125 return(mStatus_BadReferenceErr
);
12128 #if BONJOUR_ON_DEMAND
12129 if (!LocalOnlyOrP2PInterface(question
->InterfaceID
) && mDNSOpaque16IsZero(question
->TargetQID
))
12131 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12132 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
12133 m
->NumAllInterfaceQuestions
--;
12134 LogInfo("mDNS_StopQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
12135 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, question
->qname
.c
, DNSTypeName(question
->qtype
));
12137 #endif // BONJOUR_ON_DEMAND
12139 #if TARGET_OS_EMBEDDED
12140 if (Question_uDNS(question
) && !question
->metrics
.answered
&& (question
->metrics
.querySendCount
> 0))
12142 const domainname
* queryName
;
12143 mDNSBool isForCell
;
12144 mDNSu32 durationMs
;
12146 queryName
= question
->metrics
.originalQName
? question
->metrics
.originalQName
: &question
->qname
;
12147 isForCell
= (question
->qDNSServer
&& question
->qDNSServer
->cellIntf
);
12149 if (question
->metrics
.querySendCount
> 0)
12151 durationMs
= ((m
->timenow
- question
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
12157 MetricsUpdateUDNSQueryStats(queryName
, question
->qtype
, mDNSNULL
, question
->metrics
.querySendCount
, durationMs
, isForCell
);
12160 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12161 UpdateQuestionDuplicates(m
, question
);
12162 // But don't trash ThisQInterval until afterwards.
12163 question
->ThisQInterval
= -1;
12165 // If there are any cache records referencing this as their active question, then see if there is any
12166 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12167 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
12169 if (rr
->CRActiveQuestion
== question
)
12172 DNSQuestion
*replacement
= mDNSNULL
;
12173 // If we find an active question that is answered by this cached record, use it as the cache record's
12174 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12175 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12176 // via CacheRecordRmv() when the cache record expires.
12177 for (q
= m
->Questions
; q
&& (q
!= m
->NewQuestions
); q
= q
->next
)
12179 if (!q
->DuplicateOf
&& !QuerySuppressed(q
) && ResourceRecordAnswersQuestion(&rr
->resrec
, q
))
12181 if (q
->ThisQInterval
> 0)
12186 else if (!replacement
)
12193 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12194 "CurrentAnswers %d, SuppressQuery %d", replacement
, CRDisplayString(m
,rr
), question
->CurrentAnswers
, replacement
->CurrentAnswers
, replacement
->SuppressQuery
);
12195 rr
->CRActiveQuestion
= replacement
; // Question used to be active; new value may or may not be null
12196 if (!replacement
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
12200 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12201 // bump its pointer forward one question.
12202 if (m
->CurrentQuestion
== question
)
12204 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12205 question
->qname
.c
, DNSTypeName(question
->qtype
));
12206 m
->CurrentQuestion
= question
->next
;
12209 if (m
->NewQuestions
== question
)
12211 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12212 question
->qname
.c
, DNSTypeName(question
->qtype
));
12213 m
->NewQuestions
= question
->next
;
12216 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
12218 if (m
->RestartQuestion
== question
)
12220 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12221 question
->qname
.c
, DNSTypeName(question
->qtype
));
12222 m
->RestartQuestion
= question
->next
;
12225 if (m
->ValidationQuestion
== question
)
12227 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
12228 question
->qname
.c
, DNSTypeName(question
->qtype
));
12229 m
->ValidationQuestion
= question
->next
;
12232 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12233 question
->next
= mDNSNULL
;
12235 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12237 // And finally, cancel any associated GetZoneData operation that's still running.
12238 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12239 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12240 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12241 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12242 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
12243 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
12244 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
12246 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12248 for (q
= m
->Questions
; q
; q
=q
->next
)
12249 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
12252 if (!m
->LLQNAT
.clientCallback
) // Should never happen, but just in case...
12254 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12258 LogInfo("Stopping LLQNAT");
12259 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
12260 m
->LLQNAT
.clientCallback
= mDNSNULL
; // Means LLQ NAT Traversal not running
12264 // If necessary, tell server it can delete this LLQ state
12265 if (question
->state
== LLQ_Established
)
12267 question
->ReqLease
= 0;
12268 sendLLQRefresh(m
, question
);
12269 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12270 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12271 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12272 // we let that run out its natural course and complete asynchronously.
12275 question
->tcp
->question
= mDNSNULL
;
12276 question
->tcp
= mDNSNULL
;
12279 else if (question
->dnsPushState
== DNSPUSH_ESTABLISHED
)
12283 UnSubscribeToDNSPushNotificationServer(m
, q
);
12284 question
->tcp
->question
= mDNSNULL
;
12285 question
->tcp
= mDNSNULL
;
12288 #if APPLE_OSX_mDNSResponder
12289 UpdateAutoTunnelDomainStatuses(m
);
12292 // wait until we send the refresh above which needs the nta
12293 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
12295 if (question
->ValidationRequired
&& question
->DNSSECAuthInfo
)
12297 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question
->qname
.c
);
12298 question
->DAIFreeCallback(m
, question
->DNSSECAuthInfo
);
12299 question
->DNSSECAuthInfo
= mDNSNULL
;
12301 if (question
->AnonInfo
)
12303 FreeAnonInfo(question
->AnonInfo
);
12304 question
->AnonInfo
= mDNSNULL
;
12306 #if TARGET_OS_EMBEDDED
12307 if (question
->metrics
.originalQName
)
12309 mDNSPlatformMemFree(question
->metrics
.originalQName
);
12310 question
->metrics
.originalQName
= mDNSNULL
;
12314 return(mStatus_NoError
);
12317 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
12321 status
= mDNS_StartQuery_internal(m
, question
);
12326 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
12330 status
= mDNS_StopQuery_internal(m
, question
);
12335 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12336 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12337 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12338 // specifically to catch and report if the client callback does try to make API calls
12339 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
12345 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12346 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
12348 status
= mDNS_StopQuery_internal(m
, question
);
12349 if (status
== mStatus_NoError
&& !qq
)
12351 const CacheRecord
*rr
;
12352 const mDNSu32 slot
= HashSlot(&question
->qname
);
12353 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, question
->qnamehash
, &question
->qname
);
12354 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12355 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
12356 if (rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameRecordAnswersQuestion(&rr
->resrec
, question
))
12358 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12359 if (question
->QuestionCallback
)
12360 question
->QuestionCallback(m
, question
, &rr
->resrec
, mDNSfalse
);
12367 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
12371 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12372 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
12377 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
12379 mStatus status
= mStatus_BadReferenceErr
;
12382 cr
= FindIdenticalRecordInCache(m
, rr
);
12383 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
12384 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12385 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, 0);
12390 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
12391 const domainname
*const srv
, const domainname
*const domain
,
12392 const mDNSu8
*anondata
, const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12393 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12394 mDNSQuestionCallback
*Callback
, void *Context
)
12396 question
->InterfaceID
= InterfaceID
;
12397 question
->flags
= flags
;
12398 question
->Target
= zeroAddr
;
12399 question
->qtype
= kDNSType_PTR
;
12400 question
->qclass
= kDNSClass_IN
;
12401 question
->LongLived
= mDNStrue
;
12402 question
->ExpectUnique
= mDNSfalse
;
12403 question
->ForceMCast
= ForceMCast
;
12404 question
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
12405 question
->SuppressUnusable
= mDNSfalse
;
12406 question
->SearchListIndex
= 0;
12407 question
->AppendSearchDomains
= 0;
12408 question
->RetryWithSearchDomains
= mDNSfalse
;
12409 question
->TimeoutQuestion
= 0;
12410 question
->WakeOnResolve
= 0;
12411 question
->UseBackgroundTrafficClass
= useBackgroundTrafficClass
;
12412 question
->ValidationRequired
= 0;
12413 question
->ValidatingResponse
= 0;
12414 question
->ProxyQuestion
= 0;
12415 question
->qnameOrig
= mDNSNULL
;
12416 question
->AnonInfo
= mDNSNULL
;
12417 question
->QuestionCallback
= Callback
;
12418 question
->QuestionContext
= Context
;
12420 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
))
12421 return(mStatus_BadParamErr
);
12425 question
->AnonInfo
= AllocateAnonInfo(&question
->qname
, anondata
, mDNSPlatformStrLen(anondata
), mDNSNULL
);
12426 if (!question
->AnonInfo
)
12427 return(mStatus_BadParamErr
);
12430 return(mDNS_StartQuery_internal(m
, question
));
12433 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
12434 const domainname
*const srv
, const domainname
*const domain
,
12435 const mDNSu8
*anondata
, const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12436 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12437 mDNSQuestionCallback
*Callback
, void *Context
)
12441 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, anondata
, InterfaceID
, flags
, ForceMCast
, useBackgroundTrafficClass
, Callback
, Context
);
12447 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
12448 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
12450 question
->InterfaceID
= InterfaceID
;
12451 question
->flags
= 0;
12452 question
->Target
= zeroAddr
;
12453 question
->qtype
= kDNSType_PTR
;
12454 question
->qclass
= kDNSClass_IN
;
12455 question
->LongLived
= mDNSfalse
;
12456 question
->ExpectUnique
= mDNSfalse
;
12457 question
->ForceMCast
= mDNSfalse
;
12458 question
->ReturnIntermed
= mDNSfalse
;
12459 question
->SuppressUnusable
= mDNSfalse
;
12460 question
->SearchListIndex
= 0;
12461 question
->AppendSearchDomains
= 0;
12462 question
->RetryWithSearchDomains
= mDNSfalse
;
12463 question
->TimeoutQuestion
= 0;
12464 question
->WakeOnResolve
= 0;
12465 question
->UseBackgroundTrafficClass
= mDNSfalse
;
12466 question
->ValidationRequired
= 0;
12467 question
->ValidatingResponse
= 0;
12468 question
->ProxyQuestion
= 0;
12469 question
->qnameOrig
= mDNSNULL
;
12470 question
->AnonInfo
= mDNSNULL
;
12471 question
->pid
= mDNSPlatformGetPID();
12472 question
->euid
= 0;
12473 question
->QuestionCallback
= Callback
;
12474 question
->QuestionContext
= Context
;
12475 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
12476 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
12477 if (!dom
) dom
= &localdomain
;
12478 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
12479 return(mDNS_StartQuery(m
, question
));
12482 // ***************************************************************************
12483 #if COMPILER_LIKES_PRAGMA_MARK
12485 #pragma mark - Responder Functions
12488 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
12492 status
= mDNS_Register_internal(m
, rr
);
12497 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
12498 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
12500 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
12502 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
12503 return(mStatus_Invalid
);
12508 // If TTL is unspecified, leave TTL unchanged
12509 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
12511 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12514 RData
*n
= rr
->NewRData
;
12515 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
12516 if (rr
->UpdateCallback
)
12517 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
12520 rr
->NewRData
= newrdata
;
12521 rr
->newrdlength
= newrdlength
;
12522 rr
->UpdateCallback
= Callback
;
12524 #ifndef UNICAST_DISABLED
12525 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
&& !IsLocalDomain(rr
->resrec
.name
))
12527 mStatus status
= uDNS_UpdateRecord(m
, rr
);
12528 // The caller frees the memory on error, don't retain stale pointers
12529 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
12535 if (RRLocalOnly(rr
) || (rr
->resrec
.rroriginalttl
== newttl
&&
12536 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
)))
12537 CompleteRDataUpdate(m
, rr
);
12540 rr
->AnnounceCount
= InitialAnnounceCount
;
12541 InitializeLastAPTime(m
, rr
);
12542 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
12543 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
12544 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
12545 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
12546 if (rr
->UpdateCredits
<= 5)
12548 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12549 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
12550 rr
->ThisAPInterval
*= 4;
12551 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
12552 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12553 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
12555 rr
->resrec
.rroriginalttl
= newttl
;
12559 return(mStatus_NoError
);
12562 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12563 // the record list and/or question list.
12564 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12565 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
12569 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
12574 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12575 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
12577 mDNSlocal NetworkInterfaceInfo
*FindFirstAdvertisedInterface(mDNS
*const m
)
12579 NetworkInterfaceInfo
*intf
;
12580 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12581 if (intf
->Advertise
) break;
12585 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12587 char buffer
[MAX_REVERSE_MAPPING_NAME
];
12588 NetworkInterfaceInfo
*primary
;
12591 if (m
->AutoTargetServices
== 0)
12593 LogInfo("AdvertiseInterface: Returning due to AutoTargetServices zero for %s", set
->ifname
);
12597 primary
= FindFirstAdvertisedInterface(m
);
12598 if (!primary
) primary
= set
; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
12600 // If interface is marked as a direct link, we can assume the address record is unique
12601 // and does not need to go through the probe phase of the probe/announce packet sequence.
12602 recordType
= (set
->DirectLink
? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
);
12604 if (set
->DirectLink
)
12605 LogInfo("AdvertiseInterface: Marking address record as kDNSRecordTypeKnownUnique for %s", set
->ifname
);
12607 // Send dynamic update for non-linklocal IPv4 Addresses
12608 mDNS_SetupResourceRecord(&set
->RR_A
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, recordType
, AuthRecordAny
, mDNS_HostNameCallback
, set
);
12609 mDNS_SetupResourceRecord(&set
->RR_PTR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
12610 mDNS_SetupResourceRecord(&set
->RR_HINFO
, mDNSNULL
, set
->InterfaceID
, kDNSType_HINFO
, kHostNameTTL
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
12612 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12613 set
->RR_A
.AllowRemoteQuery
= mDNStrue
;
12614 set
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
12615 set
->RR_HINFO
.AllowRemoteQuery
= mDNStrue
;
12617 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12618 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12619 AssignDomainName(&set
->RR_A
.namestorage
, &m
->MulticastHostname
);
12620 if (set
->ip
.type
== mDNSAddrType_IPv4
)
12622 set
->RR_A
.resrec
.rrtype
= kDNSType_A
;
12623 set
->RR_A
.resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
12624 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12625 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
12626 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
12628 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
12631 set
->RR_A
.resrec
.rrtype
= kDNSType_AAAA
;
12632 set
->RR_A
.resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
12633 for (i
= 0; i
< 16; i
++)
12635 static const char hexValues
[] = "0123456789ABCDEF";
12636 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
12637 buffer
[i
* 4 + 1] = '.';
12638 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
12639 buffer
[i
* 4 + 3] = '.';
12641 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
12644 MakeDomainNameFromDNSNameString(&set
->RR_PTR
.namestorage
, buffer
);
12645 set
->RR_PTR
.AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12646 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
12648 set
->RR_A
.RRSet
= &primary
->RR_A
; // May refer to self
12650 mDNS_Register_internal(m
, &set
->RR_A
);
12651 mDNS_Register_internal(m
, &set
->RR_PTR
);
12653 #if APPLE_OSX_mDNSResponder
12654 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12655 D2D_start_advertising_interface(set
);
12656 #endif // APPLE_OSX_mDNSResponder
12658 if (!NO_HINFO
&& m
->HIHardware
.c
[0] > 0 && m
->HISoftware
.c
[0] > 0 && m
->HIHardware
.c
[0] + m
->HISoftware
.c
[0] <= 254)
12660 mDNSu8
*p
= set
->RR_HINFO
.resrec
.rdata
->u
.data
;
12661 AssignDomainName(&set
->RR_HINFO
.namestorage
, &m
->MulticastHostname
);
12662 set
->RR_HINFO
.DependentOn
= &set
->RR_A
;
12663 mDNSPlatformMemCopy(p
, &m
->HIHardware
, 1 + (mDNSu32
)m
->HIHardware
.c
[0]);
12664 p
+= 1 + (int)p
[0];
12665 mDNSPlatformMemCopy(p
, &m
->HISoftware
, 1 + (mDNSu32
)m
->HISoftware
.c
[0]);
12666 mDNS_Register_internal(m
, &set
->RR_HINFO
);
12670 debugf("Not creating HINFO record: platform support layer provided no information");
12671 set
->RR_HINFO
.resrec
.RecordType
= kDNSRecordTypeUnregistered
;
12675 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12677 if (m
->AutoTargetServices
== 0)
12679 LogInfo("DeadvertiseInterface: Returning due to AutoTargetServices zero for %s", set
->ifname
);
12683 #if APPLE_OSX_mDNSResponder
12684 D2D_stop_advertising_interface(set
);
12685 #endif // APPLE_OSX_mDNSResponder
12687 // Unregister these records.
12688 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12689 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12690 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12691 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12692 if (set
->RR_A
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
12693 if (set
->RR_PTR
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
12694 if (set
->RR_HINFO
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_HINFO
, mDNS_Dereg_normal
);
12697 mDNSlocal
void AdvertiseAllInterfaceRecords(mDNS
*const m
)
12699 NetworkInterfaceInfo
*intf
;
12700 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12702 if (intf
->Advertise
)
12704 LogInfo("AdvertiseInterface: Advertising for ifname %s", intf
->ifname
);
12705 AdvertiseInterface(m
, intf
);
12710 mDNSlocal
void DeadvertiseAllInterfaceRecords(mDNS
*const m
)
12712 NetworkInterfaceInfo
*intf
;
12713 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12715 if (intf
->Advertise
)
12717 LogInfo("DeadvertiseInterface: Deadvertising for ifname %s", intf
->ifname
);
12718 DeadvertiseInterface(m
, intf
);
12723 // Change target host name for record.
12724 mDNSlocal
void UpdateTargetHostName(mDNS
*const m
, AuthRecord
*const rr
)
12726 #if APPLE_OSX_mDNSResponder
12727 // If this record was also registered with any D2D plugins, stop advertising
12728 // the version with the old host name.
12729 D2D_stop_advertising_record(rr
);
12732 SetTargetToHostName(m
, rr
);
12734 #if APPLE_OSX_mDNSResponder
12735 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12736 D2D_start_advertising_record(rr
);
12740 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
12742 domainname newmname
;
12746 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12747 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12751 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
12754 AssignDomainName(&m
->MulticastHostname
, &newmname
);
12755 DeadvertiseAllInterfaceRecords(m
);
12756 AdvertiseAllInterfaceRecords(m
);
12759 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12760 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12761 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12766 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
12768 (void)rr
; // Unused parameter
12772 char *msg
= "Unknown result";
12773 if (result
== mStatus_NoError
) msg
= "Name registered";
12774 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
12775 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
12779 if (result
== mStatus_NoError
)
12781 // Notify the client that the host name is successfully registered
12782 if (m
->MainCallback
)
12783 m
->MainCallback(m
, mStatus_NoError
);
12785 else if (result
== mStatus_NameConflict
)
12787 domainlabel oldlabel
= m
->hostlabel
;
12789 // 1. First give the client callback a chance to pick a new name
12790 if (m
->MainCallback
)
12791 m
->MainCallback(m
, mStatus_NameConflict
);
12793 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12794 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12795 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12796 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
12797 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
12799 // 3. Generate the FQDNs from the hostlabel,
12800 // and make sure all SRV records, etc., are updated to reference our new hostname
12802 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
12804 else if (result
== mStatus_MemFree
)
12806 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12807 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12808 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12811 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
12814 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
12816 NetworkInterfaceInfo
*intf
;
12817 active
->IPv4Available
= mDNSfalse
;
12818 active
->IPv6Available
= mDNSfalse
;
12819 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12820 if (intf
->InterfaceID
== active
->InterfaceID
)
12822 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
12823 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
12827 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
12830 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12831 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
12832 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
12834 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
12835 // Zero out the updateid so that if we have a pending response from the server, it won't
12836 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12837 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
12838 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
12842 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12845 // We initialize ThisQInterval to -1 indicating that the question has not been started
12846 // yet. If the question (browse) is started later during interface registration, it will
12847 // be stopped during interface deregistration. We can't sanity check to see if the
12848 // question has been stopped or not before initializing it to -1 because we need to
12849 // initialize it to -1 the very first time.
12851 set
->NetWakeBrowse
.ThisQInterval
= -1;
12852 for (i
=0; i
<3; i
++)
12854 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
12855 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
12857 set
->NextSPSAttempt
= -1;
12858 set
->NextSPSAttemptTime
= m
->timenow
;
12861 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12863 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12864 while (p
&& p
!= set
) p
=p
->next
;
12865 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12867 if (set
->InterfaceActive
)
12869 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12870 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, mDNSNULL
, set
->InterfaceID
, 0, mDNSfalse
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
12874 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12876 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12877 while (p
&& p
!= set
) p
=p
->next
;
12878 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12880 // Note: We start the browse only if the interface is NetWake capable and we use this to
12881 // stop the resolves also. Hence, the resolves should not be started without the browse
12882 // being started i.e, resolves should not happen unless NetWake capable which is
12883 // guaranteed by BeginSleepProcessing.
12884 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
12887 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12889 // Stop our browse and resolve operations
12890 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
12891 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
12893 // Make special call to the browse callback to let it know it can to remove all records for this interface
12894 if (m
->SPSBrowseCallback
)
12896 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12897 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
12898 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12901 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12902 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12903 InitializeNetWakeState(m
, set
);
12907 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
12910 mDNSBool FirstOfType
= mDNStrue
;
12911 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
12913 if (!set
->InterfaceID
)
12914 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set
->ip
); return(mStatus_Invalid
); }
12916 if (!mDNSAddressIsValidNonZero(&set
->mask
))
12917 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set
->ip
, &set
->mask
); return(mStatus_Invalid
); }
12921 // Assume this interface will be active now, unless we find a duplicate already in the list
12922 set
->InterfaceActive
= mDNStrue
;
12923 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
12924 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
12926 InitializeNetWakeState(m
, set
);
12928 // Scan list to see if this InterfaceID is already represented
12933 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
12935 return(mStatus_AlreadyRegistered
);
12938 if ((*p
)->InterfaceID
== set
->InterfaceID
)
12940 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
12941 set
->InterfaceActive
= mDNSfalse
;
12942 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
12943 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
12944 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
12950 set
->next
= mDNSNULL
;
12953 if (set
->Advertise
)
12954 AdvertiseInterface(m
, set
);
12956 LogInfo("mDNS_RegisterInterface: InterfaceID %d %s (%#a) %s",
12957 (uint32_t)set
->InterfaceID
, set
->ifname
, &set
->ip
,
12958 set
->InterfaceActive
?
12959 "not represented in list; marking active and retriggering queries" :
12960 "already represented in list; marking inactive for now");
12962 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
12964 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
12965 // giving the false impression that there's an active representative of this interface when there really isn't.
12966 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
12967 // even if we believe that we previously had an active representative of this interface.
12968 if (set
->McastTxRx
&& (FirstOfType
|| set
->InterfaceActive
))
12971 // Normally, after an interface comes up, we pause half a second before beginning probing.
12972 // This is to guard against cases where there's rapid interface changes, where we could be confused by
12973 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
12974 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
12975 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
12976 // and think it's a conflicting answer to our probe.
12977 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
12978 const mDNSs32 probedelay
= flapping
? mDNSPlatformOneSecond
* 5 : mDNSPlatformOneSecond
/ 2;
12979 const mDNSu8 numannounce
= flapping
? (mDNSu8
)1 : InitialAnnounceCount
;
12981 // Use a small amount of randomness:
12982 // In the case of a network administrator turning on an Ethernet hub so that all the
12983 // connected machines establish link at exactly the same time, we don't want them all
12984 // to go and hit the network with identical queries at exactly the same moment.
12985 // We set a random delay of up to InitialQuestionInterval (1/3 second).
12986 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
12987 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
12988 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
12989 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
12990 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
12991 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
12995 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
12996 m
->mDNSStats
.InterfaceUpFlap
++;
12999 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set
->ifname
, &set
->ip
, probedelay
);
13001 if (m
->SuppressProbes
== 0 ||
13002 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
13003 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
13005 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13006 // it here also handles the wake up case as the network link comes UP after waking causing
13007 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13008 // that the network link comes UP after 60 seconds and we never set the OWNER option
13009 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
13010 LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
13012 m
->mDNSStats
.InterfaceUp
++;
13013 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
13015 if (mDNSOpaque16IsZero(q
->TargetQID
))
13017 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
13018 { // then reactivate this question
13019 // If flapping, delay between first and second queries is nine seconds instead of one second
13020 mDNSBool dodelay
= flapping
&& (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
13021 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
13022 mDNSs32 qdelay
= dodelay
? mDNSPlatformOneSecond
* 5 : 0;
13023 if (dodelay
) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q
->qname
.c
, DNSTypeName(q
->qtype
));
13025 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
13027 q
->ThisQInterval
= initial
;
13028 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
13030 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
13031 q
->RecentAnswerPkts
= 0;
13033 ReInitAnonInfo(&q
->AnonInfo
, &q
->qname
);
13034 SetNextQueryTime(m
,q
);
13039 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13040 // we now need them to re-probe if necessary, and then re-announce.
13041 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13043 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13046 ReInitAnonInfo(&rr
->resrec
.AnonInfo
, rr
->resrec
.name
);
13047 mDNSCoreRestartRegistration(m
, rr
, numannounce
);
13050 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
13055 RestartRecordGetZoneData(m
);
13057 mDNS_UpdateAllowSleep(m
);
13060 return(mStatus_NoError
);
13063 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13064 // the record list and/or question list.
13065 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13066 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
)
13068 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
13069 mDNSBool revalidate
= mDNSfalse
;
13070 NetworkInterfaceInfo
*primary
;
13071 NetworkInterfaceInfo
*intf
;
13076 // Find this record in our list
13077 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
13078 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
13080 mDNS_DeactivateNetWake_internal(m
, set
);
13082 // Unlink this record from our list
13084 set
->next
= mDNSNULL
;
13086 if (!set
->InterfaceActive
)
13088 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13089 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13090 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
13091 UpdateInterfaceProtocols(m
, intf
);
13095 intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
13098 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13099 " making it active", (uint32_t)set
->InterfaceID
, set
->ifname
, &set
->ip
);
13100 if (intf
->InterfaceActive
)
13101 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set
->ifname
, &set
->ip
);
13102 intf
->InterfaceActive
= mDNStrue
;
13103 UpdateInterfaceProtocols(m
, intf
);
13105 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
13107 // See if another representative *of the same type* exists. If not, we mave have gone from
13108 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13109 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13110 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
13112 if (!intf
) revalidate
= mDNStrue
;
13121 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13122 " marking questions etc. dormant", (uint32_t)set
->InterfaceID
, set
->ifname
, &set
->ip
);
13124 m
->mDNSStats
.InterfaceDown
++;
13126 if (set
->McastTxRx
&& flapping
)
13128 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
13129 m
->mDNSStats
.InterfaceDownFlap
++;
13132 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13133 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13134 for (q
= m
->Questions
; q
; q
=q
->next
)
13136 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
13137 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
13139 q
->FlappingInterface2
= q
->FlappingInterface1
;
13140 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
13144 // 2. Flush any cache records received on this interface
13145 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
13146 FORALL_CACHERECORDS(slot
, cg
, rr
)
13148 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13150 // If this interface is deemed flapping,
13151 // postpone deleting the cache records in case the interface comes back again
13152 if (set
->McastTxRx
&& flapping
)
13154 // For a flapping interface we want these record to go away after 30 seconds
13155 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13156 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13157 // if the interface does come back, any relevant questions will be reactivated anyway
13158 rr
->UnansweredQueries
= MaxUnansweredQueries
;
13162 mDNS_PurgeCacheResourceRecord(m
, rr
);
13169 // If we still have address records referring to this one, update them.
13170 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13171 // so the call to FindFirstAdvertisedInterface() won’t accidentally find it.
13172 primary
= FindFirstAdvertisedInterface(m
);
13173 A
= primary
? &primary
->RR_A
: mDNSNULL
;
13174 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13175 if (intf
->RR_A
.RRSet
== &set
->RR_A
)
13176 intf
->RR_A
.RRSet
= A
;
13178 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13179 if (set
->Advertise
) DeadvertiseInterface(m
, set
);
13181 // If we have any cache records received on this interface that went away, then re-verify them.
13182 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13183 // giving the false impression that there's an active representative of this interface when there really isn't.
13184 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13185 if (revalidate
&& !m
->ShutdownTime
)
13190 FORALL_CACHERECORDS(slot
, cg
, rr
)
13191 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13192 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13195 mDNS_UpdateAllowSleep(m
);
13200 mDNSlocal
void SetAnonInfoSRS(ServiceRecordSet
*sr
, int NumSubTypes
)
13207 len
= mDNSPlatformStrLen(sr
->AnonData
);
13208 if (sr
->RR_PTR
.resrec
.AnonInfo
)
13210 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for PTR record %##s, should have been freed already", sr
->RR_PTR
.resrec
.name
->c
);
13211 FreeAnonInfo(sr
->RR_PTR
.resrec
.AnonInfo
);
13213 sr
->RR_PTR
.resrec
.AnonInfo
= AllocateAnonInfo(sr
->RR_PTR
.resrec
.name
, sr
->AnonData
, len
, mDNSNULL
);
13214 for (i
=0; i
<NumSubTypes
; i
++)
13216 if (sr
->SubTypes
[i
].resrec
.AnonInfo
)
13218 LogMsg("SetAnonInfoSRS: Freeing AnonInfo for subtype record %##s, should have been freed already", sr
->SubTypes
[i
].resrec
.name
->c
);
13219 FreeAnonInfo(sr
->SubTypes
[i
].resrec
.AnonInfo
);
13221 sr
->SubTypes
[i
].resrec
.AnonInfo
= AllocateAnonInfo(sr
->SubTypes
[i
].resrec
.name
, sr
->AnonData
, len
, mDNSNULL
);
13225 mDNSlocal
void ResetAnonInfoSRS(ServiceRecordSet
*sr
, int NumSubTypes
)
13231 if (sr
->RR_PTR
.resrec
.AnonInfo
)
13233 FreeAnonInfo(sr
->RR_PTR
.resrec
.AnonInfo
);
13234 sr
->RR_PTR
.resrec
.AnonInfo
= mDNSNULL
;
13236 for (i
=0; i
<NumSubTypes
; i
++)
13238 if (sr
->SubTypes
[i
].resrec
.AnonInfo
)
13240 FreeAnonInfo(sr
->SubTypes
[i
].resrec
.AnonInfo
);
13241 sr
->SubTypes
[i
].resrec
.AnonInfo
= mDNSNULL
;
13246 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13248 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13249 (void)m
; // Unused parameter
13253 char *msg
= "Unknown result";
13254 if (result
== mStatus_NoError
) msg
= "Name Registered";
13255 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
13256 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
13257 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
13261 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13262 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
13264 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13265 if (result
== mStatus_NameConflict
)
13267 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
13268 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
13272 if (result
== mStatus_MemFree
)
13274 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13275 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13276 // every record is finished cleaning up.
13278 ExtraResourceRecord
*e
= sr
->Extras
;
13280 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13281 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13282 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13283 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13284 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13288 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13291 ResetAnonInfoSRS(sr
, sr
->NumSubTypes
);
13293 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13294 // then we can now report the NameConflict to the client
13295 if (sr
->Conflict
) result
= mStatus_NameConflict
;
13299 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered" : "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
13300 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13301 // function is allowed to do anything, including deregistering this service and freeing its memory.
13302 if (sr
->ServiceCallback
)
13303 sr
->ServiceCallback(m
, sr
, result
);
13306 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13308 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13309 if (sr
->ServiceCallback
)
13310 sr
->ServiceCallback(m
, sr
, result
);
13314 // Derive AuthRecType from the coreFlag* values.
13315 // Note, this is not using the external flags values, kDNSServiceFlags*, defined in dns_sd.h.
13316 // It should be changed to do so once the use of coreFlag* is completely replaced with
13317 // the use the kDNSServiceFlags* definitions within mDNSResponder.
13318 mDNSlocal AuthRecType
setAuthRecType(mDNSInterfaceID InterfaceID
, mDNSu32 flags
)
13320 AuthRecType artype
;
13322 if (InterfaceID
== mDNSInterface_LocalOnly
)
13323 artype
= AuthRecordLocalOnly
;
13324 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13325 artype
= AuthRecordP2P
;
13326 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& coreFlagIncludeP2P
)
13327 && (flags
& coreFlagIncludeAWDL
))
13328 artype
= AuthRecordAnyIncludeAWDLandP2P
;
13329 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& coreFlagIncludeP2P
))
13330 artype
= AuthRecordAnyIncludeP2P
;
13331 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& coreFlagIncludeAWDL
))
13332 artype
= AuthRecordAnyIncludeAWDL
;
13334 artype
= AuthRecordAny
;
13339 // Used to derive the original D2D specific flags specified by the client in the registration
13340 // when we don't have access to the original flag (kDNSServiceFlags*) values.
13341 mDNSexport mDNSu32
deriveD2DFlagsFromAuthRecType(AuthRecType authRecType
)
13344 if ((authRecType
== AuthRecordAnyIncludeP2P
) || (authRecType
== AuthRecordAnyIncludeAWDLandP2P
))
13345 flags
|= kDNSServiceFlagsIncludeP2P
;
13346 else if ((authRecType
== AuthRecordAnyIncludeAWDL
) || (authRecType
== AuthRecordAnyIncludeAWDLandP2P
))
13347 flags
|= kDNSServiceFlagsIncludeAWDL
;
13352 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13353 // Type is service type (e.g. "_ipp._tcp.")
13354 // Domain is fully qualified domain name (i.e. ending with a null label)
13355 // We always register a TXT, even if it is empty (so that clients are not
13356 // left waiting forever looking for a nonexistent record.)
13357 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13358 // then the default host name (m->MulticastHostname) is automatically used
13359 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13360 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
13361 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13362 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
13363 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
13364 mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
, mDNSu32 flags
)
13369 AuthRecType artype
;
13370 mDNSu8 recordType
= (flags
& coreFlagKnownUnique
) ? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
13372 sr
->ServiceCallback
= Callback
;
13373 sr
->ServiceContext
= Context
;
13374 sr
->Conflict
= mDNSfalse
;
13376 sr
->Extras
= mDNSNULL
;
13377 sr
->NumSubTypes
= NumSubTypes
;
13378 sr
->SubTypes
= SubTypes
;
13381 artype
= setAuthRecType(InterfaceID
, flags
);
13383 // Initialize the AuthRecord objects to sane values
13384 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13385 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, artype
, ServiceCallback
, sr
);
13386 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13388 if (flags
& coreFlagWakeOnly
)
13390 sr
->RR_PTR
.AuthFlags
= AuthFlagsWakeOnly
;
13393 if (SameDomainName(type
, (const domainname
*) "\x4" "_ubd" "\x4" "_tcp"))
13394 hostTTL
= kHostNameSmallTTL
;
13396 hostTTL
= kHostNameTTL
;
13398 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, hostTTL
, recordType
, artype
, ServiceCallback
, sr
);
13399 mDNS_SetupResourceRecord(&sr
->RR_TXT
, mDNSNULL
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
13401 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13402 if (mDNSIPPortIsZero(port
))
13403 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, InterfaceID
, NSSCallback
, sr
, flags
));
13405 // If the caller is registering an oversized TXT record,
13406 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13407 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
13408 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
13410 // Set up the record names
13411 // For now we only create an advisory record for the main type, not for subtypes
13412 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13413 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
13414 return(mStatus_BadParamErr
);
13415 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13416 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13417 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13419 // 1. Set up the ADV record rdata to advertise our service type
13420 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
13422 // 2. Set up the PTR record rdata to point to our service name
13423 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13424 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13425 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
13426 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
13427 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
13429 // 2a. Set up any subtype PTRs to point to our service name
13430 // If the client is using subtypes, it is the client's responsibility to have
13431 // already set the first label of the record name to the subtype being registered
13432 for (i
=0; i
<NumSubTypes
; i
++)
13435 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
13436 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13437 AppendDomainName(&st
, type
);
13438 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13439 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13440 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
13441 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
13442 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
13445 SetAnonInfoSRS(sr
, NumSubTypes
);
13447 // 3. Set up the SRV record rdata.
13448 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
13449 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
13450 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
13452 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13453 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
13454 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
13456 // 4. Set up the TXT record rdata,
13457 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13458 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13459 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
13460 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
13462 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
13463 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
13464 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
13466 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
13469 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13470 // that if the SRV cannot find a target, rest of the records that belong to this service
13471 // will not be activated.
13472 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
13473 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13474 // any list and hence no need to deregister. We could probably do similar checks for other
13475 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13481 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
13482 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13483 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13484 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13485 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13486 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13487 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
13488 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
13489 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
13493 if (err
) mDNS_DeregisterService(m
, sr
);
13497 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
13498 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
, mDNSu32 flags
)
13500 ExtraResourceRecord
**e
;
13502 AuthRecType artype
;
13503 mDNSInterfaceID InterfaceID
= sr
->RR_PTR
.resrec
.InterfaceID
;
13504 ResourceRecord
*rr
;
13506 artype
= setAuthRecType(InterfaceID
, flags
);
13508 extra
->next
= mDNSNULL
;
13509 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
13510 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
13511 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13515 if (extra
->r
.resrec
.rrtype
== kDNSType_TXT
)
13517 if (sr
->RR_TXT
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_TXT
.resrec
;
13519 else if (extra
->r
.resrec
.rrtype
== kDNSType_SRV
)
13521 if (sr
->RR_SRV
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_SRV
.resrec
;
13526 ExtraResourceRecord
*srExtra
;
13528 for (srExtra
= sr
->Extras
; srExtra
; srExtra
= srExtra
->next
)
13530 if ((srExtra
->r
.resrec
.rrtype
== extra
->r
.resrec
.rrtype
) && (srExtra
->r
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
13532 rr
= &srExtra
->r
.resrec
;
13538 if (rr
&& (extra
->r
.resrec
.rroriginalttl
!= rr
->rroriginalttl
))
13540 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13541 extra
->r
.resrec
.rroriginalttl
, rr
->rroriginalttl
, RRDisplayString(m
, &extra
->r
.resrec
));
13542 extra
->r
.resrec
.rroriginalttl
= rr
->rroriginalttl
;
13546 while (*e
) e
= &(*e
)->next
;
13548 extra
->r
.DependentOn
= &sr
->RR_SRV
;
13550 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13551 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
13553 status
= mDNS_Register_internal(m
, &extra
->r
);
13554 if (status
== mStatus_NoError
) *e
= extra
;
13560 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
13561 mDNSRecordCallback MemFreeCallback
, void *Context
)
13563 ExtraResourceRecord
**e
;
13568 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
13571 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
13572 status
= mStatus_BadReferenceErr
;
13576 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
13577 extra
->r
.RecordCallback
= MemFreeCallback
;
13578 extra
->r
.RecordContext
= Context
;
13580 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
13586 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
13588 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13589 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13590 domainlabel name1
, name2
;
13591 domainname type
, domain
;
13592 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
13593 ExtraResourceRecord
*extras
= sr
->Extras
;
13596 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
13600 IncrementLabelSuffix(&name2
, mDNStrue
);
13604 if (SameDomainName(&domain
, &localdomain
))
13605 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
13606 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
13608 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
13609 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
, sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
13610 sr
->SubTypes
, sr
->NumSubTypes
,
13611 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
, sr
->flags
);
13613 // mDNS_RegisterService() just reset sr->Extras to NULL.
13614 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13615 // through the old list of extra records, and re-add them to our freshly created service registration
13616 while (!err
&& extras
)
13618 ExtraResourceRecord
*e
= extras
;
13619 extras
= extras
->next
;
13620 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
, 0);
13626 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13627 // which may change the record list and/or question list.
13628 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13629 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
13631 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13632 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
13634 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
13636 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
13637 return(mStatus_BadReferenceErr
);
13639 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
13641 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
13642 // Avoid race condition:
13643 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13644 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13645 // If the client happens to deregister the service in the middle of that process, then
13646 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13647 // instead of incorrectly promoting it to mStatus_NameConflict.
13648 // This race condition is exposed particularly when the conformance test generates
13649 // a whole batch of simultaneous conflicts across a range of services all advertised
13650 // using the same system default name, and if we don't take this precaution then
13651 // we end up incrementing m->nicelabel multiple times instead of just once.
13652 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13653 sr
->Conflict
= mDNSfalse
;
13654 return(mStatus_NoError
);
13660 ExtraResourceRecord
*e
;
13664 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13665 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13666 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
13667 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
13669 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
13671 // We deregister all of the extra records, but we leave the sr->Extras list intact
13672 // in case the client wants to do a RenameAndReregister and reinstate the registration
13675 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
13679 for (i
=0; i
<sr
->NumSubTypes
; i
++)
13680 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
13682 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
13688 // Create a registration that asserts that no such service exists with this name.
13689 // This can be useful where there is a given function is available through several protocols.
13690 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13691 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13692 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13693 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13694 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
13695 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13696 const domainname
*const host
,
13697 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
, mDNSu32 flags
)
13699 AuthRecType artype
;
13701 artype
= setAuthRecType(InterfaceID
, flags
);
13703 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, artype
, Callback
, Context
);
13704 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13705 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
13706 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
13707 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
13708 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
13709 else rr
->AutoTarget
= Target_AutoHost
;
13710 return(mDNS_Register(m
, rr
));
13713 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
13714 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
13716 AuthRecType artype
;
13718 if (InterfaceID
== mDNSInterface_LocalOnly
)
13719 artype
= AuthRecordLocalOnly
;
13720 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13721 artype
= AuthRecordP2P
;
13723 artype
= AuthRecordAny
;
13724 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, mDNSNULL
, mDNSNULL
);
13725 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
13726 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
13727 return(mDNS_Register(m
, rr
));
13730 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
13733 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
13737 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
13740 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
13744 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
13749 for (i
=0; i
<10; i
++)
13751 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
13752 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
13755 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
13760 // ***************************************************************************
13761 #if COMPILER_LIKES_PRAGMA_MARK
13763 #pragma mark - Sleep Proxy Server
13766 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
13768 // If we see an ARP from a machine we think is sleeping, then either
13769 // (i) the machine has woken, or
13770 // (ii) it's just a stray old packet from before the machine slept
13771 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13772 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13773 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13774 // 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*
13775 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13776 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13778 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
13779 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
13780 rr
->ProbeRestartCount
++;
13782 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13783 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13784 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13785 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13786 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13787 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13788 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
13789 InitializeLastAPTime(m
, rr
);
13792 rr
->AnnounceCount
= InitialAnnounceCount
;
13793 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
13794 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13795 SetNextAnnounceProbeTime(m
, rr
);
13799 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
13801 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
13803 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
13809 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13810 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13811 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13812 // The times we might need to react to an ARP Announcement are:
13813 // (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
13814 // (ii) if it's a conflicting Announcement from another host
13815 // -- and we check for these in Pass 2 below.
13816 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
13818 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13819 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13820 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
13822 static const char msg1
[] = "ARP Req from owner -- re-probing";
13823 static const char msg2
[] = "Ignoring ARP Request from ";
13824 static const char msg3
[] = "Creating Local ARP Cache entry ";
13825 static const char msg4
[] = "Answering ARP Request from ";
13826 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
13827 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
13828 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
13829 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13830 intf
->ifname
, msg
, &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13833 if ( rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
13834 RestartARPProbing(m
, rr
);
13836 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
13838 else if (msg
== msg3
)
13840 mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
13842 else if (msg
== msg4
)
13844 SendARP(m
, 2, rr
, &arp
->tpa
, &arp
->sha
, &arp
->spa
, &arp
->sha
);
13850 // 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.
13851 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13852 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13853 // 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.
13854 // If we see an apparently conflicting ARP, we check the sender hardware address:
13855 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13856 // 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.
13857 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
13858 debugf("ARP from self for %.4a", &arp
->tpa
);
13861 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
13862 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13863 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13864 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
13866 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
13868 LogSPS("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13869 &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13873 RestartARPProbing(m
, rr
);
13874 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
13876 LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
13877 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
13878 &arp
->sha
, &arp
->spa
, &arp
->tpa
, ARDisplayString(m
, rr
));
13882 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13883 &arp
->sha
, &arp
->spa
, &arp
->tpa
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13884 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
13894 // Option 1 is Source Link Layer Address Option
13895 // Option 2 is Target Link Layer Address Option
13896 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
13898 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
13899 while (options < end)
13901 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
13902 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
13903 options += options[1] * 8;
13909 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
13910 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
13913 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
13918 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
13919 if (ndp
->type
== NDP_Sol
)
13921 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
13923 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13924 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13925 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
13927 static const char msg1
[] = "NDP Req from owner -- re-probing";
13928 static const char msg2
[] = "Ignoring NDP Request from ";
13929 static const char msg3
[] = "Creating Local NDP Cache entry ";
13930 static const char msg4
[] = "Answering NDP Request from ";
13931 static const char msg5
[] = "Answering NDP Probe from ";
13932 const char *const msg
= sha
&& mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
13933 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
13934 sha
&& mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
13935 spa
&& mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
13936 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
13937 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13940 if (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
13941 RestartARPProbing(m
, rr
);
13943 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
13945 else if (msg
== msg3
)
13946 mDNSPlatformSetLocalAddressCacheEntry(m
, &rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
13947 else if (msg
== msg4
)
13948 SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
13949 else if (msg
== msg5
)
13950 SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
13954 // 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.
13955 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
13956 debugf("NDP from self for %.16a", &ndp
->target
);
13959 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
13960 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
13961 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
13962 // Hence it is the NDP target address we care about, not the actual packet source address.
13963 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
13964 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
13965 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13966 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13967 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
13969 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
13971 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13972 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13976 RestartARPProbing(m
, rr
);
13977 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
13979 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
13980 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
13984 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13985 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13986 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
13995 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
13996 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
13998 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
13999 mDNSBool wake
= mDNSfalse
;
14000 mDNSBool kaWake
= mDNSfalse
;
14004 #define XX wake ? "Received" : "Ignoring", end-p
14005 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
14011 #define TH_FIN 0x01
14012 #define TH_SYN 0x02
14013 #define TH_RST 0x04
14014 #define TH_ACK 0x10
14016 kr
= mDNS_MatchKeepaliveInfo(m
, dst
, src
, port
, t
->tcp
.src
, &seq
, &ack
);
14019 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
));
14021 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14022 // (b) packet that contains new data and acks a sequence number higher than the one
14023 // we have been sending in the keepalive
14025 wake
= ((t
->tcp
.flags
& TH_RST
) || (t
->tcp
.flags
& TH_FIN
)) ;
14029 mDNSu32 pseq
, pack
;
14030 mDNSBool data
= mDNSfalse
;
14033 // Convert to host order
14034 ptr
= (mDNSu8
*)&seq
;
14035 seq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14037 ptr
= (mDNSu8
*)&ack
;
14038 ack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14041 ptr
= (mDNSu8
*)&pseq
;
14042 pseq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14045 ptr
= (mDNSu8
*)&pack
;
14046 pack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14048 // If the other side is acking one more than our sequence number (keepalive is one
14049 // less than the last valid sequence sent) and it's sequence is more than what we
14051 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14052 tcphlen
= ((t
->tcp
.offset
>> 4) * 4);
14053 if (end
- ((mDNSu8
*)t
+ tcphlen
) > 0) data
= mDNStrue
;
14054 wake
= ((int)(pack
- seq
) > 0) && ((int)(pseq
- ack
) >= 0) && data
;
14056 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14057 if ((t
->tcp
.flags
& TH_ACK
) && (data
== mDNSfalse
) &&
14058 ((int)(ack
- pseq
) == 1))
14061 mDNS_SendKeepaliveACK(m
, kr
);
14063 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14064 end
, tcphlen
, end
- ((mDNSu8
*)t
+ tcphlen
), pack
, seq
, pseq
, ack
, wake
);
14066 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t
->tcp
.flags
); }
14072 // (a) RST is not set, AND
14073 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14074 wake
= (!(t
->tcp
.flags
& TH_RST
) && (t
->tcp
.flags
& (TH_FIN
|TH_SYN
)) != TH_FIN
);
14076 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14077 // except for ssh connections, where we'll wake for plain data packets too
14078 if (!mDNSSameIPPort(port
, SSHPort
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
14080 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
14081 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
14082 (t
->tcp
.flags
& 2) ? " SYN" : "",
14083 (t
->tcp
.flags
& 1) ? " FIN" : "",
14084 (t
->tcp
.flags
& 4) ? " RST" : "");
14090 #define ARD_AsNumber 3283
14091 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
14092 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
14093 if (udplen
>= sizeof(UDPHeader
))
14095 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
14098 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14099 if (mDNSSameIPPort(port
, IPSECPort
))
14101 // Specifically ignore NAT keepalive packets
14102 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
14105 // Skip over the Non-ESP Marker if present
14106 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
14107 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
14108 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
14109 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
14110 if ((ike
->Version
& 0x10) == 0x10)
14112 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14113 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14114 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
14115 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
14120 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14121 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14122 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14123 // UDP header (8 bytes)
14124 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14125 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
14127 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
14132 case 0x3A: if (&t
->bytes
[len
] <= end
)
14134 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
14135 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
14136 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
14140 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
14146 AuthRecord
*rr
, *r2
;
14149 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14150 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
14151 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14152 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
14154 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
14155 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
14156 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
14157 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14158 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
14159 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
14161 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14162 if (!r2
&& kaWake
) r2
= rr
; // So that we wake for keepalive packets, even without a matching SRV record
14165 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14166 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
14167 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14170 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14171 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
14177 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
14179 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14180 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14181 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14182 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14183 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14185 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14186 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14187 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14188 // since it points to a an address 14 bytes before pkt.
14189 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
14190 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
14192 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14194 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14195 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
14196 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
14197 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14198 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
14200 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
14201 const mDNSu8
* transEnd
= p
+ 14 + mDNSVal16(pkt
->v4
.totlen
);
14202 if (transEnd
> end
) transEnd
= end
;
14203 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
, &pkt
->v4
.dst
);
14204 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
14205 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
14206 if (transEnd
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
14207 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, transEnd
, InterfaceID
, 0);
14209 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14210 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
14212 const mDNSu8
*const trans
= p
+ 54;
14213 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
, &pkt
->v6
.dst
);
14214 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
14215 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
14216 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
14217 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
14218 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
14222 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
14224 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d.%d %#s",
14225 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
, &m
->nicelabel
);
14228 #ifndef SPC_DISABLED
14229 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
14231 if (result
== mStatus_NameConflict
)
14232 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
14233 else if (result
== mStatus_MemFree
)
14239 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
14243 ConstructSleepProxyServerName(m
, &name
);
14244 mDNS_RegisterService(m
, srs
,
14245 &name
, &SleepProxyServiceType
, &localdomain
,
14246 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
14247 (mDNSu8
*)"", 1, // TXT data, length
14248 mDNSNULL
, 0, // Subtypes (none)
14249 mDNSInterface_Any
, // Interface ID
14250 SleepProxyServerCallback
, mDNSNULL
, 0); // Callback, context, flags
14252 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
14258 // Called with lock held
14259 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
, mDNSu8 features
)
14261 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14262 mDNS_DropLockBeforeCallback();
14264 // If turning off SPS, close our socket
14265 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14266 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
14268 // If turning off, or changing type, deregister old name
14269 #ifndef SPC_DISABLED
14270 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
14271 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
14272 #endif // SPC_DISABLED
14274 // Record our new SPS parameters
14276 m
->SPSPortability
= port
;
14277 m
->SPSMarginalPower
= marginalpower
;
14278 m
->SPSTotalPower
= totpower
;
14279 m
->SPSFeatureFlags
= features
;
14280 // If turning on, open socket and advertise service
14285 m
->SPSSocket
= mDNSPlatformUDPSocket(m
, zeroIPPort
);
14286 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
14288 #ifndef SPC_DISABLED
14289 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
14290 #endif // SPC_DISABLED
14292 else if (m
->SPSState
)
14294 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
14295 m
->NextScheduledSPS
= m
->timenow
;
14298 mDNS_ReclaimLockAfterCallback();
14301 // ***************************************************************************
14302 #if COMPILER_LIKES_PRAGMA_MARK
14304 #pragma mark - Startup and Shutdown
14307 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14309 if (storage
&& numrecords
)
14312 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
14313 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
14314 storage
[numrecords
-1].next
= m
->rrcache_free
;
14315 m
->rrcache_free
= storage
;
14316 m
->rrcache_size
+= numrecords
;
14320 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14323 mDNS_GrowCache_internal(m
, storage
, numrecords
);
14327 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14328 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14329 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14335 if (!rrcachestorage
) rrcachesize
= 0;
14338 m
->NetworkChanged
= 0;
14339 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14340 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
14341 m
->DivertMulticastAdvertisements
= mDNSfalse
;
14342 m
->mDNSPlatformStatus
= mStatus_Waiting
;
14343 m
->UnicastPort4
= zeroIPPort
;
14344 m
->UnicastPort6
= zeroIPPort
;
14345 m
->PrimaryMAC
= zeroEthAddr
;
14346 m
->MainCallback
= Callback
;
14347 m
->MainContext
= Context
;
14348 m
->rec
.r
.resrec
.RecordType
= 0;
14349 m
->rec
.r
.resrec
.AnonInfo
= mDNSNULL
;
14351 // For debugging: To catch and report locking failures
14353 m
->mDNS_reentrancy
= 0;
14354 m
->ShutdownTime
= 0;
14355 m
->lock_rrcache
= 0;
14356 m
->lock_Questions
= 0;
14357 m
->lock_Records
= 0;
14359 // Task Scheduling variables
14360 result
= mDNSPlatformTimeInit();
14361 if (result
!= mStatus_NoError
) return(result
);
14362 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
14363 timenow
= mDNS_TimeNow_NoLock(m
);
14365 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14366 m
->timenow_last
= timenow
;
14367 m
->NextScheduledEvent
= timenow
;
14368 m
->SuppressSending
= timenow
;
14369 m
->NextCacheCheck
= timenow
+ 0x78000000;
14370 m
->NextScheduledQuery
= timenow
+ 0x78000000;
14371 m
->NextScheduledProbe
= timenow
+ 0x78000000;
14372 m
->NextScheduledResponse
= timenow
+ 0x78000000;
14373 m
->NextScheduledNATOp
= timenow
+ 0x78000000;
14374 m
->NextScheduledSPS
= timenow
+ 0x78000000;
14375 m
->NextScheduledKA
= timenow
+ 0x78000000;
14376 m
->NextScheduledStopTime
= timenow
+ 0x78000000;
14377 m
->NextBLEServiceTime
= 0; // zero indicates inactive
14379 #if BONJOUR_ON_DEMAND
14380 m
->NextBonjourDisableTime
= 0; // Timer active when non zero.
14381 m
->BonjourEnabled
= 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14382 #endif // BONJOUR_ON_DEMAND
14384 m
->DelayConflictProcessing
= MAX_CONFLICT_PROCESSING_DELAYS
;
14385 m
->RandomQueryDelay
= 0;
14386 m
->RandomReconfirmDelay
= 0;
14389 m
->LocalRemoveEvents
= mDNSfalse
;
14390 m
->SleepState
= SleepState_Awake
;
14391 m
->SleepSeqNum
= 0;
14392 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
14393 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
14397 #if APPLE_OSX_mDNSResponder
14398 m
->StatStartTime
= mDNSPlatformUTC();
14399 m
->NextStatLogTime
= m
->StatStartTime
+ kDefaultNextStatsticsLogTime
;
14400 m
->ActiveStatTime
= 0;
14401 m
->UnicastPacketsSent
= 0;
14402 m
->MulticastPacketsSent
= 0;
14403 m
->RemoteSubnet
= 0;
14404 #endif // APPLE_OSX_mDNSResponder
14406 // These fields only required for mDNS Searcher...
14407 m
->Questions
= mDNSNULL
;
14408 m
->NewQuestions
= mDNSNULL
;
14409 m
->CurrentQuestion
= mDNSNULL
;
14410 m
->LocalOnlyQuestions
= mDNSNULL
;
14411 m
->NewLocalOnlyQuestions
= mDNSNULL
;
14412 m
->RestartQuestion
= mDNSNULL
;
14413 m
->ValidationQuestion
= mDNSNULL
;
14414 m
->rrcache_size
= 0;
14415 m
->rrcache_totalused
= 0;
14416 m
->rrcache_active
= 0;
14417 m
->rrcache_report
= 10;
14418 m
->rrcache_free
= mDNSNULL
;
14420 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
14422 m
->rrcache_hash
[slot
] = mDNSNULL
;
14423 m
->rrcache_nextcheck
[slot
] = timenow
+ 0x78000000;;
14426 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
14427 m
->rrauth
.rrauth_free
= mDNSNULL
;
14429 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
14430 m
->rrauth
.rrauth_hash
[slot
] = mDNSNULL
;
14432 // Fields below only required for mDNS Responder...
14433 m
->hostlabel
.c
[0] = 0;
14434 m
->nicelabel
.c
[0] = 0;
14435 m
->MulticastHostname
.c
[0] = 0;
14436 m
->HIHardware
.c
[0] = 0;
14437 m
->HISoftware
.c
[0] = 0;
14438 m
->ResourceRecords
= mDNSNULL
;
14439 m
->DuplicateRecords
= mDNSNULL
;
14440 m
->NewLocalRecords
= mDNSNULL
;
14441 m
->NewLocalOnlyRecords
= mDNSfalse
;
14442 m
->CurrentRecord
= mDNSNULL
;
14443 m
->HostInterfaces
= mDNSNULL
;
14444 m
->ProbeFailTime
= 0;
14445 m
->NumFailedProbes
= 0;
14446 m
->SuppressProbes
= 0;
14448 #ifndef UNICAST_DISABLED
14449 m
->NextuDNSEvent
= timenow
+ 0x78000000;
14450 m
->NextSRVUpdate
= timenow
+ 0x78000000;
14452 m
->DNSServers
= mDNSNULL
;
14454 m
->Router
= zeroAddr
;
14455 m
->AdvertisedV4
= zeroAddr
;
14456 m
->AdvertisedV6
= zeroAddr
;
14458 m
->AuthInfoList
= mDNSNULL
;
14460 m
->ReverseMap
.ThisQInterval
= -1;
14461 m
->StaticHostname
.c
[0] = 0;
14463 m
->Hostnames
= mDNSNULL
;
14464 m
->AutoTunnelNAT
.clientContext
= mDNSNULL
;
14466 m
->WABBrowseQueriesCount
= 0;
14467 m
->WABLBrowseQueriesCount
= 0;
14468 m
->WABRegQueriesCount
= 0;
14469 m
->AutoTargetServices
= 0;
14471 #if BONJOUR_ON_DEMAND
14472 m
->NumAllInterfaceRecords
= 0;
14473 m
->NumAllInterfaceQuestions
= 0;
14475 // NAT traversal fields
14476 m
->LLQNAT
.clientCallback
= mDNSNULL
;
14477 m
->LLQNAT
.clientContext
= mDNSNULL
;
14478 m
->NATTraversals
= mDNSNULL
;
14479 m
->CurrentNATTraversal
= mDNSNULL
;
14480 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
14481 m
->retryGetAddr
= timenow
+ 0x78000000; // absolute time when we retry
14482 m
->ExtAddress
= zerov4Addr
;
14483 m
->PCPNonce
[0] = mDNSRandom(-1);
14484 m
->PCPNonce
[1] = mDNSRandom(-1);
14485 m
->PCPNonce
[2] = mDNSRandom(-1);
14487 m
->NATMcastRecvskt
= mDNSNULL
;
14488 m
->LastNATupseconds
= 0;
14489 m
->LastNATReplyLocalTime
= timenow
;
14490 m
->LastNATMapResultCode
= NATErr_None
;
14492 m
->UPnPInterfaceID
= 0;
14493 m
->SSDPSocket
= mDNSNULL
;
14494 m
->SSDPWANPPPConnection
= mDNSfalse
;
14495 m
->UPnPRouterPort
= zeroIPPort
;
14496 m
->UPnPSOAPPort
= zeroIPPort
;
14497 m
->UPnPRouterURL
= mDNSNULL
;
14498 m
->UPnPWANPPPConnection
= mDNSfalse
;
14499 m
->UPnPSOAPURL
= mDNSNULL
;
14500 m
->UPnPRouterAddressString
= mDNSNULL
;
14501 m
->UPnPSOAPAddressString
= mDNSNULL
;
14503 m
->SPSPortability
= 0;
14504 m
->SPSMarginalPower
= 0;
14505 m
->SPSTotalPower
= 0;
14506 m
->SPSFeatureFlags
= 0;
14508 m
->SPSProxyListChanged
= mDNSNULL
;
14509 m
->SPSSocket
= mDNSNULL
;
14510 m
->SPSBrowseCallback
= mDNSNULL
;
14511 m
->ProxyRecords
= 0;
14513 m
->DNSPushServers
= mDNSNULL
;
14514 m
->DNSPushZones
= mDNSNULL
;
14517 #if APPLE_OSX_mDNSResponder
14518 m
->TunnelClients
= mDNSNULL
;
14521 CHECK_WCF_FUNCTION(WCFConnectionNew
)
14523 m
->WCF
= WCFConnectionNew();
14524 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
14530 result
= mDNSPlatformInit(m
);
14532 #ifndef UNICAST_DISABLED
14533 // It's better to do this *after* the platform layer has set up the
14534 // interface list and security credentials
14535 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
14541 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
14543 if (m
->SPSState
== 1)
14545 domainlabel name
, newname
;
14546 #ifndef SPC_DISABLED
14547 domainname type
, domain
;
14548 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
14549 #endif // SPC_DISABLED
14550 ConstructSleepProxyServerName(m
, &newname
);
14551 if (!SameDomainLabelCS(name
.c
, newname
.c
))
14553 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
14554 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14555 // it will reregister the service under the new name
14557 #ifndef SPC_DISABLED
14558 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
14559 #endif // SPC_DISABLED
14563 if (m
->MainCallback
)
14564 m
->MainCallback(m
, mStatus_ConfigChanged
);
14567 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
14570 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
14571 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
14574 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
, const DNSServer
* const ptr
, mDNSBool lameduck
)
14576 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
14577 cr
->resrec
.rrtype
== kDNSType_A
||
14578 cr
->resrec
.rrtype
== kDNSType_AAAA
||
14579 cr
->resrec
.rrtype
== kDNSType_SRV
;
14583 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
14584 purge
? "purging" : "reconfirming",
14585 lameduck
? "lame duck" : "new",
14586 ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
, CRDisplayString(m
, cr
));
14590 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14591 mDNS_PurgeCacheResourceRecord(m
, cr
);
14595 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14596 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
14600 mDNSlocal
void mDNS_PurgeForQuestion(mDNS
*const m
, DNSQuestion
*q
)
14602 const mDNSu32 slot
= HashSlot(&q
->qname
);
14603 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
14605 mDNSu8 validatingResponse
= 0;
14607 // For DNSSEC questions, purge the corresponding RRSIGs also.
14608 if (DNSSECQuestion(q
))
14610 validatingResponse
= q
->ValidatingResponse
;
14611 q
->ValidatingResponse
= mDNStrue
;
14613 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14615 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
14617 LogInfo("mDNS_PurgeForQuestion: Flushing %s", CRDisplayString(m
, rp
));
14618 mDNS_PurgeCacheResourceRecord(m
, rp
);
14621 if (DNSSECQuestion(q
))
14623 q
->ValidatingResponse
= validatingResponse
;
14627 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14628 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14629 // Just re-issuing the question for RRSIGs does not work in practice as the response
14630 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14632 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14633 // have the cached NSECs, purge them. For positive responses, if we don't have the
14634 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14636 mDNSlocal
void CheckForDNSSECRecords(mDNS
*const m
, DNSQuestion
*q
)
14638 const mDNSu32 slot
= HashSlot(&q
->qname
);
14639 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
14642 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14644 if (SameNameRecordAnswersQuestion(&rp
->resrec
, q
))
14646 if (rp
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| !rp
->nsec
)
14648 if (!rp
->CRDNSSECQuestion
)
14650 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m
, rp
));
14651 mDNS_PurgeCacheResourceRecord(m
, rp
);
14658 // Check for a positive unicast response to the question but with qtype
14659 mDNSexport mDNSBool
mDNS_CheckForCacheRecord(mDNS
*const m
, DNSQuestion
*q
, mDNSu16 qtype
)
14661 DNSQuestion question
;
14662 const mDNSu32 slot
= HashSlot(&q
->qname
);
14663 CacheGroup
*const cg
= CacheGroupForName(m
, slot
, q
->qnamehash
, &q
->qname
);
14666 // Create an identical question but with qtype
14667 mDNS_SetupQuestion(&question
, q
->InterfaceID
, &q
->qname
, qtype
, mDNSNULL
, mDNSNULL
);
14668 question
.qDNSServer
= q
->qDNSServer
;
14670 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14672 if (!rp
->resrec
.InterfaceID
&& rp
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&&
14673 SameNameRecordAnswersQuestion(&rp
->resrec
, &question
))
14675 LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m
, rp
));
14682 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
14688 if (q
->DuplicateOf
)
14689 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
14691 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14692 // of events for all of them are consistent. Duplicates for a question are always inserted
14693 // after in the list.
14694 q
->qDNSServer
= new;
14695 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14697 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
14701 mDNSlocal
void SetConfigState(mDNS
*const m
, mDNSBool
delete)
14708 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14710 ptr
->penaltyTime
= 0;
14711 NumUnicastDNSServers
--;
14712 ptr
->flags
|= DNSServer_FlagDelete
;
14713 #if APPLE_OSX_mDNSResponder
14714 if (ptr
->flags
& DNSServer_FlagUnreachable
)
14715 NumUnreachableDNSServers
--;
14718 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14719 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14721 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14722 mr
->flags
|= McastResolver_FlagDelete
;
14726 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14728 ptr
->penaltyTime
= 0;
14729 NumUnicastDNSServers
++;
14730 ptr
->flags
&= ~DNSServer_FlagDelete
;
14731 #if APPLE_OSX_mDNSResponder
14732 if (ptr
->flags
& DNSServer_FlagUnreachable
)
14733 NumUnreachableDNSServers
++;
14736 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14737 mr
->flags
&= ~McastResolver_FlagDelete
;
14741 mDNSlocal
void SetDynDNSHostNameIfChanged(mDNS
*const m
, domainname
*const fqdn
)
14743 // Did our FQDN change?
14744 if (!SameDomainName(fqdn
, &m
->FQDN
))
14746 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
14748 AssignDomainName(&m
->FQDN
, fqdn
);
14752 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
14753 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
14758 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
14763 mDNSBool Restart
= mDNSfalse
;
14764 mDNSAddr v4
, v6
, r
;
14766 DNSServer
*ptr
, **p
= &m
->DNSServers
;
14767 const DNSServer
*oldServers
= m
->DNSServers
;
14769 McastResolver
*mr
, **mres
= &m
->McastResolvers
;
14771 debugf("uDNS_SetupDNSConfig: entry");
14773 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14774 uDNS_SetupWABQueries(m
);
14778 // We need to first mark all the entries to be deleted. If the configuration changed, then
14779 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14781 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14782 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14783 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14784 // for the dns configuration change notification.
14785 SetConfigState(m
, mDNStrue
);
14786 if (!mDNSPlatformSetDNSConfig(m
, mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
, mDNStrue
))
14788 SetDynDNSHostNameIfChanged(m
, &fqdn
);
14789 SetConfigState(m
, mDNSfalse
);
14791 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14792 return mStatus_NoError
;
14795 // For now, we just delete the mcast resolvers. We don't deal with cache or
14796 // questions here. Neither question nor cache point to mcast resolvers. Questions
14797 // do inherit the timeout values from mcast resolvers. But we don't bother
14798 // affecting them as they never change.
14801 if (((*mres
)->flags
& McastResolver_FlagDelete
) != 0)
14804 *mres
= (*mres
)->next
;
14805 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr
, mr
->domain
.c
);
14806 mDNSPlatformMemFree(mr
);
14810 (*mres
)->flags
&= ~McastResolver_FlagNew
;
14811 mres
= &(*mres
)->next
;
14815 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14817 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14818 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14819 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14820 // DNSServers and flush the cache.
14822 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14823 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14824 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14825 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14826 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14827 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14828 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14829 // the same resGroupID.
14831 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14832 // of the old followed by ADD of the new records.
14834 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14835 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14836 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14838 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14839 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14840 // non-scoped question and vice versa.
14842 for (q
= m
->Questions
; q
; q
=q
->next
)
14844 if (!mDNSOpaque16IsZero(q
->TargetQID
))
14848 if (q
->DuplicateOf
) continue;
14849 SetValidDNSServers(m
, q
);
14850 q
->triedAllServersOnce
= 0;
14851 s
= GetServerForQuestion(m
, q
);
14856 // If DNS Server for this question has changed, reactivate it
14857 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
14858 t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), t
? t
->domain
.c
: (mDNSu8
*)"",
14859 s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), s
? s
->domain
.c
: (mDNSu8
*)"",
14860 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->InterfaceID
);
14862 old
= q
->SuppressQuery
;
14863 new = ShouldSuppressUnicastQuery(m
, q
, s
);
14866 // Changing the DNS server affected the SuppressQuery status. We need to
14867 // deliver RMVs for the previous ADDs (if any) before switching to the new
14868 // DNSServer. To keep it simple, we walk all the questions and mark them
14869 // to be restarted and then handle all of them at once.
14871 q
->SuppressQuery
= new;
14872 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14874 if (qptr
->DuplicateOf
== q
)
14877 Restart
= mDNStrue
;
14881 DNSServerChangeForQuestion(m
, q
, s
);
14882 q
->unansweredQueries
= 0;
14884 // If we had sent a query out to DNSServer "t" and we are changing to "s", we
14885 // need to ignore the responses coming back from "t" as the DNS configuration
14886 // has changed e.g., when a new interface is coming up and that becomes the primary
14887 // interface, we switch to the DNS servers configured for the primary interface. In
14888 // this case, we should not accept responses associated with the previous interface as
14889 // the "name" could resolve differently on this new primary interface. Hence, discard
14890 // in-flight responses.
14891 q
->TargetQID
= mDNS_NewMessageID(m
);
14893 if (!QuerySuppressed(q
))
14895 debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
14896 ActivateUnicastQuery(m
, q
, mDNStrue
);
14897 // ActivateUnicastQuery is called for duplicate questions also as it does something
14898 // special for AutoTunnel questions
14899 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14901 if (qptr
->DuplicateOf
== q
) ActivateUnicastQuery(m
, qptr
, mDNStrue
);
14908 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
14909 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), q
->DuplicateOf
, q
->SuppressUnusable
);
14910 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14911 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= q
->qDNSServer
; }
14916 RestartUnicastQuestions(m
);
14918 FORALL_CACHERECORDS(slot
, cg
, cr
)
14920 if (cr
->resrec
.InterfaceID
)
14923 // We already walked the questions and restarted/reactivated them if the dns server
14924 // change affected the question. That should take care of updating the cache. But
14925 // what if there is no active question at this point when the DNS server change
14926 // happened ? There could be old cache entries lying around and if we don't flush
14927 // them, a new question after the DNS server change could pick up these stale
14928 // entries and get a wrong answer.
14930 // For cache entries that have active questions we might have skipped rescheduling
14931 // the questions if they were suppressed (see above). To keep it simple, we walk
14932 // all the cache entries to make sure that there are no stale entries. We use the
14933 // active question's InterfaceID/ServiceID for looking up the right DNS server.
14934 // Note that the unscoped value for ServiceID is -1.
14936 // Note: If GetServerForName returns NULL, it could either mean that there are no
14937 // DNS servers or no matching DNS servers for this question. In either case,
14938 // the cache should get purged below when we process deleted DNS servers.
14940 ptr
= GetServerForName(m
, cr
->resrec
.name
,
14941 (cr
->CRActiveQuestion
? cr
->CRActiveQuestion
->InterfaceID
: mDNSNULL
),
14942 (cr
->CRActiveQuestion
? cr
->CRActiveQuestion
->ServiceID
: -1));
14944 // Purge or Reconfirm if this cache entry would use the new DNS server
14945 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
14947 // As the DNSServers for this cache record is not the same anymore, we don't
14948 // want any new questions to pick this old value. If there is no active question,
14949 // we can't possibly re-confirm, so purge in that case. If it is a DNSSEC question,
14950 // purge the cache as the DNSSEC capabilities of the DNS server may have changed.
14952 if (cr
->CRActiveQuestion
== mDNSNULL
|| DNSSECQuestion(cr
->CRActiveQuestion
))
14954 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m
, cr
),
14955 &ptr
->addr
, (cr
->resrec
.rDNSServer
!= mDNSNULL
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
));
14956 mDNS_PurgeCacheResourceRecord(m
, cr
);
14960 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m
, cr
),
14961 &ptr
->addr
, (cr
->resrec
.rDNSServer
!= mDNSNULL
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
));
14962 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNSfalse
);
14966 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
14967 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
14968 if (!cr
->resrec
.rDNSServer
&& cr
->CRActiveQuestion
&& cr
->CRActiveQuestion
->qDNSServer
)
14970 cr
->resrec
.rDNSServer
= cr
->CRActiveQuestion
->qDNSServer
;
14971 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr
->resrec
.rDNSServer
->addr
, CRDisplayString(m
, cr
));
14977 if (((*p
)->flags
& DNSServer_FlagDelete
) != 0)
14979 // Scan our cache, looking for uDNS records that we would have queried this server for.
14980 // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
14981 // different DNS servers can give different answers to the same question.
14983 FORALL_CACHERECORDS(slot
, cg
, cr
)
14985 if (cr
->resrec
.InterfaceID
) continue;
14986 if (cr
->resrec
.rDNSServer
== ptr
)
14988 // If we don't have an active question for this cache record, neither Purge can
14989 // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
14990 // pointer on the record NULL so that we don't point to freed memory (We might dereference
14991 // DNSServer pointers from resource record for logging purposes).
14993 // If there is an active question, point to its DNSServer as long as it does not point to the
14994 // freed one. We already went through the questions above and made them point at either the
14995 // new server or NULL if there is no server.
14997 if (cr
->CRActiveQuestion
)
14999 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
15001 if (qptr
->qDNSServer
== ptr
)
15003 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15004 " to be freed", CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
, &ptr
->addr
);
15005 qptr
->validDNSServers
= zeroOpaque64
;
15006 qptr
->qDNSServer
= mDNSNULL
;
15007 cr
->resrec
.rDNSServer
= mDNSNULL
;
15011 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15012 " resetting to question's DNSServer Address %#a", CRDisplayString(m
, cr
), qptr
->qname
.c
, DNSTypeName(qptr
->qtype
),
15013 qptr
->InterfaceID
, &ptr
->addr
, (qptr
->qDNSServer
) ? &qptr
->qDNSServer
->addr
: mDNSNULL
);
15014 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
15019 LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
15020 cr
->resrec
.name
, &cr
->resrec
.rDNSServer
->addr
, &ptr
->addr
);
15021 cr
->resrec
.rDNSServer
= mDNSNULL
;
15024 PurgeOrReconfirmCacheRecord(m
, cr
, ptr
, mDNStrue
);
15028 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s) %d", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
, NumUnicastDNSServers
);
15029 mDNSPlatformMemFree(ptr
);
15033 (*p
)->flags
&= ~DNSServer_FlagNew
;
15038 // 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).
15039 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15040 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15041 // 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.
15042 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
15045 FORALL_CACHERECORDS(slot
, cg
, cr
)
15047 if (!cr
->resrec
.InterfaceID
)
15049 mDNS_PurgeCacheResourceRecord(m
, cr
);
15053 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15054 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
15056 // Force anything that needs to get zone data to get that information again
15057 RestartRecordGetZoneData(m
);
15060 SetDynDNSHostNameIfChanged(m
, &fqdn
);
15064 // handle router and primary interface changes
15065 v4
= v6
= r
= zeroAddr
;
15066 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
15068 if (mDNSPlatformGetPrimaryInterface(m
, &v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
15070 mDNS_SetPrimaryInterfaceInfo(m
,
15071 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
15072 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
15073 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
15077 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
15078 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
15081 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers
);
15082 return mStatus_NoError
;
15085 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
15087 m
->mDNSPlatformStatus
= result
;
15088 if (m
->MainCallback
)
15091 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15092 m
->MainCallback(m
, mStatus_NoError
);
15093 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15098 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
15100 m
->CurrentRecord
= start
;
15101 while (m
->CurrentRecord
)
15103 AuthRecord
*rr
= m
->CurrentRecord
;
15104 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15105 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
15106 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15107 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
15108 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
15109 else if (rr
->AnnounceCount
> 1)
15111 rr
->AnnounceCount
= 1;
15112 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
15114 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15115 // new records could have been added to the end of the list as a result of that call.
15116 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
15117 m
->CurrentRecord
= rr
->next
;
15121 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
15127 LogInfo("mDNS_StartExit");
15128 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
15130 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0, 0);
15132 #if APPLE_OSX_mDNSResponder
15134 CHECK_WCF_FUNCTION(WCFConnectionDealloc
)
15136 if (m
->WCF
) WCFConnectionDealloc((WCFConnection
*)m
->WCF
);
15141 #ifndef UNICAST_DISABLED
15145 // Don't need to do SleepRecordRegistrations() here
15146 // because we deregister all records and services later in this routine
15147 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
15149 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15150 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15151 // and we may crash because the list still contains dangling pointers.
15152 for (s
= SearchList
; s
; s
= s
->next
)
15153 while (s
->AuthRecs
)
15155 ARListElem
*dereg
= s
->AuthRecs
;
15156 s
->AuthRecs
= s
->AuthRecs
->next
;
15157 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
15162 DeadvertiseAllInterfaceRecords(m
);
15164 // Shut down all our active NAT Traversals
15165 while (m
->NATTraversals
)
15167 NATTraversalInfo
*t
= m
->NATTraversals
;
15168 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15170 // After stopping the NAT Traversal, we zero out the fields.
15171 // This has particularly important implications for our AutoTunnel records --
15172 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15173 // handlers to just turn around and attempt to re-register those same records.
15174 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15176 t
->ExternalAddress
= zerov4Addr
;
15177 t
->NewAddress
= zerov4Addr
;
15178 t
->ExternalPort
= zeroIPPort
;
15179 t
->RequestedPort
= zeroIPPort
;
15181 t
->Result
= mStatus_NoError
;
15184 // Make sure there are nothing but deregistering records remaining in the list
15185 if (m
->CurrentRecord
)
15186 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
15188 // We're in the process of shutting down, so queries, etc. are no longer available.
15189 // Consequently, determining certain information, e.g. the uDNS update server's IP
15190 // address, will not be possible. The records on the main list are more likely to
15191 // already contain such information, so we deregister the duplicate records first.
15192 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15193 DeregLoop(m
, m
->DuplicateRecords
);
15194 LogInfo("mDNS_StartExit: Deregistering resource records");
15195 DeregLoop(m
, m
->ResourceRecords
);
15197 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15198 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15199 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
15201 m
->NextScheduledResponse
= m
->timenow
;
15202 m
->SuppressSending
= 0;
15205 if (m
->ResourceRecords
) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15206 else LogInfo("mDNS_StartExit: No deregistering records remain");
15208 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
15209 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15211 // If any deregistering records remain, send their deregistration announcements before we exit
15212 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
15216 LogInfo("mDNS_StartExit: done");
15219 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
15221 mDNSu32 rrcache_active
= 0;
15222 mDNSu32 rrcache_totalused
= m
->rrcache_totalused
;
15226 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
15227 mDNSPlatformClose(m
);
15229 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
15231 while (m
->rrcache_hash
[slot
])
15233 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
15234 while (cg
->members
)
15236 CacheRecord
*cr
= cg
->members
;
15237 cg
->members
= cg
->members
->next
;
15238 if (cr
->CRActiveQuestion
) rrcache_active
++;
15239 ReleaseCacheRecord(m
, cr
);
15241 cg
->rrcache_tail
= &cg
->members
;
15242 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
15245 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
15246 if (rrcache_active
!= m
->rrcache_active
)
15247 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused
, rrcache_active
, m
->rrcache_active
);
15249 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
15250 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15252 LogInfo("mDNS_FinalExit: done");