1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
3 * Copyright (c) 2002-2019 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
31 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
35 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
36 #include "SymptomReporter.h"
39 // Disable certain benign warnings with Microsoft compilers
40 #if (defined(_MSC_VER))
41 // Disable "conditional expression is constant" warning for debug macros.
42 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
43 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
44 #pragma warning(disable:4127)
46 // Disable "assignment within conditional expression".
47 // Other compilers understand the convention that if you place the assignment expression within an extra pair
48 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
49 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
50 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
51 #pragma warning(disable:4706)
54 #include "dns_sd.h" // for kDNSServiceFlags* definitions
55 #include "dns_sd_internal.h"
57 #if APPLE_OSX_mDNSResponder
58 // Delay in seconds before disabling multicast after there are no active queries or registrations.
59 #define BONJOUR_DISABLE_DELAY 60
62 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
63 #include <WebFilterDNS/WebFilterDNS.h>
65 WCFConnection
*WCFConnectionNew(void) __attribute__((weak_import
));
66 void WCFConnectionDealloc(WCFConnection
* c
) __attribute__((weak_import
));
69 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
73 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
77 // Forward declarations
78 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
);
79 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
);
80 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
);
81 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
82 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
);
83 mDNSlocal
void CheckForDNSSECRecords(mDNS
*const m
, DNSQuestion
*q
);
84 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
);
85 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
,
86 mDNSu32
*seq
, mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
);
88 typedef mDNSu32 DeadvertiseFlags
;
89 #define kDeadvertiseFlag_NormalHostname (1U << 0)
90 #define kDeadvertiseFlag_RandHostname (1U << 1)
91 #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
93 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, DeadvertiseFlags flags
);
94 mDNSlocal
void AdvertiseInterfaceIfNeeded(mDNS
*const m
, NetworkInterfaceInfo
*set
);
95 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
);
96 mDNSlocal
void mDNSParseNSEC3Records(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
97 const mDNSInterfaceID InterfaceID
, CacheRecord
**NSEC3Records
);
98 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
);
100 // ***************************************************************************
101 #if COMPILER_LIKES_PRAGMA_MARK
102 #pragma mark - Program Constants
105 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
106 #define MDNS_TRACER 1
108 // Any records bigger than this are considered 'large' records
109 #define SmallRecordLimit 1024
111 #define kMaxUpdateCredits 10
112 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
114 // define special NR_AnswerTo values
115 #define NR_AnswerMulticast (mDNSu8*)~0
116 #define NR_AnswerUnicast (mDNSu8*)~1
118 // Question default timeout values
119 #define DEFAULT_MCAST_TIMEOUT 5
120 #define DEFAULT_LO_OR_P2P_TIMEOUT 5
122 // The code (see SendQueries() and BuildQuestion()) needs to have the
123 // RequestUnicast value set to a value one greater than the number of times you want the query
124 // sent with the "request unicast response" (QU) bit set.
125 #define SET_QU_IN_FIRST_QUERY 2
126 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
128 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
129 #define DARK_WAKE_DELAY_SLEEP 5
130 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
132 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
133 #define MAX_CONFLICT_PROCESSING_DELAYS 3
135 // RFC 6762 defines Passive Observation Of Failures (POOF)
137 // A host observes the multicast queries issued by the other hosts on
138 // the network. One of the major benefits of also sending responses
139 // using multicast is that it allows all hosts to see the responses
140 // (or lack thereof) to those queries.
142 // If a host sees queries, for which a record in its cache would be
143 // expected to be given as an answer in a multicast response, but no
144 // such answer is seen, then the host may take this as an indication
145 // that the record may no longer be valid.
147 // After seeing two or more of these queries, and seeing no multicast
148 // response containing the expected answer within ten seconds, then even
149 // though its TTL may indicate that it is not yet due to expire, that
150 // record SHOULD be flushed from the cache.
152 // <https://tools.ietf.org/html/rfc6762#section-10.5>
154 #define POOF_ENABLED 1
156 mDNSexport
const char *const mDNS_DomainTypeNames
[] =
158 "b._dns-sd._udp.", // Browse
159 "db._dns-sd._udp.", // Default Browse
160 "lb._dns-sd._udp.", // Automatic Browse
161 "r._dns-sd._udp.", // Registration
162 "dr._dns-sd._udp." // Default Registration
165 #ifdef UNICAST_DISABLED
166 #define uDNS_IsActiveQuery(q, u) mDNSfalse
169 // ***************************************************************************
170 #if COMPILER_LIKES_PRAGMA_MARK
172 #pragma mark - General Utility Functions
175 #if MDNS_MALLOC_DEBUGGING
176 // When doing memory allocation debugging, this function traverses all lists in the mDNS query
177 // structures and caches and checks each entry in the list to make sure it's still good.
178 mDNSlocal
void mDNS_ValidateLists(void *context
)
181 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
182 mDNSu32 NumAllInterfaceRecords
= 0;
183 mDNSu32 NumAllInterfaceQuestions
= 0;
186 // Check core mDNS lists
188 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
190 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
191 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
192 if (rr
->resrec
.name
!= &rr
->namestorage
)
193 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
194 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
195 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
196 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
200 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
202 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
203 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
204 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
205 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
209 rr
= m
->NewLocalRecords
;
211 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
212 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
214 rr
= m
->CurrentRecord
;
216 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
217 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
220 for (q
= m
->Questions
; q
; q
=q
->next
)
222 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
223 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
224 if (q
->DuplicateOf
&& q
->LocalSocket
)
225 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
226 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
227 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
228 NumAllInterfaceQuestions
++;
235 FORALL_CACHERECORDS(slot
, cg
, cr
)
237 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
238 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
239 if (cr
->CRActiveQuestion
)
241 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
242 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
246 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
247 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
248 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
250 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
251 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
252 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
254 #endif // MDNS_MALLOC_DEBUGGING
256 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
257 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
258 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
259 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
260 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
261 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
262 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
263 (rr)->resrec.rrtype == kDNSType_CNAME || \
264 (rr)->resrec.rrtype == kDNSType_PTR))
266 mDNSlocal
void SetNextQueryStopTime(mDNS
*const m
, const DNSQuestion
*const q
)
270 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
271 m
->NextScheduledStopTime
= q
->StopTime
;
274 mDNSexport
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
278 if (ActiveQuestion(q
))
280 // Depending on whether this is a multicast or unicast question we want to set either:
281 // m->NextScheduledQuery = NextQSendTime(q) or
282 // m->NextuDNSEvent = NextQSendTime(q)
283 mDNSs32
*const timer
= mDNSOpaque16IsZero(q
->TargetQID
) ? &m
->NextScheduledQuery
: &m
->NextuDNSEvent
;
284 if (*timer
- NextQSendTime(q
) > 0)
285 *timer
= NextQSendTime(q
);
289 mDNSlocal
void ReleaseAuthEntity(AuthHash
*r
, AuthEntity
*e
)
291 #if MDNS_MALLOC_DEBUGGING >= 1
293 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
295 e
->next
= r
->rrauth_free
;
297 r
->rrauth_totalused
--;
300 mDNSlocal
void ReleaseAuthGroup(AuthHash
*r
, AuthGroup
**cp
)
302 AuthEntity
*e
= (AuthEntity
*)(*cp
);
303 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp
)->name
->c
);
304 if ((*cp
)->rrauth_tail
!= &(*cp
)->members
)
305 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
306 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
307 (*cp
)->name
= mDNSNULL
;
308 *cp
= (*cp
)->next
; // Cut record from list
309 ReleaseAuthEntity(r
, e
);
312 mDNSlocal AuthEntity
*GetAuthEntity(AuthHash
*r
, const AuthGroup
*const PreserveAG
)
314 AuthEntity
*e
= mDNSNULL
;
316 if (r
->rrauth_lock
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
321 // We allocate just one AuthEntity at a time because we need to be able
322 // free them all individually which normally happens when we parse /etc/hosts into
323 // AuthHash where we add the "new" entries and discard (free) the already added
324 // entries. If we allocate as chunks, we can't free them individually.
325 AuthEntity
*storage
= (AuthEntity
*) mDNSPlatformMemAllocateClear(sizeof(*storage
));
326 storage
->next
= mDNSNULL
;
327 r
->rrauth_free
= storage
;
330 // If we still have no free records, recycle all the records we can.
331 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
334 mDNSu32 oldtotalused
= r
->rrauth_totalused
;
336 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
338 AuthGroup
**cp
= &r
->rrauth_hash
[slot
];
341 if ((*cp
)->members
|| (*cp
)==PreserveAG
) cp
=&(*cp
)->next
;
342 else ReleaseAuthGroup(r
, cp
);
345 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
346 oldtotalused
- r
->rrauth_totalused
, oldtotalused
, r
->rrauth_totalused
);
349 if (r
->rrauth_free
) // If there are records in the free list, take one
352 r
->rrauth_free
= e
->next
;
353 if (++r
->rrauth_totalused
>= r
->rrauth_report
)
355 LogInfo("RR Auth now using %ld objects", r
->rrauth_totalused
);
356 if (r
->rrauth_report
< 100) r
->rrauth_report
+= 10;
357 else if (r
->rrauth_report
< 1000) r
->rrauth_report
+= 100;
358 else r
->rrauth_report
+= 1000;
360 mDNSPlatformMemZero(e
, sizeof(*e
));
368 mDNSexport AuthGroup
*AuthGroupForName(AuthHash
*r
, const mDNSu32 namehash
, const domainname
*const name
)
371 const mDNSu32 slot
= namehash
% AUTH_HASH_SLOTS
;
373 for (ag
= r
->rrauth_hash
[slot
]; ag
; ag
=ag
->next
)
374 if (ag
->namehash
== namehash
&& SameDomainName(ag
->name
, name
))
379 mDNSexport AuthGroup
*AuthGroupForRecord(AuthHash
*r
, const ResourceRecord
*const rr
)
381 return(AuthGroupForName(r
, rr
->namehash
, rr
->name
));
384 mDNSlocal AuthGroup
*GetAuthGroup(AuthHash
*r
, const ResourceRecord
*const rr
)
386 mDNSu16 namelen
= DomainNameLength(rr
->name
);
387 AuthGroup
*ag
= (AuthGroup
*)GetAuthEntity(r
, mDNSNULL
);
388 const mDNSu32 slot
= rr
->namehash
% AUTH_HASH_SLOTS
;
389 if (!ag
) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
390 ag
->next
= r
->rrauth_hash
[slot
];
391 ag
->namehash
= rr
->namehash
;
392 ag
->members
= mDNSNULL
;
393 ag
->rrauth_tail
= &ag
->members
;
394 ag
->NewLocalOnlyRecords
= mDNSNULL
;
395 if (namelen
> sizeof(ag
->namestorage
))
396 ag
->name
= (domainname
*) mDNSPlatformMemAllocate(namelen
);
398 ag
->name
= (domainname
*)ag
->namestorage
;
401 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
402 ReleaseAuthEntity(r
, (AuthEntity
*)ag
);
405 AssignDomainName(ag
->name
, rr
->name
);
407 if (AuthGroupForRecord(r
, rr
)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr
->name
->c
);
408 r
->rrauth_hash
[slot
] = ag
;
409 if (AuthGroupForRecord(r
, rr
) != ag
) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr
->name
->c
);
414 // Returns the AuthGroup in which the AuthRecord was inserted
415 mDNSexport AuthGroup
*InsertAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
420 ag
= AuthGroupForRecord(r
, &rr
->resrec
);
421 if (!ag
) ag
= GetAuthGroup(r
, &rr
->resrec
); // If we don't have a AuthGroup for this name, make one now
424 *(ag
->rrauth_tail
) = rr
; // Append this record to tail of cache slot list
425 ag
->rrauth_tail
= &(rr
->next
); // Advance tail pointer
430 mDNSexport AuthGroup
*RemoveAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
435 a
= AuthGroupForRecord(r
, &rr
->resrec
);
436 if (!a
) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m
, rr
)); return mDNSNULL
; }
444 // We don't break here, so that we can set the tail below without tracking "prev" pointers
446 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m
, rr
));
447 *rp
= (*rp
)->next
; // Cut record from list
450 // TBD: If there are no more members, release authgroup ?
455 mDNSexport CacheGroup
*CacheGroupForName(const mDNS
*const m
, const mDNSu32 namehash
, const domainname
*const name
)
458 mDNSu32 slot
= HashSlotFromNameHash(namehash
);
459 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
460 if (cg
->namehash
== namehash
&& SameDomainName(cg
->name
, name
))
465 mDNSlocal CacheGroup
*CacheGroupForRecord(const mDNS
*const m
, const ResourceRecord
*const rr
)
467 return(CacheGroupForName(m
, rr
->namehash
, rr
->name
));
470 mDNSexport mDNSBool
mDNS_AddressIsLocalSubnet(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, const mDNSAddr
*addr
)
472 NetworkInterfaceInfo
*intf
;
474 if (addr
->type
== mDNSAddrType_IPv4
)
476 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
477 if (mDNSv4AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
478 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
479 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
480 if (((intf
->ip
.ip
.v4
.NotAnInteger
^ addr
->ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0)
484 if (addr
->type
== mDNSAddrType_IPv6
)
486 if (mDNSv6AddressIsLinkLocal(&addr
->ip
.v6
)) return(mDNStrue
);
487 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
488 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
489 if ((((intf
->ip
.ip
.v6
.l
[0] ^ addr
->ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
490 (((intf
->ip
.ip
.v6
.l
[1] ^ addr
->ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
491 (((intf
->ip
.ip
.v6
.l
[2] ^ addr
->ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
492 (((intf
->ip
.ip
.v6
.l
[3] ^ addr
->ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0))
499 mDNSlocal NetworkInterfaceInfo
*FirstInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
501 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
502 while (intf
&& intf
->InterfaceID
!= InterfaceID
) intf
= intf
->next
;
506 mDNSlocal NetworkInterfaceInfo
*FirstIPv4LLInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
508 NetworkInterfaceInfo
*intf
;
513 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
514 // we still want to find the first IPv4 Link-Local interface
515 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
517 if (intf
->InterfaceID
== InterfaceID
&&
518 intf
->ip
.type
== mDNSAddrType_IPv4
&& mDNSv4AddressIsLinkLocal(&intf
->ip
.ip
.v4
))
520 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf
->ip
.ip
.v4
);
527 mDNSexport
char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
529 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
530 return(intf
? intf
->ifname
: mDNSNULL
);
533 // Caller should hold the lock
534 mDNSlocal
void GenerateNegativeResponseEx(mDNS
*const m
, mDNSInterfaceID InterfaceID
, QC_result qc
, mDNSBool noData
)
537 if (!m
->CurrentQuestion
) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
538 q
= m
->CurrentQuestion
;
539 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
540 "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME
" (" PUB_S
")",
541 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
543 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, InterfaceID
, mDNSNULL
);
544 m
->rec
.r
.resrec
.negativeRecordType
= noData
? kNegativeRecordType_NoData
: kNegativeRecordType_Unspecified
;
546 // We need to force the response through in the following cases
548 // a) SuppressUnusable questions that are suppressed
549 // b) Append search domains and retry the question
551 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
552 // through we use "QC_forceresponse".
553 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, qc
);
554 if (m
->CurrentQuestion
== q
) { q
->ThisQInterval
= 0; } // Deactivate this question
555 // Don't touch the question after this
556 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
558 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
560 mDNSexport
void AnswerQuestionByFollowingCNAME(mDNS
*const m
, DNSQuestion
*q
, ResourceRecord
*rr
)
562 const mDNSBool selfref
= SameDomainName(&q
->qname
, &rr
->rdata
->u
.name
);
563 if (q
->CNAMEReferrals
>= 10 || selfref
)
565 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
566 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME
" (" PUB_S
") NOT following CNAME referral %d" PUB_S
" for " PRI_S
,
567 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
),
568 q
->CNAMEReferrals
, selfref
? " (Self-Referential)" : "", RRDisplayString(m
, rr
));
573 const mDNSu32 c
= q
->CNAMEReferrals
+ 1; // Stash a copy of the new q->CNAMEReferrals value
574 UDPSocket
*sock
= q
->LocalSocket
;
575 mDNSOpaque16 id
= q
->TargetQID
;
576 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
580 q
->LocalSocket
= mDNSNULL
;
582 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
583 // themselves. Without that check we can get into a case where we have two duplicate questions,
584 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
585 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
586 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
587 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
588 // for either of them. This is not a problem for CNAME loops of two or more records because in
589 // those cases the newly re-appended question A has a different target name and therefore cannot be
590 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
592 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
593 // and track CNAMEs coming and going, we should really create a subordinate query here,
594 // which we would subsequently cancel and retract if the CNAME referral record were removed.
595 // In reality this is such a corner case we'll ignore it until someone actually needs it.
597 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
598 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME
" (" PUB_S
") following CNAME referral %d for " PRI_S
,
599 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
),
600 q
->CNAMEReferrals
, RRDisplayString(m
, rr
));
602 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
603 if ((q
->CNAMEReferrals
== 0) && !q
->metrics
.originalQName
)
608 qNameLen
= DomainNameLength(&q
->qname
);
609 if ((qNameLen
> 0) && (qNameLen
<= MAX_DOMAIN_NAME
))
611 qName
= (domainname
*) mDNSPlatformMemAllocate(qNameLen
);
614 mDNSPlatformMemCopy(qName
->c
, q
->qname
.c
, qNameLen
);
615 q
->metrics
.originalQName
= qName
;
619 metrics
= q
->metrics
;
620 mDNSPlatformMemZero(&q
->metrics
, sizeof(q
->metrics
));
622 mDNS_StopQuery_internal(m
, q
); // Stop old query
623 AssignDomainName(&q
->qname
, &rr
->rdata
->u
.name
); // Update qname
624 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
625 // If a unicast query results in a CNAME that points to a .local, we need to re-try
626 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
627 // to try this as unicast query even though it is a .local name
628 if (!mDNSOpaque16IsZero(q
->TargetQID
) && IsLocalDomain(&q
->qname
))
630 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
631 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME
" (" PUB_S
") Record " PRI_S
,
632 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
), RRDisplayString(m
, rr
));
633 q
->IsUnicastDotLocal
= mDNStrue
;
635 mDNS_StartQuery_internal(m
, q
); // start new query
636 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
637 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
638 q
->CNAMEReferrals
= c
;
639 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
640 metrics
.expiredAnswerState
= q
->metrics
.expiredAnswerState
; // We want the newly initialized state for this value
641 metrics
.dnsOverTCPState
= q
->metrics
.dnsOverTCPState
; // We want the newly initialized state for this value
642 q
->metrics
= metrics
;
646 // 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.
647 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
650 // Transplant the old socket into the new question, and copy the query ID across too.
651 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
652 q
->LocalSocket
= sock
;
661 #include <unicode/uidna.h>
663 // #define DEBUG_PUNYCODE 1
665 mDNSlocal mDNSu8
*PunycodeConvert(const mDNSu8
*const src
, mDNSu8
*const dst
, const mDNSu8
*const end
)
667 UErrorCode errorCode
= U_ZERO_ERROR
;
668 UIDNAInfo info
= UIDNA_INFO_INITIALIZER
;
669 UIDNA
*uts46
= uidna_openUTS46(UIDNA_USE_STD3_RULES
|UIDNA_NONTRANSITIONAL_TO_UNICODE
, &errorCode
);
670 int32_t len
= uidna_nameToASCII_UTF8(uts46
, (const char *)src
+1, src
[0], (char *)dst
+1, end
-(dst
+1), &info
, &errorCode
);
673 if (errorCode
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src
, errorCode
);
674 if (info
.errors
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src
, info
.errors
);
675 if (len
> MAX_DOMAIN_LABEL
) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src
, len
);
677 if (errorCode
|| info
.errors
|| len
> MAX_DOMAIN_LABEL
) return mDNSNULL
;
679 return(dst
+ 1 + len
);
682 mDNSlocal mDNSBool
IsHighASCIILabel(const mDNSu8
*d
)
685 for (i
=1; i
<=d
[0]; i
++) if (d
[i
] & 0x80) return mDNStrue
;
689 mDNSlocal
const mDNSu8
*FindLastHighASCIILabel(const domainname
*const d
)
691 const mDNSu8
*ptr
= d
->c
;
692 const mDNSu8
*ans
= mDNSNULL
;
695 const mDNSu8
*const next
= ptr
+ 1 + ptr
[0];
696 if (ptr
[0] > MAX_DOMAIN_LABEL
|| next
>= d
->c
+ MAX_DOMAIN_NAME
) return mDNSNULL
;
697 if (IsHighASCIILabel(ptr
)) ans
= ptr
;
703 mDNSlocal mDNSBool
PerformNextPunycodeConversion(const DNSQuestion
*const q
, domainname
*const newname
)
705 const mDNSu8
*h
= FindLastHighASCIILabel(&q
->qname
);
707 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q
->qname
.c
, DNSTypeName(q
->qtype
), h
);
709 if (!h
) return mDNSfalse
; // There are no high-ascii labels to convert
711 mDNSu8
*const dst
= PunycodeConvert(h
, newname
->c
+ (h
- q
->qname
.c
), newname
->c
+ MAX_DOMAIN_NAME
);
713 return mDNSfalse
; // The label was not convertible to Punycode
716 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
717 const mDNSu8
*const src
= h
+ 1 + h
[0];
718 const mDNSu8 remainder
= DomainNameLength((domainname
*)src
);
719 if (dst
+ remainder
> newname
->c
+ MAX_DOMAIN_NAME
) return mDNSfalse
; // Name too long -- cannot be converted to Punycode
721 mDNSPlatformMemCopy(newname
->c
, q
->qname
.c
, h
- q
->qname
.c
); // Fill in the leading part
722 mDNSPlatformMemCopy(dst
, src
, remainder
); // Fill in the trailing part
724 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q
->qname
.c
, newname
->c
);
732 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
733 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
734 mDNSlocal
void AnswerLocalQuestionWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
736 DNSQuestion
*q
= m
->CurrentQuestion
;
737 mDNSBool followcname
;
741 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m
, rr
));
745 followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
747 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
748 if (!(rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
))
750 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
751 AddRecord
? "Add" : "Rmv", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
755 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
756 if (AddRecord
) rr
->AnsweredLocalQ
= mDNStrue
;
757 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
758 if (q
->QuestionCallback
&& !q
->NoAnswer
)
760 q
->CurrentAnswers
+= AddRecord
? 1 : -1;
761 if (UniqueLocalOnlyRecord(rr
))
763 if (!followcname
|| q
->ReturnIntermed
)
765 // Don't send this packet on the wire as we answered from /etc/hosts
766 q
->ThisQInterval
= 0;
767 q
->LOAddressAnswers
+= AddRecord
? 1 : -1;
768 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
770 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
771 // The callback above could have caused the question to stop. Detect that
772 // using m->CurrentQuestion
773 if (followcname
&& m
->CurrentQuestion
== q
)
774 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
779 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
782 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
785 mDNSlocal
void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*ar
, QC_result AddRecord
)
787 if (m
->CurrentQuestion
)
788 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
789 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
790 m
->CurrentQuestion
= m
->Questions
;
791 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
794 DNSQuestion
*q
= m
->CurrentQuestion
;
796 answered
= AuthRecordAnswersQuestion(ar
, q
);
798 answered
= LocalOnlyRecordAnswersQuestion(ar
, q
);
800 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, AddRecord
); // MUST NOT dereference q again
801 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
802 m
->CurrentQuestion
= q
->next
;
804 m
->CurrentQuestion
= mDNSNULL
;
807 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
808 // delivers the appropriate add/remove events to listening questions:
809 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
810 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
811 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
812 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
813 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
815 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
816 // and by mDNS_Deregister_internal()
818 mDNSlocal
void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*ar
, QC_result AddRecord
)
820 if (m
->CurrentQuestion
)
821 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
822 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
824 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
825 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
828 DNSQuestion
*q
= m
->CurrentQuestion
;
829 // We are called with both LocalOnly/P2P record or a regular AuthRecord
831 answered
= AuthRecordAnswersQuestion(ar
, q
);
833 answered
= LocalOnlyRecordAnswersQuestion(ar
, q
);
835 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, AddRecord
); // MUST NOT dereference q again
836 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
837 m
->CurrentQuestion
= q
->next
;
840 m
->CurrentQuestion
= mDNSNULL
;
842 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
843 if (ar
->ARType
== AuthRecordLocalOnly
|| ar
->ARType
== AuthRecordP2P
)
844 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m
, ar
, AddRecord
);
848 // ***************************************************************************
849 #if COMPILER_LIKES_PRAGMA_MARK
851 #pragma mark - Resource Record Utility Functions
854 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
856 mDNSlocal mDNSBool
ResourceRecordIsValidAnswer(const AuthRecord
*const rr
)
858 if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
) &&
859 ((rr
->Additional1
== mDNSNULL
) || (rr
->Additional1
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)) &&
860 ((rr
->Additional2
== mDNSNULL
) || (rr
->Additional2
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)) &&
861 ((rr
->DependentOn
== mDNSNULL
) || (rr
->DependentOn
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)))
871 mDNSlocal mDNSBool
IsInterfaceValidForAuthRecord(const AuthRecord
*const rr
, const mDNSInterfaceID InterfaceID
)
873 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
875 return mDNSPlatformValidRecordForInterface(rr
, InterfaceID
);
879 return ((rr
->resrec
.InterfaceID
== InterfaceID
) ? mDNStrue
: mDNSfalse
);
883 mDNSlocal mDNSBool
ResourceRecordIsValidInterfaceAnswer(const AuthRecord
*const rr
, const mDNSInterfaceID interfaceID
)
885 return ((IsInterfaceValidForAuthRecord(rr
, interfaceID
) && ResourceRecordIsValidAnswer(rr
)) ? mDNStrue
: mDNSfalse
);
888 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
889 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
891 // Parameters for handling probing conflicts
892 #define kMaxAllowedMCastProbingConflicts 1 // Maximum number of conflicts to allow from mcast messages.
893 #define kProbingConflictPauseDuration mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
895 // See RFC 6762: "8.3 Announcing"
896 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
897 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
898 #define InitialAnnounceCount ((mDNSu8)4)
900 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
901 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
902 // and then if the machine fails to wake, 3 goodbye packets).
903 #define GoodbyeCount ((mDNSu8)3)
904 #define WakeupCount ((mDNSu8)18)
905 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
906 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week
908 // Number of wakeups we send if WakeOnResolve is set in the question
909 #define InitialWakeOnResolveCount ((mDNSu8)3)
911 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
912 // This means that because the announce interval is doubled after sending the first packet, the first
913 // observed on-the-wire inter-packet interval between announcements is actually one second.
914 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
915 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
916 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
917 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
919 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
920 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
921 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
923 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
924 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
925 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
927 // Adjustment factor to avoid race condition (used for unicast cache entries) :
928 // 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.
929 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
930 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
931 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
932 // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
933 // the cached copy at our local caching server will already have expired, so the server will be forced
934 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
936 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
937 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
939 #define MaxUnansweredQueries 4
941 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
942 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
943 // TTL and rdata may differ.
944 // This is used for cache flush management:
945 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
946 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
948 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
950 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
952 mDNSlocal mDNSBool
SameResourceRecordNameClassInterface(const AuthRecord
*const r1
, const AuthRecord
*const r2
)
954 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
955 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
956 if (r1
->resrec
.InterfaceID
&&
957 r2
->resrec
.InterfaceID
&&
958 r1
->resrec
.InterfaceID
!= r2
->resrec
.InterfaceID
) return(mDNSfalse
);
960 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
&&
961 r1
->resrec
.namehash
== r2
->resrec
.namehash
&&
962 SameDomainName(r1
->resrec
.name
, r2
->resrec
.name
));
965 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
966 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
967 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
968 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
969 // so a response of any type should match, even if it is not actually the type the client plans to use.
971 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
972 // and require the rrtypes to match for the rdata to be considered potentially conflicting
973 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
975 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
976 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
977 if (pktrr
->resrec
.InterfaceID
&&
978 authrr
->resrec
.InterfaceID
&&
979 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
980 if (!(authrr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) || authrr
->WakeUp
.HMAC
.l
[0])
981 if (pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
982 if ((authrr
->resrec
.InterfaceID
== mDNSInterface_Any
) &&
983 !mDNSPlatformValidRecordForInterface(authrr
, pktrr
->resrec
.InterfaceID
)) return(mDNSfalse
);
985 pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&&
986 pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&&
987 SameDomainName(pktrr
->resrec
.name
, authrr
->resrec
.name
));
990 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
991 // This is the information that the requester believes to be correct.
992 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
993 // This is the information that we believe to be correct.
994 // We've already determined that we plan to give this answer on this interface
995 // (either the record is non-specific, or it is specific to this interface)
996 // so now we just need to check the name, type, class, rdata and TTL.
997 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
999 // If RR signature is different, or data is different, then don't suppress our answer
1000 if (!IdenticalResourceRecord(&ka
->resrec
, &rr
->resrec
)) return(mDNSfalse
);
1002 // If the requester's indicated TTL is less than half the real TTL,
1003 // we need to give our answer before the requester's copy expires.
1004 // If the requester's indicated TTL is at least half the real TTL,
1005 // then we can suppress our answer this time.
1006 // If the requester's indicated TTL is greater than the TTL we believe,
1007 // then that's okay, and we don't need to do anything about it.
1008 // (If two responders on the network are offering the same information,
1009 // that's okay, and if they are offering the information with different TTLs,
1010 // the one offering the lower TTL should defer to the one offering the higher TTL.)
1011 return (mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
1014 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
1016 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1018 if ((rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
> mDNSPlatformOneSecond
* 10)
1020 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr
->ProbeCount
, (rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
, ARDisplayString(m
, rr
));
1021 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m
->SuppressProbes
, m
->timenow
, m
->SuppressProbes
- m
->timenow
);
1023 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1024 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1025 // Some defensive code:
1026 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1027 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1028 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1029 if (m
->NextScheduledProbe
- m
->timenow
< 0)
1030 m
->NextScheduledProbe
= m
->timenow
;
1032 else if (rr
->AnnounceCount
&& (ResourceRecordIsValidAnswer(rr
) || rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
))
1034 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1035 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1039 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
1041 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1042 rr
->ThisAPInterval
= rr
->AddressProxy
.type
? mDNSPlatformOneSecond
: DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
1044 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1045 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1046 // records that are going to probe, then we delay its first announcement so that it will
1047 // go out synchronized with the first announcement for the other records that *are* probing.
1048 // This is a minor performance tweak that helps keep groups of related records synchronized together.
1049 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1050 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1051 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1052 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
1053 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1057 rr
->ProbingConflictCount
= 0;
1058 // If we have no probe suppression time set, or it is in the past, set it now
1059 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
1061 // To allow us to aggregate probes when a group of services are registered together,
1062 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1063 // This means the common-case behaviour is:
1064 // randomized wait; probe
1065 // 1/4 second wait; probe
1066 // 1/4 second wait; probe
1067 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1068 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
1070 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1071 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
1072 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledProbe
);
1073 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
1074 m
->SuppressProbes
= m
->timenow
;
1076 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1077 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
1078 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledQuery
);
1079 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
1080 m
->SuppressProbes
= m
->timenow
;
1082 // except... don't expect to be able to send before the m->SuppressSending timer fires
1083 if (m
->SuppressSending
&& m
->SuppressProbes
- m
->SuppressSending
< 0)
1084 m
->SuppressProbes
= NonZeroTime(m
->SuppressSending
);
1086 if (m
->SuppressProbes
- m
->timenow
> mDNSPlatformOneSecond
* 8)
1088 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1089 m
->SuppressProbes
- m
->timenow
,
1090 m
->NextScheduledProbe
- m
->timenow
,
1091 m
->NextScheduledQuery
- m
->timenow
,
1093 m
->SuppressSending
- m
->timenow
);
1094 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
1097 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
1099 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1100 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1101 else if ((rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
) && (rr
->resrec
.RecordType
!= kDNSRecordTypeShared
) && m
->SuppressProbes
&& (m
->SuppressProbes
- m
->timenow
>= 0))
1102 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
+ DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
1104 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1106 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1107 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1108 // After three probes one second apart with no answer, we conclude the client is now sleeping
1109 // and we can begin broadcasting our announcements to take over ownership of that IP address.
1110 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1111 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1112 if (rr
->AddressProxy
.type
)
1113 rr
->LastAPTime
= m
->timenow
;
1115 // Set LastMCTime to now, to inhibit multicast responses
1116 // (no need to send additional multicast responses when we're announcing anyway)
1117 rr
->LastMCTime
= m
->timenow
;
1118 rr
->LastMCInterface
= mDNSInterfaceMark
;
1120 SetNextAnnounceProbeTime(m
, rr
);
1123 mDNSlocal
const domainname
*SetUnicastTargetToHostName(mDNS
*const m
, AuthRecord
*rr
)
1125 const domainname
*target
;
1128 rr
->AutoTarget
= Target_AutoHostAndNATMAP
;
1131 target
= GetServiceTarget(m
, rr
);
1132 if (!target
|| target
->c
[0] == 0)
1134 // defer registration until we've got a target
1135 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m
, rr
));
1136 rr
->state
= regState_NoTarget
;
1141 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target
->c
, ARDisplayString(m
,rr
));
1146 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1147 mDNSlocal mDNSBool
AuthRecordIncludesOrIsAWDL(const AuthRecord
*const ar
)
1149 return ((AuthRecordIncludesAWDL(ar
) || mDNSPlatformInterfaceIsAWDL(ar
->resrec
.InterfaceID
)) ? mDNStrue
: mDNSfalse
);
1153 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1154 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1155 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
1157 domainname
*const target
= GetRRDomainNameTarget(&rr
->resrec
);
1158 const domainname
*newname
;
1160 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1161 if (AuthRecordIncludesOrIsAWDL(rr
))
1163 newname
= &m
->RandomizedHostname
;
1168 newname
= &m
->MulticastHostname
;
1170 if (!target
) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr
->resrec
.rrtype
));
1172 if (!(rr
->ForceMCast
|| rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
|| IsLocalDomain(&rr
->namestorage
)))
1174 const domainname
*const n
= SetUnicastTargetToHostName(m
, rr
);
1176 else { if (target
) target
->c
[0] = 0; SetNewRData(&rr
->resrec
, mDNSNULL
, 0); return; }
1179 if (target
&& SameDomainName(target
, newname
))
1180 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
->c
, target
->c
);
1182 if (target
&& !SameDomainName(target
, newname
))
1184 AssignDomainName(target
, newname
);
1185 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
1187 // If we're in the middle of probing this record, we need to start again,
1188 // because changing its rdata may change the outcome of the tie-breaker.
1189 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1190 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1192 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1193 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1194 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1195 if (rr
->RequireGoodbye
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
1196 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1197 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1199 rr
->AnnounceCount
= InitialAnnounceCount
;
1200 rr
->RequireGoodbye
= mDNSfalse
;
1201 rr
->ProbeRestartCount
= 0;
1202 InitializeLastAPTime(m
, rr
);
1206 mDNSlocal
void AcknowledgeRecord(mDNS
*const m
, AuthRecord
*const rr
)
1208 if (rr
->RecordCallback
)
1210 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1211 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1212 rr
->Acknowledged
= mDNStrue
;
1213 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1214 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
1215 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1219 mDNSexport
void ActivateUnicastRegistration(mDNS
*const m
, AuthRecord
*const rr
)
1221 // Make sure that we don't activate the SRV record and associated service records, if it is in
1222 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1223 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1224 // the target becomes available, the records will be reregistered.
1225 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
1227 AuthRecord
*srvRR
= mDNSNULL
;
1228 if (rr
->resrec
.rrtype
== kDNSType_PTR
)
1229 srvRR
= rr
->Additional1
;
1230 else if (rr
->resrec
.rrtype
== kDNSType_TXT
)
1231 srvRR
= rr
->DependentOn
;
1234 if (srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
1236 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
1240 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1241 ARDisplayString(m
, srvRR
), srvRR
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1242 rr
->state
= srvRR
->state
;
1247 if (rr
->state
== regState_NoTarget
)
1249 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m
, rr
));
1252 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1253 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1254 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1255 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1256 // 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.
1257 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1259 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m
, rr
), rr
->state
);
1260 rr
->state
= regState_DeregPending
;
1264 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m
, rr
), rr
->state
);
1265 rr
->state
= regState_Pending
;
1267 rr
->ProbingConflictCount
= 0;
1268 rr
->LastConflictPktNum
= 0;
1269 rr
->ProbeRestartCount
= 0;
1271 rr
->AnnounceCount
= 0;
1272 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1273 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1274 rr
->expire
= 0; // Forget about all the leases, start fresh
1275 rr
->uselease
= mDNStrue
;
1276 rr
->updateid
= zeroID
;
1277 rr
->SRVChanged
= mDNSfalse
;
1278 rr
->updateError
= mStatus_NoError
;
1279 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1280 // The records might already be registered with the server and hence could have NAT state.
1281 if (rr
->NATinfo
.clientContext
)
1283 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1284 rr
->NATinfo
.clientContext
= mDNSNULL
;
1286 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1287 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1288 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1289 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1292 // Two records qualify to be local duplicates if:
1293 // (a) the RecordTypes are the same, or
1294 // (b) one is Unique and the other Verified
1295 // (c) either is in the process of deregistering
1296 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1297 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1298 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1300 #define RecordIsLocalDuplicate(A,B) \
1301 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1303 mDNSlocal AuthRecord
*CheckAuthIdenticalRecord(AuthHash
*r
, AuthRecord
*rr
)
1308 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1309 if (!a
) return mDNSNULL
;
1313 if (!RecordIsLocalDuplicate(rp
, rr
))
1317 if (rp
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1319 rp
->AnnounceCount
= 0;
1328 mDNSlocal mDNSBool
CheckAuthRecordConflict(AuthHash
*r
, AuthRecord
*rr
)
1331 const AuthRecord
*rp
;
1333 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1334 if (!a
) return mDNSfalse
;
1338 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
1339 const AuthRecord
*s2
= rp
->RRSet
? rp
->RRSet
: rp
;
1340 if (s1
!= s2
&& SameResourceRecordSignature(rp
, rr
) && !IdenticalSameNameRecord(&rp
->resrec
, &rr
->resrec
))
1348 // checks to see if "rr" is already present
1349 mDNSlocal AuthRecord
*CheckAuthSameRecord(AuthHash
*r
, AuthRecord
*rr
)
1354 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1355 if (!a
) return mDNSNULL
;
1369 mDNSlocal
void DecrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1371 if (RRLocalOnly(rr
))
1373 // A sanity check, this should be prevented in calling code.
1374 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1378 if (!AuthRecord_uDNS(rr
) && (rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHost
))
1380 NetworkInterfaceInfo
*intf
;
1381 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1382 DeadvertiseFlags flags
= 0; // DeadvertiseFlags for non-AWDL interfaces.
1383 DeadvertiseFlags flagsAWDL
= 0; // DeadvertiseFlags for AWDL interfaces.
1384 if (AuthRecordIncludesOrIsAWDL(rr
))
1386 if (AuthRecordIncludesAWDL(rr
))
1388 m
->AutoTargetAWDLIncludedCount
--;
1389 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1390 "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S
,
1391 m
->AutoTargetAWDLIncludedCount
, ARDisplayString(m
, rr
));
1392 if (m
->AutoTargetAWDLIncludedCount
== 0)
1394 flags
|= kDeadvertiseFlag_RandHostname
;
1395 if (m
->AutoTargetAWDLOnlyCount
== 0) flagsAWDL
|= kDeadvertiseFlag_RandHostname
;
1400 m
->AutoTargetAWDLOnlyCount
--;
1401 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1402 "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S
,
1403 m
->AutoTargetAWDLOnlyCount
, ARDisplayString(m
, rr
));
1404 if ((m
->AutoTargetAWDLIncludedCount
== 0) && (m
->AutoTargetAWDLOnlyCount
== 0))
1406 flagsAWDL
|= kDeadvertiseFlag_RandHostname
;
1409 if (flags
|| flagsAWDL
)
1411 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1413 if (!intf
->Advertise
) continue;
1414 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
))
1416 if (flagsAWDL
) DeadvertiseInterface(m
, intf
, flagsAWDL
);
1420 if (flags
) DeadvertiseInterface(m
, intf
, flags
);
1424 if ((m
->AutoTargetAWDLIncludedCount
== 0) && (m
->AutoTargetAWDLOnlyCount
== 0))
1426 GetRandomUUIDLocalHostname(&m
->RandomizedHostname
);
1432 m
->AutoTargetServices
--;
1433 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1434 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S
,
1435 m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1436 if (m
->AutoTargetServices
== 0)
1438 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1440 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
, kDeadvertiseFlag_NormalHostname
);
1446 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1447 if (!AuthRecord_uDNS(rr
))
1449 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1450 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
1451 m
->NumAllInterfaceRecords
--;
1452 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1453 "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S
,
1454 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1459 mDNSlocal
void AdvertiseNecessaryInterfaceRecords(mDNS
*const m
)
1461 NetworkInterfaceInfo
*intf
;
1462 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1464 if (intf
->Advertise
) AdvertiseInterfaceIfNeeded(m
, intf
);
1468 mDNSlocal
void IncrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1470 mDNSBool enablingBonjour
= mDNSfalse
;
1472 if (RRLocalOnly(rr
))
1474 // A sanity check, this should be prevented in calling code.
1475 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1479 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1480 if (!AuthRecord_uDNS(rr
))
1482 m
->NumAllInterfaceRecords
++;
1483 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1484 "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S
,
1485 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1486 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1488 m
->NextBonjourDisableTime
= 0;
1489 if (m
->BonjourEnabled
== 0)
1491 // Enable Bonjour immediately by scheduling network changed processing where
1492 // we will join the multicast group on each active interface.
1493 m
->BonjourEnabled
= 1;
1494 enablingBonjour
= mDNStrue
;
1495 m
->NetworkChanged
= m
->timenow
;
1501 if (!AuthRecord_uDNS(rr
) && (rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHost
))
1503 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1504 if (AuthRecordIncludesAWDL(rr
))
1506 m
->AutoTargetAWDLIncludedCount
++;
1507 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1508 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S
,
1509 m
->AutoTargetAWDLIncludedCount
, ARDisplayString(m
, rr
));
1511 else if (mDNSPlatformInterfaceIsAWDL(rr
->resrec
.InterfaceID
))
1513 m
->AutoTargetAWDLOnlyCount
++;
1514 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1515 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S
,
1516 m
->AutoTargetAWDLOnlyCount
, ARDisplayString(m
, rr
));
1521 m
->AutoTargetServices
++;
1522 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1523 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S
,
1524 m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1526 // If this is the first advertised service and we did not just enable Bonjour above, then
1527 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1528 // be advertised during the network changed processing scheduled above, so no need
1530 if (!enablingBonjour
) AdvertiseNecessaryInterfaceRecords(m
);
1534 mDNSlocal
void getKeepaliveRaddr(mDNS
*const m
, AuthRecord
*rr
, mDNSAddr
*raddr
)
1536 mDNSAddr laddr
= zeroAddr
;
1537 mDNSEthAddr eth
= zeroEthAddr
;
1538 mDNSIPPort lport
= zeroIPPort
;
1539 mDNSIPPort rport
= zeroIPPort
;
1540 mDNSu32 timeout
= 0;
1545 if (mDNS_KeepaliveRecord(&rr
->resrec
))
1547 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
1548 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
1550 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, raddr
, rport
.NotAnInteger
);
1556 // Exported so uDNS.c can call this
1557 mDNSexport mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
1559 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
1561 AuthRecord
**p
= &m
->ResourceRecords
;
1562 AuthRecord
**d
= &m
->DuplicateRecords
;
1564 if ((mDNSs32
)rr
->resrec
.rroriginalttl
<= 0)
1565 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr
->resrec
.rroriginalttl
, ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1567 if (!rr
->resrec
.RecordType
)
1568 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1570 if (m
->ShutdownTime
)
1571 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m
, rr
)); return(mStatus_ServiceNotRunning
); }
1573 if (m
->DivertMulticastAdvertisements
&& !AuthRecord_uDNS(rr
))
1575 mDNSInterfaceID previousID
= rr
->resrec
.InterfaceID
;
1576 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1578 rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
1579 rr
->ARType
= AuthRecordLocalOnly
;
1581 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
1583 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1584 if (intf
&& !intf
->Advertise
) { rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
; rr
->ARType
= AuthRecordLocalOnly
; }
1586 if (rr
->resrec
.InterfaceID
!= previousID
)
1587 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m
, rr
));
1590 if (RRLocalOnly(rr
))
1592 if (CheckAuthSameRecord(&m
->rrauth
, rr
))
1594 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1595 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1596 return(mStatus_AlreadyRegistered
);
1601 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1604 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1605 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1606 return(mStatus_AlreadyRegistered
);
1610 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
1613 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1614 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1615 return(mStatus_AlreadyRegistered
);
1618 if (rr
->DependentOn
)
1620 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1621 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1622 else if (rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
)
1624 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1625 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1626 return(mStatus_Invalid
);
1628 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
)))
1630 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1631 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
1632 return(mStatus_Invalid
);
1636 rr
->next
= mDNSNULL
;
1638 // Field Group 1: The actual information pertaining to this resource record
1639 // Set up by client prior to call
1641 // Field Group 2: Persistent metadata for Authoritative Records
1642 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1643 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1644 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1645 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1646 // rr->Callback = already set in mDNS_SetupResourceRecord
1647 // rr->Context = already set in mDNS_SetupResourceRecord
1648 // rr->RecordType = already set in mDNS_SetupResourceRecord
1649 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1650 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1651 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1652 if (rr
->AutoTarget
&& target
) target
->c
[0] = 0;
1654 // Field Group 3: Transient state for Authoritative Records
1655 rr
->Acknowledged
= mDNSfalse
;
1656 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1657 rr
->ProbeRestartCount
= 0;
1658 rr
->AnnounceCount
= InitialAnnounceCount
;
1659 rr
->RequireGoodbye
= mDNSfalse
;
1660 rr
->AnsweredLocalQ
= mDNSfalse
;
1661 rr
->IncludeInProbe
= mDNSfalse
;
1662 rr
->ImmedUnicast
= mDNSfalse
;
1663 rr
->SendNSECNow
= mDNSNULL
;
1664 rr
->ImmedAnswer
= mDNSNULL
;
1665 rr
->ImmedAdditional
= mDNSNULL
;
1666 rr
->SendRNow
= mDNSNULL
;
1667 rr
->v4Requester
= zerov4Addr
;
1668 rr
->v6Requester
= zerov6Addr
;
1669 rr
->NextResponse
= mDNSNULL
;
1670 rr
->NR_AnswerTo
= mDNSNULL
;
1671 rr
->NR_AdditionalTo
= mDNSNULL
;
1672 if (!rr
->AutoTarget
) InitializeLastAPTime(m
, rr
);
1673 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1674 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1675 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1676 rr
->NewRData
= mDNSNULL
;
1677 rr
->newrdlength
= 0;
1678 rr
->UpdateCallback
= mDNSNULL
;
1679 rr
->UpdateCredits
= kMaxUpdateCredits
;
1680 rr
->NextUpdateCredit
= 0;
1681 rr
->UpdateBlocked
= 0;
1683 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1684 if (rr
->WakeUp
.HMAC
.l
[0] && !rr
->AddressProxy
.type
) rr
->AnnounceCount
= 2;
1686 // Field Group 4: Transient uDNS state for Authoritative Records
1687 rr
->state
= regState_Zero
;
1691 rr
->updateid
= zeroID
;
1692 rr
->updateIntID
= zeroOpaque64
;
1693 rr
->zone
= rr
->resrec
.name
;
1698 rr
->InFlightRData
= 0;
1699 rr
->InFlightRDLen
= 0;
1700 rr
->QueuedRData
= 0;
1701 rr
->QueuedRDLen
= 0;
1702 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1703 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1704 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1705 // times with different values if the external NAT port changes during the lifetime of the service registration.
1706 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1708 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1709 // rr->resrec.name->c = MUST be set by client
1710 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1711 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1712 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1713 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1715 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1716 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1717 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1718 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rr
->resrec
.rdlength
== 0) { rr
->resrec
.rdlength
= 1; rr
->resrec
.rdata
->u
.txt
.c
[0] = 0; }
1722 SetTargetToHostName(m
, rr
); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1723 #ifndef UNICAST_DISABLED
1724 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1725 // 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.
1726 if (rr
->state
== regState_NoTarget
)
1728 // Initialize the target so that we don't crash while logging etc.
1729 domainname
*tar
= GetRRDomainNameTarget(&rr
->resrec
);
1730 if (tar
) tar
->c
[0] = 0;
1731 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m
, rr
));
1737 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
1738 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
1741 if (!ValidateDomainName(rr
->resrec
.name
))
1742 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1744 // Don't do this until *after* we've set rr->resrec.rdlength
1745 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
1746 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1748 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
1749 rr
->resrec
.rdatahash
= target
? DomainNameHashValue(target
) : RDataHashValue(&rr
->resrec
);
1751 if (RRLocalOnly(rr
))
1753 // If this is supposed to be unique, make sure we don't have any name conflicts.
1754 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1755 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1756 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1757 // Hence, just bail out.
1758 // This comment is doesn’t make any sense. -- SC
1759 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1761 if (CheckAuthRecordConflict(&m
->rrauth
, rr
))
1763 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m
, rr
), rr
, rr
->resrec
.InterfaceID
);
1764 return mStatus_NameConflict
;
1769 // For uDNS records, we don't support duplicate checks at this time.
1770 #ifndef UNICAST_DISABLED
1771 if (AuthRecord_uDNS(rr
))
1773 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1774 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1775 // 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.
1776 while (*p
) p
=&(*p
)->next
;
1778 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1780 rr
->ProbeRestartCount
= 0;
1781 rr
->AnnounceCount
= 0;
1782 if (rr
->state
!= regState_NoTarget
) ActivateUnicastRegistration(m
, rr
);
1783 return(mStatus_NoError
); // <--- Note: For unicast records, code currently bails out at this point
1787 // Now that we've finished building our new record, make sure it's not identical to one we already have
1788 if (RRLocalOnly(rr
))
1791 rr
->ProbeRestartCount
= 0;
1792 rr
->AnnounceCount
= 0;
1793 r
= CheckAuthIdenticalRecord(&m
->rrauth
, rr
);
1797 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1798 if (RecordIsLocalDuplicate(r
, rr
))
1800 if (r
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) r
->AnnounceCount
= 0;
1807 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m
,rr
));
1809 // If the previous copy of this record is already verified unique,
1810 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1811 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1812 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1813 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
1818 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m
,rr
));
1819 if (RRLocalOnly(rr
))
1822 ag
= InsertAuthRecord(m
, &m
->rrauth
, rr
);
1823 if (ag
&& !ag
->NewLocalOnlyRecords
)
1825 m
->NewLocalOnlyRecords
= mDNStrue
;
1826 ag
->NewLocalOnlyRecords
= rr
;
1828 // No probing for LocalOnly records; acknowledge them right away
1829 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1830 AcknowledgeRecord(m
, rr
);
1831 return(mStatus_NoError
);
1835 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1840 if (!AuthRecord_uDNS(rr
)) // This check is superfluous, given that for unicast records we (currently) bail out above
1842 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1843 IncrementAutoTargetServices(m
, rr
);
1845 // For records that are not going to probe, acknowledge them right away
1846 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
1847 AcknowledgeRecord(m
, rr
);
1849 // Adding a record may affect whether or not we should sleep
1850 mDNS_UpdateAllowSleep(m
);
1853 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1854 // This is used by the in-NIC proxy to send the keepalive packets.
1855 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
1858 // Set the record type to known unique to prevent probing keep alive records.
1859 // Also make sure we do not announce the keepalive records.
1860 rr
->resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
1861 rr
->AnnounceCount
= 0;
1862 getKeepaliveRaddr(m
, rr
, &raddr
);
1863 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1864 // asynchronous task to update the resource record
1865 mDNSPlatformGetRemoteMacAddr(&raddr
);
1868 return(mStatus_NoError
);
1871 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
1873 m
->ProbeFailTime
= m
->timenow
;
1874 m
->NumFailedProbes
++;
1875 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1876 // If a bunch of hosts have all been configured with the same name, then they'll all
1877 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1878 // up to name-10. After that they'll start adding random increments in the range 1-100,
1879 // so they're more likely to branch out in the available namespace and settle on a set of
1880 // unique names quickly. If after five more tries the host is still conflicting, then we
1881 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1882 if (m
->NumFailedProbes
>= 15)
1884 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
1885 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1886 m
->NumFailedProbes
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1890 mDNSlocal
void CompleteRDataUpdate(mDNS
*const m
, AuthRecord
*const rr
)
1892 RData
*OldRData
= rr
->resrec
.rdata
;
1893 mDNSu16 OldRDLen
= rr
->resrec
.rdlength
;
1894 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
1895 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
1896 if (rr
->UpdateCallback
)
1897 rr
->UpdateCallback(m
, rr
, OldRData
, OldRDLen
); // ... and let the client know
1900 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1901 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1902 // Exported so uDNS.c can call this
1903 mDNSexport mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
1906 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
1907 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
1908 mDNSBool dupList
= mDNSfalse
;
1910 if (RRLocalOnly(rr
))
1915 a
= AuthGroupForRecord(&m
->rrauth
, &rr
->resrec
);
1916 if (!a
) return mDNSfalse
;
1918 while (*rp
&& *rp
!= rr
) rp
=&(*rp
)->next
;
1923 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1928 // We found our record on the main list. See if there are any duplicates that need special handling.
1929 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
1931 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1932 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1933 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
) if (RecordIsLocalDuplicate(r2
, rr
)) r2
->ProbeCount
= 0xFF;
1937 // Before we delete the record (and potentially send a goodbye packet)
1938 // first see if we have a record on the duplicate list ready to take over from it.
1939 AuthRecord
**d
= &m
->DuplicateRecords
;
1940 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
1943 AuthRecord
*dup
= *d
;
1944 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1945 dup
, rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1946 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
1947 if (RRLocalOnly(rr
))
1949 dup
->next
= mDNSNULL
;
1950 if (!InsertAuthRecord(m
, &m
->rrauth
, dup
)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m
, dup
));
1954 dup
->next
= rr
->next
; // And then...
1955 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
1957 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
1958 dup
->ProbeCount
= rr
->ProbeCount
;
1959 dup
->ProbeRestartCount
= rr
->ProbeRestartCount
;
1960 dup
->AnnounceCount
= rr
->AnnounceCount
;
1961 dup
->RequireGoodbye
= rr
->RequireGoodbye
;
1962 dup
->AnsweredLocalQ
= rr
->AnsweredLocalQ
;
1963 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
1964 dup
->ImmedUnicast
= rr
->ImmedUnicast
;
1965 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
1966 dup
->v4Requester
= rr
->v4Requester
;
1967 dup
->v6Requester
= rr
->v6Requester
;
1968 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
1969 dup
->LastAPTime
= rr
->LastAPTime
;
1970 dup
->LastMCTime
= rr
->LastMCTime
;
1971 dup
->LastMCInterface
= rr
->LastMCInterface
;
1972 dup
->Private
= rr
->Private
;
1973 dup
->state
= rr
->state
;
1974 rr
->RequireGoodbye
= mDNSfalse
;
1975 rr
->AnsweredLocalQ
= mDNSfalse
;
1981 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1982 p
= &m
->DuplicateRecords
;
1983 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1984 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1987 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1988 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1989 // also that have been marked above in this function. In that case, we come here and if we don't
1990 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1991 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1993 rr
->WakeUp
.HMAC
= zeroEthAddr
;
1994 rr
->RequireGoodbye
= mDNSfalse
;
1995 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
1998 if (*p
) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1999 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2004 // No need to log an error message if we already know this is a potentially repeated deregistration
2005 if (drt
!= mDNS_Dereg_repeat
)
2006 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr
, ARDisplayString(m
,rr
));
2007 return(mStatus_BadReferenceErr
);
2010 // If this is a shared record and we've announced it at least once,
2011 // we need to retract that announcement before we delete the record
2013 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2014 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2015 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2016 // mechanism to cope with the client callback modifying the question list while that's happening.
2017 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2018 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2019 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2020 // records, thereby invoking yet more callbacks, without limit.
2021 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2022 // actual goodbye packets.
2024 #ifndef UNICAST_DISABLED
2025 if (AuthRecord_uDNS(rr
))
2027 if (rr
->RequireGoodbye
)
2029 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2030 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2031 m
->LocalRemoveEvents
= mDNStrue
;
2032 uDNS_DeregisterRecord(m
, rr
);
2033 // At this point unconditionally we bail out
2034 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2035 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2036 // process and will complete asynchronously. Either way we don't need to do anything more here.
2037 return(mStatus_NoError
);
2039 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2040 // from the server. In that case, if the records have been part of a group update, clear the
2042 rr
->updateid
= zeroID
;
2044 // We defer cleaning up NAT state only after sending goodbyes. This is important because
2045 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2046 // This happens today when we turn on/off interface where we get multiple network transitions
2047 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2048 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2049 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2050 // NAT state here takes care of the case where we did not send goodbyes at all.
2051 if (rr
->NATinfo
.clientContext
)
2053 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
2054 rr
->NATinfo
.clientContext
= mDNSNULL
;
2056 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
2057 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2059 #endif // UNICAST_DISABLED
2061 if (RecordType
== kDNSRecordTypeUnregistered
)
2062 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m
, rr
));
2063 else if (RecordType
== kDNSRecordTypeDeregistering
)
2065 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m
, rr
));
2066 return(mStatus_BadReferenceErr
);
2069 if (rr
->WakeUp
.HMAC
.l
[0] ||
2070 (((RecordType
== kDNSRecordTypeShared
) || (rr
->ARType
== AuthRecordLocalOnly
)) &&
2071 (rr
->RequireGoodbye
|| rr
->AnsweredLocalQ
)))
2073 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m
, rr
));
2074 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2075 rr
->resrec
.rroriginalttl
= 0;
2076 rr
->AnnounceCount
= rr
->WakeUp
.HMAC
.l
[0] ? WakeupCount
: (drt
== mDNS_Dereg_rapid
) ? 1 : GoodbyeCount
;
2077 rr
->ThisAPInterval
= mDNSPlatformOneSecond
* 2;
2078 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
2079 m
->LocalRemoveEvents
= mDNStrue
;
2080 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
2081 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
2085 if (!dupList
&& RRLocalOnly(rr
))
2087 AuthGroup
*ag
= RemoveAuthRecord(m
, &m
->rrauth
, rr
);
2088 if (ag
->NewLocalOnlyRecords
== rr
) ag
->NewLocalOnlyRecords
= rr
->next
;
2092 *p
= rr
->next
; // Cut this record from the list
2093 if (m
->NewLocalRecords
== rr
) m
->NewLocalRecords
= rr
->next
;
2094 DecrementAutoTargetServices(m
, rr
);
2096 // If someone is about to look at this, bump the pointer forward
2097 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
2098 rr
->next
= mDNSNULL
;
2100 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m
, rr
));
2101 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
2103 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
2104 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2105 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2107 // If we have an update queued up which never executed, give the client a chance to free that memory
2108 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
2111 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2112 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2113 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2114 // so any attempt to touch rr after this is likely to lead to a crash.
2115 if (drt
!= mDNS_Dereg_conflict
)
2117 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2118 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m
, rr
));
2119 if (rr
->RecordCallback
)
2120 rr
->RecordCallback(m
, rr
, mStatus_MemFree
); // MUST NOT touch rr after this
2121 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2125 RecordProbeFailure(m
, rr
);
2126 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2127 if (rr
->RecordCallback
)
2128 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
); // MUST NOT touch rr after this
2129 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2130 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2131 // Note that with all the client callbacks going on, by the time we get here all the
2132 // records we marked may have been explicitly deregistered by the client anyway.
2133 r2
= m
->DuplicateRecords
;
2136 if (r2
->ProbeCount
!= 0xFF)
2142 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2143 // See if this record was also registered with any D2D plugins.
2144 D2D_stop_advertising_record(r2
);
2146 mDNS_Deregister_internal(m
, r2
, mDNS_Dereg_conflict
);
2147 // As this is a duplicate record, it will be unlinked from the list
2149 r2
= m
->DuplicateRecords
;
2154 mDNS_UpdateAllowSleep(m
);
2155 return(mStatus_NoError
);
2158 // ***************************************************************************
2159 #if COMPILER_LIKES_PRAGMA_MARK
2161 #pragma mark - Packet Sending Functions
2164 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
2166 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
2169 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2170 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2171 // The referenced record will definitely be acceptable (by recursive application of this rule)
2172 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
2173 rr
->NR_AdditionalTo
= add
;
2174 *nrpp
= &rr
->NextResponse
;
2176 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2179 mDNSlocal
void AddRRSetAdditionalsToResponseList(mDNS
*const m
, AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*additional
, const mDNSInterfaceID InterfaceID
)
2182 if (additional
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2184 for (rr2
= m
->ResourceRecords
; rr2
; rr2
= rr2
->next
)
2186 if ((rr2
->resrec
.namehash
== additional
->resrec
.namehash
) &&
2187 (rr2
->resrec
.rrtype
== additional
->resrec
.rrtype
) &&
2188 (rr2
!= additional
) &&
2189 (rr2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) &&
2190 (rr2
->resrec
.rrclass
== additional
->resrec
.rrclass
) &&
2191 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) &&
2192 SameDomainName(rr2
->resrec
.name
, additional
->resrec
.name
))
2194 AddRecordToResponseList(nrpp
, rr2
, rr
);
2200 mDNSlocal
void AddAdditionalsToResponseList(mDNS
*const m
, AuthRecord
*ResponseRecords
, AuthRecord
***nrpp
, const mDNSInterfaceID InterfaceID
)
2202 AuthRecord
*rr
, *rr2
;
2203 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
2205 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2206 // later in the "for" loop, and we will follow further "additional" links then.)
2207 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
2209 AddRecordToResponseList(nrpp
, rr
->Additional1
, rr
);
2210 AddRRSetAdditionalsToResponseList(m
, nrpp
, rr
, rr
->Additional1
, InterfaceID
);
2213 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
2215 AddRecordToResponseList(nrpp
, rr
->Additional2
, rr
);
2216 AddRRSetAdditionalsToResponseList(m
, nrpp
, rr
, rr
->Additional2
, InterfaceID
);
2219 // For SRV records, automatically add the Address record(s) for the target host
2220 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
2222 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
2223 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2224 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
2225 rr
->resrec
.rdatahash
== rr2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2226 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, rr2
->resrec
.name
))
2227 AddRecordToResponseList(nrpp
, rr2
, rr
);
2229 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
)) // For A or AAAA, put counterpart as additional
2231 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
2232 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2233 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
2234 rr
->resrec
.namehash
== rr2
->resrec
.namehash
&& // ... and have the same name
2235 SameDomainName(rr
->resrec
.name
, rr2
->resrec
.name
))
2236 AddRecordToResponseList(nrpp
, rr2
, rr
);
2238 else if (rr
->resrec
.rrtype
== kDNSType_PTR
) // For service PTR, see if we want to add DeviceInfo record
2240 if (ResourceRecordIsValidInterfaceAnswer(&m
->DeviceInfo
, InterfaceID
) &&
2241 SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2242 AddRecordToResponseList(nrpp
, &m
->DeviceInfo
, rr
);
2247 mDNSlocal
void SendDelayedUnicastResponse(mDNS
*const m
, const mDNSAddr
*const dest
, const mDNSInterfaceID InterfaceID
)
2250 AuthRecord
*ResponseRecords
= mDNSNULL
;
2251 AuthRecord
**nrp
= &ResponseRecords
;
2252 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
2254 // Make a list of all our records that need to be unicast to this destination
2255 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2257 // If we find we can no longer unicast this answer, clear ImmedUnicast
2258 if (rr
->ImmedAnswer
== mDNSInterfaceMark
||
2259 mDNSSameIPv4Address(rr
->v4Requester
, onesIPv4Addr
) ||
2260 mDNSSameIPv6Address(rr
->v6Requester
, onesIPv6Addr
) )
2261 rr
->ImmedUnicast
= mDNSfalse
;
2263 if (rr
->ImmedUnicast
&& rr
->ImmedAnswer
== InterfaceID
)
2265 if ((dest
->type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->v4Requester
, dest
->ip
.v4
)) ||
2266 (dest
->type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->v6Requester
, dest
->ip
.v6
)))
2268 rr
->ImmedAnswer
= mDNSNULL
; // Clear the state fields
2269 rr
->ImmedUnicast
= mDNSfalse
;
2270 rr
->v4Requester
= zerov4Addr
;
2271 rr
->v6Requester
= zerov6Addr
;
2273 // Only sent records registered for P2P over P2P interfaces
2274 if (intf
&& !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
))
2279 if (rr
->NextResponse
== mDNSNULL
&& nrp
!= &rr
->NextResponse
) // rr->NR_AnswerTo
2281 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
2283 nrp
= &rr
->NextResponse
;
2289 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
2291 while (ResponseRecords
)
2293 mDNSu8
*responseptr
= m
->omsg
.data
;
2295 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2297 // Put answers in the packet
2298 while (ResponseRecords
&& ResponseRecords
->NR_AnswerTo
)
2300 rr
= ResponseRecords
;
2301 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2302 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2304 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
);
2306 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2307 if (!newptr
&& m
->omsg
.h
.numAnswers
)
2309 break; // If packet full, send it now
2311 if (newptr
) responseptr
= newptr
;
2312 ResponseRecords
= rr
->NextResponse
;
2313 rr
->NextResponse
= mDNSNULL
;
2314 rr
->NR_AnswerTo
= mDNSNULL
;
2315 rr
->NR_AdditionalTo
= mDNSNULL
;
2316 rr
->RequireGoodbye
= mDNStrue
;
2319 // Add additionals, if there's space
2320 while (ResponseRecords
&& !ResponseRecords
->NR_AnswerTo
)
2322 rr
= ResponseRecords
;
2323 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2324 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2325 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2326 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2328 if (newptr
) responseptr
= newptr
;
2329 if (newptr
&& m
->omsg
.h
.numAnswers
) rr
->RequireGoodbye
= mDNStrue
;
2330 else if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
->ImmedAnswer
= mDNSInterfaceMark
;
2331 ResponseRecords
= rr
->NextResponse
;
2332 rr
->NextResponse
= mDNSNULL
;
2333 rr
->NR_AnswerTo
= mDNSNULL
;
2334 rr
->NR_AdditionalTo
= mDNSNULL
;
2337 if (m
->omsg
.h
.numAnswers
)
2338 mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, InterfaceID
, mDNSNULL
, mDNSNULL
, dest
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
2342 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2343 // and the client's mStatus_MemFree callback will have been invoked
2344 mDNSexport
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
2346 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m
, rr
));
2347 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2348 // it should go ahead and immediately dispose of this registration
2349 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
2350 rr
->RequireGoodbye
= mDNSfalse
;
2351 rr
->WakeUp
.HMAC
= zeroEthAddr
;
2352 if (rr
->AnsweredLocalQ
) { AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_rmv
); rr
->AnsweredLocalQ
= mDNSfalse
; }
2353 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
); // Don't touch rr after this
2356 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2357 // any deregistering records that remain in the m->ResourceRecords list.
2358 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2359 // which may change the record list and/or question list.
2360 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2361 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
2363 if (m
->CurrentRecord
)
2364 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2365 m
->CurrentRecord
= m
->ResourceRecords
;
2367 while (m
->CurrentRecord
)
2369 AuthRecord
*rr
= m
->CurrentRecord
;
2370 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2371 CompleteDeregistration(m
, rr
); // Don't touch rr after this
2373 m
->CurrentRecord
= rr
->next
;
2377 mDNSlocal mStatus
GetLabelDecimalValue(const mDNSu8
*const src
, mDNSu8
*dst
)
2380 if (src
[0] < 1 || src
[0] > 3) return(mStatus_Invalid
);
2381 for (i
=1; i
<=src
[0]; i
++)
2383 if (src
[i
] < '0' || src
[i
] > '9') return(mStatus_Invalid
);
2384 val
= val
* 10 + src
[i
] - '0';
2386 if (val
> 255) return(mStatus_Invalid
);
2388 return(mStatus_NoError
);
2391 mDNSlocal mStatus
GetIPv4FromName(mDNSAddr
*const a
, const domainname
*const name
)
2393 int skip
= CountLabels(name
) - 6;
2394 if (skip
< 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2395 if (GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+3)->c
, &a
->ip
.v4
.b
[0]) ||
2396 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+2)->c
, &a
->ip
.v4
.b
[1]) ||
2397 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+1)->c
, &a
->ip
.v4
.b
[2]) ||
2398 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+0)->c
, &a
->ip
.v4
.b
[3])) return mStatus_Invalid
;
2399 a
->type
= mDNSAddrType_IPv4
;
2400 return(mStatus_NoError
);
2403 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2404 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2405 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2407 mDNSlocal mStatus
GetIPv6FromName(mDNSAddr
*const a
, const domainname
*const name
)
2410 const domainname
*n
;
2412 int skip
= CountLabels(name
) - 34;
2413 if (skip
< 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2415 n
= SkipLeadingLabels(name
, skip
);
2416 for (i
=0; i
<16; i
++)
2418 if (n
->c
[0] != 1) return mStatus_Invalid
;
2419 l
= HexVal(n
->c
[1]);
2420 n
= (const domainname
*)(n
->c
+ 2);
2422 if (n
->c
[0] != 1) return mStatus_Invalid
;
2423 h
= HexVal(n
->c
[1]);
2424 n
= (const domainname
*)(n
->c
+ 2);
2426 if (l
<0 || h
<0) return mStatus_Invalid
;
2427 a
->ip
.v6
.b
[15-i
] = (mDNSu8
)((h
<< 4) | l
);
2430 a
->type
= mDNSAddrType_IPv6
;
2431 return(mStatus_NoError
);
2434 mDNSlocal mDNSs32
ReverseMapDomainType(const domainname
*const name
)
2436 int skip
= CountLabels(name
) - 2;
2439 const domainname
*suffix
= SkipLeadingLabels(name
, skip
);
2440 if (SameDomainName(suffix
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4
;
2441 if (SameDomainName(suffix
, (const domainname
*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6
;
2443 return(mDNSAddrType_None
);
2446 mDNSlocal
void SendARP(mDNS
*const m
, const mDNSu8 op
, const AuthRecord
*const rr
,
2447 const mDNSv4Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2450 mDNSu8
*ptr
= m
->omsg
.data
;
2451 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2452 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2454 // 0x00 Destination address
2455 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2457 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2458 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
2460 // 0x0C ARP Ethertype (0x0806)
2461 *ptr
++ = 0x08; *ptr
++ = 0x06;
2464 *ptr
++ = 0x00; *ptr
++ = 0x01; // Hardware address space; Ethernet = 1
2465 *ptr
++ = 0x08; *ptr
++ = 0x00; // Protocol address space; IP = 0x0800
2466 *ptr
++ = 6; // Hardware address length
2467 *ptr
++ = 4; // Protocol address length
2468 *ptr
++ = 0x00; *ptr
++ = op
; // opcode; Request = 1, Response = 2
2470 // 0x16 Sender hardware address (our MAC address)
2471 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[i
];
2473 // 0x1C Sender protocol address
2474 for (i
=0; i
<4; i
++) *ptr
++ = spa
->b
[i
];
2476 // 0x20 Target hardware address
2477 for (i
=0; i
<6; i
++) *ptr
++ = tha
->b
[i
];
2479 // 0x26 Target protocol address
2480 for (i
=0; i
<4; i
++) *ptr
++ = tpa
->b
[i
];
2482 // 0x2A Total ARP Packet length 42 bytes
2483 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2486 mDNSlocal mDNSu16
CheckSum(const void *const data
, mDNSs32 length
, mDNSu32 sum
)
2488 const mDNSu16
*ptr
= data
;
2489 while (length
> 0) { length
-= 2; sum
+= *ptr
++; }
2490 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2491 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2492 return(sum
!= 0xFFFF ? sum
: 0);
2495 mDNSlocal mDNSu16
IPv6CheckSum(const mDNSv6Addr
*const src
, const mDNSv6Addr
*const dst
, const mDNSu8 protocol
, const void *const data
, const mDNSu32 length
)
2497 IPv6PseudoHeader ph
;
2500 ph
.len
.b
[0] = length
>> 24;
2501 ph
.len
.b
[1] = length
>> 16;
2502 ph
.len
.b
[2] = length
>> 8;
2503 ph
.len
.b
[3] = length
;
2507 ph
.pro
.b
[3] = protocol
;
2508 return CheckSum(&ph
, sizeof(ph
), CheckSum(data
, length
, 0));
2511 mDNSlocal
void SendNDP(mDNS
*const m
, const mDNSu8 op
, const mDNSu8 flags
, const AuthRecord
*const rr
,
2512 const mDNSv6Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv6Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2515 mDNSOpaque16 checksum
;
2516 mDNSu8
*ptr
= m
->omsg
.data
;
2517 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2518 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2519 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2520 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] } };
2521 const mDNSv6Addr
*const v6dst
= (op
== NDP_Sol
) ? &mc
: tpa
;
2522 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2523 if (!intf
) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2525 // 0x00 Destination address
2526 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2527 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2528 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2529 // link with a pointless link-layer multicast.
2530 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2531 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2535 // *ptr++ = tpa->b[0xD];
2536 // *ptr++ = tpa->b[0xE];
2537 // *ptr++ = tpa->b[0xF];
2539 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2540 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2542 // 0x0C IPv6 Ethertype (0x86DD)
2543 *ptr
++ = 0x86; *ptr
++ = 0xDD;
2546 *ptr
++ = 0x60; *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00; // Version, Traffic Class, Flow Label
2547 *ptr
++ = 0x00; *ptr
++ = 0x20; // Length
2548 *ptr
++ = 0x3A; // Protocol == ICMPv6
2549 *ptr
++ = 0xFF; // Hop Limit
2551 // 0x16 Sender IPv6 address
2552 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2554 // 0x26 Destination IPv6 address
2555 for (i
=0; i
<16; i
++) *ptr
++ = v6dst
->b
[i
];
2558 *ptr
++ = op
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2559 *ptr
++ = 0x00; // Code
2560 *ptr
++ = 0x00; *ptr
++ = 0x00; // Checksum placeholder (0x38, 0x39)
2562 *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00;
2564 if (op
== NDP_Sol
) // Neighbor Solicitation. The NDP "target" is the address we seek.
2567 for (i
=0; i
<16; i
++) *ptr
++ = tpa
->b
[i
];
2568 // 0x4E Source Link-layer Address
2569 // <http://www.ietf.org/rfc/rfc2461.txt>
2570 // MUST NOT be included when the source IP address is the unspecified address.
2571 // Otherwise, on link layers that have addresses this option MUST be included
2572 // in multicast solicitations and SHOULD be included in unicast solicitations.
2573 if (!mDNSIPv6AddressIsZero(*spa
))
2575 *ptr
++ = NDP_SrcLL
; // Option Type 1 == Source Link-layer Address
2576 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2577 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2580 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2583 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2584 // 0x4E Target Link-layer Address
2585 *ptr
++ = NDP_TgtLL
; // Option Type 2 == Target Link-layer Address
2586 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2587 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2590 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2591 m
->omsg
.data
[0x13] = ptr
- &m
->omsg
.data
[0x36]; // Compute actual length
2592 checksum
.NotAnInteger
= ~IPv6CheckSum(spa
, v6dst
, 0x3A, &m
->omsg
.data
[0x36], m
->omsg
.data
[0x13]);
2593 m
->omsg
.data
[0x38] = checksum
.b
[0];
2594 m
->omsg
.data
[0x39] = checksum
.b
[1];
2596 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2599 mDNSlocal
void SetupTracerOpt(const mDNS
*const m
, rdataOPT
*const Trace
)
2601 mDNSu32 DNS_VERS
= _DNS_SD_H
;
2602 Trace
->u
.tracer
.platf
= m
->mDNS_plat
;
2603 Trace
->u
.tracer
.mDNSv
= DNS_VERS
;
2605 Trace
->opt
= kDNSOpt_Trace
;
2606 Trace
->optlen
= DNSOpt_TraceData_Space
- 4;
2609 mDNSlocal
void SetupOwnerOpt(const mDNS
*const m
, const NetworkInterfaceInfo
*const intf
, rdataOPT
*const owner
)
2611 owner
->u
.owner
.vers
= 0;
2612 owner
->u
.owner
.seq
= m
->SleepSeqNum
;
2613 owner
->u
.owner
.HMAC
= m
->PrimaryMAC
;
2614 owner
->u
.owner
.IMAC
= intf
->MAC
;
2615 owner
->u
.owner
.password
= zeroEthAddr
;
2617 // Don't try to compute the optlen until *after* we've set up the data fields
2618 // 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
2619 owner
->opt
= kDNSOpt_Owner
;
2620 owner
->optlen
= DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) - 4;
2623 mDNSlocal
void GrantUpdateCredit(AuthRecord
*rr
)
2625 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
2626 else rr
->NextUpdateCredit
= NonZeroTime(rr
->NextUpdateCredit
+ kUpdateCreditRefreshInterval
);
2629 mDNSlocal mDNSBool
ShouldSendGoodbyesBeforeSleep(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, AuthRecord
*rr
)
2631 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2632 // and hence there is no need to check for Transfering state. But if we have sleep
2633 // proxies and partially sending goodbyes for some records, we will be in Transfering
2634 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2635 // we are not awake handles both cases.
2636 if ((rr
->AuthFlags
& AuthFlagsWakeOnly
) && (m
->SleepState
!= SleepState_Awake
))
2638 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m
, rr
));
2642 if (m
->SleepState
!= SleepState_Sleeping
)
2645 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2646 // whether you can send goodbyes or not.
2647 if (!intf
->SendGoodbyes
)
2649 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2654 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2659 // Note about acceleration of announcements to facilitate automatic coalescing of
2660 // multiple independent threads of announcements into a single synchronized thread:
2661 // The announcements in the packet may be at different stages of maturity;
2662 // One-second interval, two-second interval, four-second interval, and so on.
2663 // After we've put in all the announcements that are due, we then consider
2664 // whether there are other nearly-due announcements that are worth accelerating.
2665 // To be eligible for acceleration, a record MUST NOT be older (further along
2666 // its timeline) than the most mature record we've already put in the packet.
2667 // In other words, younger records can have their timelines accelerated to catch up
2668 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2669 // Older records cannot have their timelines accelerated; this would just widen
2670 // the gap between them and their younger bretheren and get them even more out of sync.
2672 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2673 // the record list and/or question list.
2674 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2675 mDNSlocal
void SendResponses(mDNS
*const m
)
2678 AuthRecord
*rr
, *r2
;
2679 mDNSs32 maxExistingAnnounceInterval
= 0;
2680 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2682 m
->NextScheduledResponse
= m
->timenow
+ FutureTime
;
2684 if (m
->SleepState
== SleepState_Transferring
) RetrySPSRegistrations(m
);
2686 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2687 if (rr
->ImmedUnicast
)
2689 mDNSAddr v4
= { mDNSAddrType_IPv4
, {{{0}}} };
2690 mDNSAddr v6
= { mDNSAddrType_IPv6
, {{{0}}} };
2691 v4
.ip
.v4
= rr
->v4Requester
;
2692 v6
.ip
.v6
= rr
->v6Requester
;
2693 if (!mDNSIPv4AddressIsZero(rr
->v4Requester
)) SendDelayedUnicastResponse(m
, &v4
, rr
->ImmedAnswer
);
2694 if (!mDNSIPv6AddressIsZero(rr
->v6Requester
)) SendDelayedUnicastResponse(m
, &v6
, rr
->ImmedAnswer
);
2695 if (rr
->ImmedUnicast
)
2697 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m
, rr
));
2698 rr
->ImmedUnicast
= mDNSfalse
;
2703 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2706 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2707 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2709 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
2710 if (TimeToAnnounceThisRecord(rr
, m
->timenow
))
2712 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2714 if (!rr
->WakeUp
.HMAC
.l
[0])
2716 if (rr
->AnnounceCount
) rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send goodbye packet on all interfaces
2720 mDNSBool unicastOnly
;
2721 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr
->AnnounceCount
-3, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
2722 unicastOnly
= ((rr
->AnnounceCount
== WakeupCount
) || (rr
->AnnounceCount
== WakeupCount
- 1)) ? mDNStrue
: mDNSfalse
;
2723 SendWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.IMAC
, &rr
->WakeUp
.password
, unicastOnly
);
2724 for (r2
= rr
; r2
; r2
=r2
->next
)
2725 if ((r2
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) && r2
->AnnounceCount
&& (r2
->resrec
.InterfaceID
== rr
->resrec
.InterfaceID
) &&
2726 mDNSSameEthAddress(&r2
->WakeUp
.IMAC
, &rr
->WakeUp
.IMAC
) && !mDNSSameEthAddress(&zeroEthAddr
, &r2
->WakeUp
.HMAC
))
2728 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2729 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2730 if (r2
->AddressProxy
.type
== mDNSAddrType_IPv6
&& r2
->AnnounceCount
== WakeupCount
)
2732 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2733 r2
->AnnounceCount
-3, &r2
->WakeUp
.HMAC
, &r2
->WakeUp
.IMAC
, ARDisplayString(m
,r2
));
2734 SendNDP(m
, NDP_Adv
, NDP_Override
, r2
, &r2
->AddressProxy
.ip
.v6
, &r2
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2736 r2
->LastAPTime
= m
->timenow
;
2737 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2738 if (--r2
->AnnounceCount
<= GoodbyeCount
) r2
->WakeUp
.HMAC
= zeroEthAddr
;
2742 else if (ResourceRecordIsValidAnswer(rr
))
2744 if (rr
->AddressProxy
.type
)
2746 if (!mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
2748 rr
->AnnounceCount
--;
2749 rr
->ThisAPInterval
*= 2;
2750 rr
->LastAPTime
= m
->timenow
;
2751 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv4
)
2753 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2754 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2755 SendARP(m
, 1, rr
, &rr
->AddressProxy
.ip
.v4
, &zeroEthAddr
, &rr
->AddressProxy
.ip
.v4
, &onesEthAddr
);
2757 else if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
2759 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2760 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2761 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2767 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2768 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
2769 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
2770 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
2776 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2777 // Eligible records that are more than half-way to their announcement time are accelerated
2778 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2779 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
2780 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
2781 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
2782 !rr
->AddressProxy
.type
&& // Don't include ARP Annoucements when considering which records to accelerate
2783 ResourceRecordIsValidAnswer(rr
)))
2784 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2786 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2787 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2788 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2789 // then all that means is that it won't get sent -- which would not be the end of the world.
2790 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2792 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
2793 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
2794 if (RRTypeIsAddressType(r2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2795 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
2796 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
2797 rr
->resrec
.rdatahash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2798 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, r2
->resrec
.name
) &&
2799 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
2800 r2
->ImmedAdditional
= r2
->resrec
.InterfaceID
; // ... then mark this address record for sending too
2801 // We also make sure we send the DeviceInfo TXT record too, if necessary
2802 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2803 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2804 if (rr
->ImmedAnswer
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->resrec
.rrtype
== kDNSType_PTR
)
2805 if (ResourceRecordIsValidAnswer(&m
->DeviceInfo
) && SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2807 if (!m
->DeviceInfo
.ImmedAnswer
) m
->DeviceInfo
.ImmedAnswer
= rr
->ImmedAnswer
;
2808 else m
->DeviceInfo
.ImmedAnswer
= mDNSInterfaceMark
;
2812 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2813 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2814 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2815 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2816 // -- 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
2817 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2818 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2819 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2821 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
2823 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2825 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2826 (r2
->ImmedAnswer
!= mDNSInterfaceMark
) && (r2
->ImmedAnswer
!= rr
->ImmedAnswer
) &&
2827 SameResourceRecordSignature(r2
, rr
) &&
2828 ((rr
->ImmedAnswer
== mDNSInterfaceMark
) || IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAnswer
)))
2830 r2
->ImmedAnswer
= !r2
->ImmedAnswer
? rr
->ImmedAnswer
: mDNSInterfaceMark
;
2834 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
2836 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2838 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2839 (r2
->ImmedAdditional
!= rr
->ImmedAdditional
) &&
2840 SameResourceRecordSignature(r2
, rr
) &&
2841 IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAdditional
))
2843 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
2849 // Now set SendRNow state appropriately
2850 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2852 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
2854 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
2855 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
2856 rr
->LastMCTime
= m
->timenow
;
2857 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2858 rr
->ProbeRestartCount
= 0; // Reset the probe restart count
2859 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2860 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
2862 rr
->AnnounceCount
--;
2863 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
2864 rr
->ThisAPInterval
*= 2;
2865 rr
->LastAPTime
= m
->timenow
;
2866 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
2869 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
2871 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
2872 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
2873 rr
->LastMCTime
= m
->timenow
;
2874 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2876 SetNextAnnounceProbeTime(m
, rr
);
2877 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2881 // *** 2. Loop through interface list, sending records as appropriate
2886 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
2887 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
2889 int numAnnounce
= 0;
2891 mDNSu8
*responseptr
= m
->omsg
.data
;
2893 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2895 // First Pass. Look for:
2896 // 1. Deregistering records that need to send their goodbye packet
2897 // 2. Updated records that need to retract their old data
2898 // 3. Answers and announcements we need to send
2899 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2902 // Skip this interface if the record InterfaceID is *Any and the record is not
2903 // appropriate for the interface type.
2904 if ((rr
->SendRNow
== intf
->InterfaceID
) &&
2905 ((rr
->resrec
.InterfaceID
== mDNSInterface_Any
) && !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
)))
2907 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2909 else if (rr
->SendRNow
== intf
->InterfaceID
)
2911 RData
*OldRData
= rr
->resrec
.rdata
;
2912 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
2913 mDNSu8 active
= (mDNSu8
)
2914 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& !ShouldSendGoodbyesBeforeSleep(m
, intf
, rr
));
2916 if (rr
->NewRData
&& active
)
2918 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2919 if (ResourceRecordIsValidAnswer(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
2921 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, 0);
2922 if (newptr
) { responseptr
= newptr
; numDereg
++; rr
->RequireGoodbye
= mDNSfalse
; }
2923 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
2925 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
2928 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2929 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2930 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, active
? rr
->resrec
.rroriginalttl
: 0);
2931 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2934 responseptr
= newptr
;
2935 rr
->RequireGoodbye
= active
;
2936 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) numDereg
++;
2937 else if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++;else numAnswer
++;
2940 if (rr
->NewRData
&& active
)
2941 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
2943 // The first time through (pktcount==0), if this record is verified unique
2944 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2945 if (!pktcount
&& active
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2946 rr
->SendNSECNow
= mDNSInterfaceMark
;
2948 if (newptr
) // If succeeded in sending, advance to next interface
2950 // If sending on all interfaces, go to next interface; else we're finished now
2951 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
2952 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2954 rr
->SendRNow
= mDNSNULL
;
2959 // Second Pass. Add additional records, if there's space.
2960 newptr
= responseptr
;
2961 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2962 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
2963 if (ResourceRecordIsValidAnswer(rr
))
2965 // If we have at least one answer already in the packet, then plan to add additionals too
2966 mDNSBool SendAdditional
= (m
->omsg
.h
.numAnswers
> 0);
2968 // If we're not planning to send any additionals, but this record is a unique one, then
2969 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2970 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2971 if (!SendAdditional
&& (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
2973 const AuthRecord
*a
;
2974 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
2975 if (a
->LastMCTime
== m
->timenow
&&
2976 a
->LastMCInterface
== intf
->InterfaceID
&&
2977 SameResourceRecordSignature(a
, rr
)) { SendAdditional
= mDNStrue
; break; }
2979 if (!SendAdditional
) // If we don't want to send this after all,
2980 rr
->ImmedAdditional
= mDNSNULL
; // then cancel its ImmedAdditional field
2981 else if (newptr
) // Else, try to add it if we can
2983 // The first time through (pktcount==0), if this record is verified unique
2984 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2985 if (!pktcount
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2986 rr
->SendNSECNow
= mDNSInterfaceMark
;
2988 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2989 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2990 newptr
= PutRR_OS(newptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2991 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2994 responseptr
= newptr
;
2995 rr
->ImmedAdditional
= mDNSNULL
;
2996 rr
->RequireGoodbye
= mDNStrue
;
2997 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2998 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2999 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3000 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3001 rr
->LastMCTime
= m
->timenow
;
3002 rr
->LastMCInterface
= intf
->InterfaceID
;
3007 // Third Pass. Add NSEC records, if there's space.
3008 // When we're generating an NSEC record in response to a specify query for that type
3009 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3010 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3011 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3012 if (rr
->SendNSECNow
== mDNSInterfaceMark
|| rr
->SendNSECNow
== intf
->InterfaceID
)
3017 mDNS_SetupResourceRecord(&nsec
, mDNSNULL
, mDNSInterface_Any
, kDNSType_NSEC
, rr
->resrec
.rroriginalttl
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3018 nsec
.resrec
.rrclass
|= kDNSClass_UniqueRRSet
;
3019 AssignDomainName(&nsec
.namestorage
, rr
->resrec
.name
);
3020 ptr
= nsec
.rdatastorage
.u
.data
;
3021 len
= DomainNameLength(rr
->resrec
.name
);
3022 // We have a nxt name followed by window number, window length and a window bitmap
3023 nsec
.resrec
.rdlength
= len
+ 2 + NSEC_MCAST_WINDOW_SIZE
;
3024 if (nsec
.resrec
.rdlength
<= StandardAuthRDSize
)
3026 mDNSPlatformMemZero(ptr
, nsec
.resrec
.rdlength
);
3027 AssignDomainName((domainname
*)ptr
, rr
->resrec
.name
);
3029 *ptr
++ = 0; // window number
3030 *ptr
++ = NSEC_MCAST_WINDOW_SIZE
; // window length
3031 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3032 if (ResourceRecordIsValidAnswer(r2
) && SameResourceRecordNameClassInterface(r2
, rr
))
3034 if (r2
->resrec
.rrtype
>= kDNSQType_ANY
) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m
, r2
)); break; }
3035 else ptr
[r2
->resrec
.rrtype
>> 3] |= 128 >> (r2
->resrec
.rrtype
& 7);
3037 newptr
= responseptr
;
3038 if (!r2
) // If we successfully built our NSEC record, add it to the packet now
3040 newptr
= PutRR_OS(responseptr
, &m
->omsg
.h
.numAdditionals
, &nsec
.resrec
);
3041 if (newptr
) responseptr
= newptr
;
3044 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec
.resrec
.rdlength
);
3046 // If we successfully put the NSEC record, clear the SendNSECNow flag
3047 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3048 if (newptr
|| rr
->SendNSECNow
== mDNSInterfaceMark
)
3050 rr
->SendNSECNow
= mDNSNULL
;
3051 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3052 for (r2
= rr
->next
; r2
; r2
=r2
->next
)
3053 if (SameResourceRecordNameClassInterface(r2
, rr
))
3054 if (r2
->SendNSECNow
== mDNSInterfaceMark
|| r2
->SendNSECNow
== intf
->InterfaceID
)
3055 r2
->SendNSECNow
= mDNSNULL
;
3059 if (m
->omsg
.h
.numAnswers
|| m
->omsg
.h
.numAdditionals
)
3061 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3062 if (OwnerRecordSpace
|| TraceRecordSpace
)
3065 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3066 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3067 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
3068 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3069 if (OwnerRecordSpace
&& TraceRecordSpace
)
3071 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
3072 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
3073 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3074 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
3076 else if (OwnerRecordSpace
)
3078 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3080 else if (TraceRecordSpace
)
3082 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
3084 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
);
3087 responseptr
= newptr
;
3089 else if (m
->omsg
.h
.numAnswers
+ m
->omsg
.h
.numAuthorities
+ m
->omsg
.h
.numAdditionals
== 1)
3091 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3092 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3096 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3097 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3101 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3102 numDereg
, numDereg
== 1 ? "" : "s",
3103 numAnnounce
, numAnnounce
== 1 ? "" : "s",
3104 numAnswer
, numAnswer
== 1 ? "" : "s",
3105 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
3107 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
3108 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
3109 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
3110 if (++pktcount
>= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
3111 // There might be more things to send on this interface, so go around one more time and try again.
3113 else // Nothing more to send on this interface; go to next
3115 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3116 #if MDNS_DEBUGMSGS && 0
3117 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3118 debugf(msg
, intf
, next
);
3121 pktcount
= 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3126 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3129 if (m
->CurrentRecord
)
3130 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3131 m
->CurrentRecord
= m
->ResourceRecords
;
3132 while (m
->CurrentRecord
)
3134 rr
= m
->CurrentRecord
;
3135 m
->CurrentRecord
= rr
->next
;
3139 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
)
3140 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3141 IIDPrintable(rr
->SendRNow
), IIDPrintable(rr
->resrec
.InterfaceID
), rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
3142 rr
->SendRNow
= mDNSNULL
;
3145 if (rr
->ImmedAnswer
|| rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3147 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
3149 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->AnnounceCount
== 0)
3151 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3152 if (!AuthRecord_uDNS(rr
)) CompleteDeregistration(m
, rr
); // Don't touch rr after this
3156 rr
->ImmedAnswer
= mDNSNULL
;
3157 rr
->ImmedUnicast
= mDNSfalse
;
3158 rr
->v4Requester
= zerov4Addr
;
3159 rr
->v6Requester
= zerov6Addr
;
3163 verbosedebugf("SendResponses: Next in %ld ticks", m
->NextScheduledResponse
- m
->timenow
);
3166 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3167 // so we want to be lazy about how frequently we do it.
3168 // 1. If a cache record is currently referenced by *no* active questions,
3169 // then we don't mind expiring it up to a minute late (who will know?)
3170 // 2. Else, if a cache record is due for some of its final expiration queries,
3171 // we'll allow them to be late by up to 2% of the TTL
3172 // 3. Else, if a cache record has completed all its final expiration queries without success,
3173 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3174 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3175 // so allow at most 1/10 second lateness
3176 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3177 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3178 #define CacheCheckGracePeriod(CR) ( \
3179 ((CR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3180 ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50) : \
3181 ((CR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3182 ((CR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3184 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3186 mDNSexport
void ScheduleNextCacheCheckTime(mDNS
*const m
, const mDNSu32 slot
, const mDNSs32 event
)
3188 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3189 m
->rrcache_nextcheck
[slot
] = event
;
3190 if (m
->NextCacheCheck
- event
> 0)
3191 m
->NextCacheCheck
= event
;
3194 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3196 // rr->resrec.rroriginalttl
3197 // rr->UnansweredQueries
3198 // rr->CRActiveQuestion
3199 mDNSexport
void SetNextCacheCheckTimeForRecord(mDNS
*const m
, CacheRecord
*const rr
)
3201 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3203 // If we have an active question, then see if we want to schedule a refresher query for this record.
3204 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3205 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3207 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3208 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3209 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3210 (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
,rr
));
3212 ScheduleNextCacheCheckTime(m
, HashSlotFromNameHash(rr
->resrec
.namehash
), NextCacheCheckEvent(rr
));
3215 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3216 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3217 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3219 // Delay before restarting questions on a flapping interface.
3220 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3221 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3222 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3223 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3225 mDNSexport mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3227 if (interval
< kMinimumReconfirmTime
)
3228 interval
= kMinimumReconfirmTime
;
3229 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3230 interval
= 0x10000000;
3232 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3233 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3235 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3236 // For all the reconfirmations in a given batch, we want to use the same random value
3237 // so that the reconfirmation questions can be grouped into a single query packet
3238 if (!m
->RandomReconfirmDelay
) m
->RandomReconfirmDelay
= 1 + mDNSRandom(FutureTime
);
3239 interval
+= m
->RandomReconfirmDelay
% ((interval
/3) + 1);
3240 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3241 rr
->resrec
.rroriginalttl
= (interval
* 4 + mDNSPlatformOneSecond
- 1) / mDNSPlatformOneSecond
;
3242 SetNextCacheCheckTimeForRecord(m
, rr
);
3244 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3245 RRExpireTime(rr
) - m
->timenow
, CRDisplayString(m
, rr
), rr
->CRActiveQuestion
);
3246 return(mStatus_NoError
);
3249 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3250 // It also appends to the list of known answer records that need to be included,
3251 // and updates the forcast for the size of the known answer section.
3252 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, DNSMessage
*query
, mDNSu8
**queryptr
,
3253 DNSQuestion
*q
, CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3255 mDNSBool ucast
= (q
->LargeAnswers
|| q
->RequestUnicast
) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3256 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3257 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3258 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
- *answerforecast
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3261 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3266 mDNSu32 forecast
= *answerforecast
;
3267 const CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3269 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3271 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // If we have a resource record in our cache,
3272 if (cr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3273 !(cr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && // which is a shared (i.e. not unique) record type
3274 cr
->NextInKAList
== mDNSNULL
&& ka
!= &cr
->NextInKAList
&& // which is not already in the known answer list
3275 cr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3276 SameNameCacheRecordAnswersQuestion(cr
, q
) && // which answers our question
3277 cr
->TimeRcvd
+ TicksTTL(cr
)/2 - m
->timenow
> // and its half-way-to-expiry time is at least 1 second away
3278 mDNSPlatformOneSecond
) // (also ensures we never include goodbye records with TTL=1)
3280 // We don't want to include unique records in the Known Answer section. The Known Answer section
3281 // is intended to suppress floods of shared-record replies from many other devices on the network.
3282 // That concept really does not apply to unique records, and indeed if we do send a query for
3283 // which we have a unique record already in our cache, then including that unique record as a
3284 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3286 *ka
= cr
; // Link this record into our known answer chain
3287 ka
= &cr
->NextInKAList
;
3288 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3289 forecast
+= 12 + cr
->resrec
.rdestimate
;
3290 // If we're trying to put more than one question in this packet, and it doesn't fit
3291 // then undo that last question and try again next time
3292 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3294 query
->h
.numQuestions
--;
3295 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3296 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
, query
->h
.numQuestions
);
3297 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3298 while (*ka
) { CacheRecord
*c
= *ka
; *ka
= mDNSNULL
; ka
= &c
->NextInKAList
; }
3299 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3303 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3304 *queryptr
= newptr
; // Update the packet pointer
3305 *answerforecast
= forecast
; // Update the forecast
3306 *kalistptrptr
= ka
; // Update the known answer list pointer
3307 if (ucast
) q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
3309 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // For every resource record in our cache,
3310 if (cr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3311 cr
->NextInKAList
== mDNSNULL
&& ka
!= &cr
->NextInKAList
&& // which is not in the known answer list
3312 SameNameCacheRecordAnswersQuestion(cr
, q
)) // which answers our question
3314 cr
->UnansweredQueries
++; // indicate that we're expecting a response
3315 cr
->LastUnansweredTime
= m
->timenow
;
3316 SetNextCacheCheckTimeForRecord(m
, cr
);
3323 // When we have a query looking for a specified name, but there appear to be no answers with
3324 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3325 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3326 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3327 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3328 // A typical reconfirmation scenario might go like this:
3329 // Depth 0: Name "myhost.local" has no address records
3330 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3331 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3332 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3333 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3334 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3335 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSInterfaceID InterfaceID
, const int depth
)
3338 const CacheGroup
*cg
;
3340 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth
, name
->c
);
3341 if (!InterfaceID
) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3342 FORALL_CACHERECORDS(slot
, cg
, cr
)
3344 const domainname
*crtarget
;
3345 if (cr
->resrec
.InterfaceID
!= InterfaceID
) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3346 if (cr
->resrec
.rdatahash
!= namehash
) continue; // Skip records whose rdata hash doesn't match the name hash.
3347 crtarget
= GetRRDomainNameTarget(&cr
->resrec
);
3348 if (crtarget
&& SameDomainName(crtarget
, name
))
3350 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth
, InterfaceID
, CRDisplayString(m
, cr
));
3351 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
3353 ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, InterfaceID
, depth
+1);
3358 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3359 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3360 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3361 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3362 mDNSlocal
const CacheRecord
*CacheHasAddressTypeForName(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
3364 CacheGroup
*const cg
= CacheGroupForName(m
, namehash
, name
);
3365 const CacheRecord
*cr
= cg
? cg
->members
: mDNSNULL
;
3366 while (cr
&& !RRTypeIsAddressType(cr
->resrec
.rrtype
)) cr
=cr
->next
;
3371 mDNSlocal
const CacheRecord
*FindSPSInCache1(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*const c0
, const CacheRecord
*const c1
)
3373 #ifndef SPC_DISABLED
3374 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3375 const CacheRecord
*cr
, *bestcr
= mDNSNULL
;
3376 mDNSu32 bestmetric
= 1000000;
3377 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
3378 if (cr
->resrec
.rrtype
== kDNSType_PTR
&& cr
->resrec
.rdlength
>= 6) // If record is PTR type, with long enough name,
3379 if (cr
!= c0
&& cr
!= c1
) // that's not one we've seen before,
3380 if (SameNameCacheRecordAnswersQuestion(cr
, q
)) // and answers our browse query,
3381 if (!IdenticalSameNameRecord(&cr
->resrec
, &m
->SPSRecords
.RR_PTR
.resrec
)) // and is not our own advertised service...
3383 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
3384 if (bestmetric
> metric
) { bestmetric
= metric
; bestcr
= cr
; }
3387 #else // SPC_DISABLED
3394 #endif // SPC_DISABLED
3397 mDNSlocal
void CheckAndSwapSPS(const CacheRecord
**sps1
, const CacheRecord
**sps2
)
3399 const CacheRecord
*swap_sps
;
3400 mDNSu32 metric1
, metric2
;
3402 if (!(*sps1
) || !(*sps2
)) return;
3403 metric1
= SPSMetric((*sps1
)->resrec
.rdata
->u
.name
.c
);
3404 metric2
= SPSMetric((*sps2
)->resrec
.rdata
->u
.name
.c
);
3405 if (!SPSFeatures((*sps1
)->resrec
.rdata
->u
.name
.c
) && SPSFeatures((*sps2
)->resrec
.rdata
->u
.name
.c
) && (metric2
>= metric1
))
3413 mDNSlocal
void ReorderSPSByFeature(const CacheRecord
*sps
[3])
3415 CheckAndSwapSPS(&sps
[0], &sps
[1]);
3416 CheckAndSwapSPS(&sps
[0], &sps
[2]);
3417 CheckAndSwapSPS(&sps
[1], &sps
[2]);
3421 // Finds the three best Sleep Proxies we currently have in our cache
3422 mDNSexport
void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3])
3424 sps
[0] = FindSPSInCache1(m
, q
, mDNSNULL
, mDNSNULL
);
3425 sps
[1] = !sps
[0] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], mDNSNULL
);
3426 sps
[2] = !sps
[1] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], sps
[1]);
3428 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3429 // only if they have equally good metric and support features.
3430 ReorderSPSByFeature(sps
);
3433 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3434 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3437 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3440 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3443 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3446 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3449 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3450 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3451 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3452 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3454 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3455 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3456 if (v4
&& v6
) return(mDNStrue
);
3461 mDNSlocal
void RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3465 // See if we have this one in our list somewhere already
3466 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3468 // If not, find a slot we can re-use
3469 if (i
>= DupSuppressInfoSize
)
3472 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3473 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3477 // Record the info about this query we saw
3479 ds
[i
].InterfaceID
= InterfaceID
;
3483 mDNSlocal
void mDNSSendWakeOnResolve(mDNS
*const m
, DNSQuestion
*q
)
3486 mDNSInterfaceID InterfaceID
= q
->InterfaceID
;
3487 domainname
*d
= &q
->qname
;
3489 // We can't send magic packets without knowing which interface to send it on.
3490 if (InterfaceID
== mDNSInterface_Any
|| LocalOnlyOrP2PInterface(InterfaceID
))
3492 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID
, q
->qname
.c
);
3496 // Split MAC@IPAddress and pass them separately
3499 for (i
= 1; i
< len
; i
++)
3503 char EthAddr
[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3504 char IPAddr
[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3507 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q
->qname
.c
, cnt
);
3510 if ((i
- 1) > (int) (sizeof(EthAddr
) - 1))
3512 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q
->qname
.c
, i
- 1);
3515 if ((len
- i
) > (int)(sizeof(IPAddr
) - 1))
3517 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q
->qname
.c
, len
- i
);
3520 mDNSPlatformMemCopy(EthAddr
, &d
->c
[1], i
- 1);
3522 mDNSPlatformMemCopy(IPAddr
, &d
->c
[i
+ 1], len
- i
);
3523 IPAddr
[len
- i
] = 0;
3524 m
->mDNSStats
.WakeOnResolves
++;
3525 mDNSPlatformSendWakeupPacket(InterfaceID
, EthAddr
, IPAddr
, InitialWakeOnResolveCount
- q
->WakeOnResolveCount
);
3528 else if (d
->c
[i
] == ':')
3531 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q
->qname
.c
);
3535 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3537 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3538 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3541 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3542 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3544 // We forecast: qname (n) type (2) class (2)
3545 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
3546 const CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3547 const CacheRecord
*cr
;
3548 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // If we have a resource record in our cache,
3549 if (cr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3550 SameNameCacheRecordAnswersQuestion(cr
, q
) && // which answers our question
3551 cr
->TimeRcvd
+ TicksTTL(cr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3552 cr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0) // and we'll ask at least once again before NextRequiredQuery
3554 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3555 forecast
+= 12 + cr
->resrec
.rdestimate
;
3556 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3564 // How Standard Queries are generated:
3565 // 1. The Question Section contains the question
3566 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3568 // How Probe Queries are generated:
3569 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3570 // if some other host is already using *any* records with this name, we want to know about it.
3571 // 2. The Authority Section contains the proposed values we intend to use for one or more
3572 // of our records with that name (analogous to the Update section of DNS Update packets)
3573 // because if some other host is probing at the same time, we each want to know what the other is
3574 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3576 mDNSlocal
void SendQueries(mDNS
*const m
)
3584 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3585 mDNSs32 maxExistingQuestionInterval
= 0;
3586 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3587 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3589 // 1. If time for a query, work out what we need to do
3591 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3592 // to their NextRequiredQuery to be worth batching them together with this one
3593 FORALL_CACHERECORDS(slot
, cg
, cr
)
3595 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
3597 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
3599 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
3600 q
= cr
->CRActiveQuestion
;
3601 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(cr
)/20, cr
->resrec
.InterfaceID
);
3602 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3603 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3604 if (!mDNSOpaque16IsZero(q
->TargetQID
))
3606 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3607 cr
->UnansweredQueries
++;
3608 m
->mDNSStats
.CacheRefreshQueries
++;
3610 else if (q
->SendQNow
== mDNSNULL
)
3612 q
->SendQNow
= cr
->resrec
.InterfaceID
;
3614 else if (q
->SendQNow
!= cr
->resrec
.InterfaceID
)
3616 q
->SendQNow
= mDNSInterfaceMark
;
3619 // Indicate that this question was marked for sending
3620 // to update an existing cached answer record.
3621 // The browse throttling logic below uses this to determine
3622 // if the query should be sent.
3623 if (mDNSOpaque16IsZero(q
->TargetQID
))
3624 q
->CachedAnswerNeedsUpdate
= mDNStrue
;
3629 // Scan our list of questions to see which:
3630 // *WideArea* queries need to be sent
3631 // *unicast* queries need to be sent
3632 // *multicast* queries we're definitely going to send
3633 if (m
->CurrentQuestion
)
3634 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3635 m
->CurrentQuestion
= m
->Questions
;
3636 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3638 q
= m
->CurrentQuestion
;
3639 if (mDNSOpaque16IsZero(q
->TargetQID
) && TimeToSendThisQuestion(q
, m
->timenow
))
3641 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3642 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3643 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3644 maxExistingQuestionInterval
= q
->ThisQInterval
;
3646 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3647 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3648 // m->CurrentQuestion point to the right question
3649 if (q
== m
->CurrentQuestion
) m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3651 while (m
->CurrentQuestion
)
3653 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3654 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3656 m
->CurrentQuestion
= mDNSNULL
;
3658 // Scan our list of questions
3659 // (a) to see if there are any more that are worth accelerating, and
3660 // (b) to update the state variables for *all* the questions we're going to send
3661 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3662 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3663 // 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.
3664 m
->NextScheduledQuery
= m
->timenow
+ FutureTime
;
3665 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3667 if (mDNSOpaque16IsZero(q
->TargetQID
)
3668 && (q
->SendQNow
|| (ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
))))
3670 // If at least halfway to next query time, advance to next interval
3671 // If less than halfway to next query time, then
3672 // treat this as logically a repeat of the last transmission, without advancing the interval
3673 if (m
->timenow
- (q
->LastQTime
+ (q
->ThisQInterval
/2)) >= 0)
3675 // If we have reached the answer threshold for this question,
3676 // don't send it again until MaxQuestionInterval unless:
3677 // one of its cached answers needs to be refreshed,
3678 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3679 if (q
->BrowseThreshold
3680 && (q
->CurrentAnswers
>= q
->BrowseThreshold
)
3681 && (q
->CachedAnswerNeedsUpdate
== mDNSfalse
)
3682 && !((q
->flags
& kDNSServiceFlagsThresholdFinder
) && (q
->ThisQInterval
== InitialQuestionInterval
)))
3684 q
->SendQNow
= mDNSNULL
;
3685 q
->ThisQInterval
= MaxQuestionInterval
;
3686 q
->LastQTime
= m
->timenow
;
3687 q
->RequestUnicast
= 0;
3688 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3689 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
3693 // Mark this question for sending on all interfaces
3694 q
->SendQNow
= mDNSInterfaceMark
;
3695 q
->ThisQInterval
*= QuestionIntervalStep
;
3698 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3699 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
/ InitialQuestionInterval
, q
->RequestUnicast
);
3701 if (q
->ThisQInterval
> MaxQuestionInterval
)
3703 q
->ThisQInterval
= MaxQuestionInterval
;
3705 else if (mDNSOpaque16IsZero(q
->TargetQID
) && q
->InterfaceID
&&
3706 q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* QuestionIntervalStep3
&& !q
->RequestUnicast
&&
3707 !(RRTypeIsAddressType(q
->qtype
) && CacheHasAddressTypeForName(m
, &q
->qname
, q
->qnamehash
)))
3709 // Generally don't need to log this.
3710 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3711 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3712 // and when there simply happen to be no instances of the service the client is looking
3713 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3714 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3715 q
->qname
.c
, DNSTypeName(q
->qtype
));
3716 // Sending third query, and no answers yet; time to begin doubting the source
3717 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, q
->InterfaceID
, 0);
3721 // Mark for sending. (If no active interfaces, then don't even try.)
3722 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3725 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3726 q
->LastQTime
= m
->timenow
;
3729 // If we recorded a duplicate suppression for this question less than half an interval ago,
3730 // then we consider it recent enough that we don't need to do an identical query ourselves.
3731 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3733 q
->LastQTxTime
= m
->timenow
;
3734 q
->RecentAnswerPkts
= 0;
3735 if (q
->RequestUnicast
) q
->RequestUnicast
--;
3737 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3738 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3739 SetNextQueryTime(m
,q
);
3742 // 2. Scan our authoritative RR list to see what probes we might need to send
3744 m
->NextScheduledProbe
= m
->timenow
+ FutureTime
;
3746 if (m
->CurrentRecord
)
3747 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3748 m
->CurrentRecord
= m
->ResourceRecords
;
3749 while (m
->CurrentRecord
)
3751 ar
= m
->CurrentRecord
;
3752 m
->CurrentRecord
= ar
->next
;
3753 if (!AuthRecord_uDNS(ar
) && ar
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3755 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3756 if (m
->timenow
- (ar
->LastAPTime
+ ar
->ThisAPInterval
) < 0)
3758 SetNextAnnounceProbeTime(m
, ar
);
3760 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3761 else if (ar
->ProbeCount
)
3763 if (ar
->AddressProxy
.type
== mDNSAddrType_IPv4
)
3765 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3766 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3767 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3768 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3769 // A similar concern may apply to the NDP Probe too. -- SC
3770 LogSPS("SendQueries ARP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3771 SendARP(m
, 1, ar
, &zerov4Addr
, &zeroEthAddr
, &ar
->AddressProxy
.ip
.v4
, &ar
->WakeUp
.IMAC
);
3773 else if (ar
->AddressProxy
.type
== mDNSAddrType_IPv6
)
3775 LogSPS("SendQueries NDP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3776 // IPv6 source = zero
3777 // No target hardware address
3778 // IPv6 target address is address we're probing
3779 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3780 SendNDP(m
, NDP_Sol
, 0, ar
, &zerov6Addr
, mDNSNULL
, &ar
->AddressProxy
.ip
.v6
, &ar
->WakeUp
.IMAC
);
3782 // Mark for sending. (If no active interfaces, then don't even try.)
3783 ar
->SendRNow
= (!intf
|| ar
->WakeUp
.HMAC
.l
[0]) ? mDNSNULL
: ar
->resrec
.InterfaceID
? ar
->resrec
.InterfaceID
: intf
->InterfaceID
;
3784 ar
->LastAPTime
= m
->timenow
;
3785 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3786 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3787 if (ar
->ProbeCount
> DefaultProbeCountForTypeUnique
)
3788 ar
->ProbeCount
= DefaultProbeCountForTypeUnique
;
3790 SetNextAnnounceProbeTime(m
, ar
);
3791 if (ar
->ProbeCount
== 0)
3793 // If this is the last probe for this record, then see if we have any matching records
3794 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3796 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3797 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, ar
))
3799 // ... then acknowledge this record to the client.
3800 // We do this optimistically, just as we're about to send the third probe.
3801 // This helps clients that both advertise and browse, and want to filter themselves
3802 // from the browse results list, because it helps ensure that the registration
3803 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3804 // A potential downside is that we could deliver a registration confirmation and then find out
3805 // moments later that there's a name conflict, but applications have to be prepared to handle
3806 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3807 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
);
3810 // else, if it has now finished probing, move it to state Verified,
3811 // and update m->NextScheduledResponse so it will be announced
3814 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
); // Defensive, just in case it got missed somehow
3815 ar
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3816 ar
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3817 ar
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3818 SetNextAnnounceProbeTime(m
, ar
);
3822 m
->CurrentRecord
= m
->DuplicateRecords
;
3823 while (m
->CurrentRecord
)
3825 ar
= m
->CurrentRecord
;
3826 m
->CurrentRecord
= ar
->next
;
3827 if (ar
->resrec
.RecordType
== kDNSRecordTypeUnique
&& ar
->ProbeCount
== 0 && !ar
->Acknowledged
)
3828 AcknowledgeRecord(m
, ar
);
3831 // 3. Now we know which queries and probes we're sending,
3832 // go through our interface list sending the appropriate queries on each interface
3835 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
3836 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
3837 mDNSu8
*queryptr
= m
->omsg
.data
;
3838 mDNSBool useBackgroundTrafficClass
= mDNSfalse
; // set if we should use background traffic class
3840 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, QueryFlags
);
3841 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3842 if (!KnownAnswerList
)
3844 // Start a new known-answer list
3845 CacheRecord
**kalistptr
= &KnownAnswerList
;
3846 mDNSu32 answerforecast
= OwnerRecordSpace
+ TraceRecordSpace
; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3848 // Put query questions in this packet
3849 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3851 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
== intf
->InterfaceID
))
3853 mDNSBool Suppress
= mDNSfalse
;
3854 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3855 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3856 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- m
->omsg
.data
, queryptr
+ answerforecast
- m
->omsg
.data
);
3858 // If interface is P2P type, verify that query should be sent over it.
3859 if (!mDNSPlatformValidQuestionForInterface(q
, intf
))
3861 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3863 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3864 else if ((Suppress
= SuppressOnThisInterface(q
->DupSuppress
, intf
)) ||
3865 BuildQuestion(m
, intf
, &m
->omsg
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3868 m
->mDNSStats
.DupQuerySuppressions
++;
3870 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3871 if (q
->WakeOnResolveCount
)
3873 mDNSSendWakeOnResolve(m
, q
);
3874 q
->WakeOnResolveCount
--;
3877 // use background traffic class if any included question requires it
3878 if (q
->UseBackgroundTraffic
)
3880 useBackgroundTrafficClass
= mDNStrue
;
3886 // Put probe questions in this packet
3887 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3889 if (ar
->SendRNow
!= intf
->InterfaceID
)
3892 // If interface is a P2P variant, verify that the probe should be sent over it.
3893 if (!mDNSPlatformValidRecordForInterface(ar
, intf
->InterfaceID
))
3895 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3896 ar
->IncludeInProbe
= mDNSfalse
;
3900 mDNSBool ucast
= (ar
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3901 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3902 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.numQuestions
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3903 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3904 mDNSu32 forecast
= answerforecast
+ 12 + ar
->resrec
.rdestimate
;
3905 mDNSBool putProbe
= mDNStrue
;
3906 mDNSu16 qclass
= ar
->resrec
.rrclass
| ucbit
;
3908 {// Determine if this probe question is already in packet's dns message
3909 const mDNSu8
*questionptr
= m
->omsg
.data
;
3910 DNSQuestion question
;
3912 for (n
= 0; n
< m
->omsg
.h
.numQuestions
&& questionptr
; n
++)
3914 questionptr
= getQuestion(&m
->omsg
, questionptr
, limit
, mDNSInterface_Any
, &question
);
3915 if (questionptr
&& (question
.qtype
== kDNSQType_ANY
) && (question
.qclass
== qclass
) &&
3916 (question
.qnamehash
== ar
->resrec
.namehash
) && SameDomainName(&question
.qname
, ar
->resrec
.name
))
3918 putProbe
= mDNSfalse
; // set to false if already in message
3926 mDNSu8
*newptr
= putQuestion(&m
->omsg
, queryptr
, limit
- forecast
, ar
->resrec
.name
, kDNSQType_ANY
, qclass
);
3930 answerforecast
= forecast
;
3931 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3932 ar
->IncludeInProbe
= mDNStrue
;
3933 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3934 ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
), ar
->ProbeCount
, ar
->resrec
.InterfaceID
, ar
->resrec
.rdestimate
, answerforecast
);
3939 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3940 ar
->IncludeInProbe
= mDNStrue
;
3946 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3947 while (KnownAnswerList
)
3949 CacheRecord
*ka
= KnownAnswerList
;
3950 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- ka
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3951 mDNSu8
*newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAnswers
, &ka
->resrec
, ka
->resrec
.rroriginalttl
- SecsSinceRcvd
,
3952 m
->omsg
.data
+ NormalMaxDNSMessageData
- OwnerRecordSpace
- TraceRecordSpace
);
3955 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3956 ka
->resrec
.name
->c
, DNSTypeName(ka
->resrec
.rrtype
), queryptr
- m
->omsg
.data
, newptr
- m
->omsg
.data
);
3958 KnownAnswerList
= ka
->NextInKAList
;
3959 ka
->NextInKAList
= mDNSNULL
;
3963 // If we ran out of space and we have more than one question in the packet, that's an error --
3964 // we shouldn't have put more than one question if there was a risk of us running out of space.
3965 if (m
->omsg
.h
.numQuestions
> 1)
3966 LogMsg("SendQueries: Put %d answers; No more space for known answers", m
->omsg
.h
.numAnswers
);
3967 m
->omsg
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
3972 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3974 if (ar
->IncludeInProbe
)
3976 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, &ar
->resrec
);
3977 ar
->IncludeInProbe
= mDNSfalse
;
3978 if (newptr
) queryptr
= newptr
;
3979 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m
,ar
));
3983 if (queryptr
> m
->omsg
.data
)
3985 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3986 if (OwnerRecordSpace
|| TraceRecordSpace
)
3989 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3990 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3991 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
3992 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3993 if (OwnerRecordSpace
&& TraceRecordSpace
)
3995 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
3996 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
3997 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3998 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
4000 else if (OwnerRecordSpace
)
4002 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
4004 else if (TraceRecordSpace
)
4006 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
4008 queryptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAdditionals
,
4009 &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
4012 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
4013 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
4015 if (queryptr
> m
->omsg
.data
+ NormalMaxDNSMessageData
)
4017 if (m
->omsg
.h
.numQuestions
!= 1 || m
->omsg
.h
.numAnswers
!= 0 || m
->omsg
.h
.numAuthorities
!= 1 || m
->omsg
.h
.numAdditionals
!= 1)
4018 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "",
4019 TraceRecordSpace
? "TRACER" : "", m
->omsg
.data
, m
->omsg
.data
+ NormalMaxDNSMessageData
, queryptr
, m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
,
4020 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
4024 if ((m
->omsg
.h
.flags
.b
[0] & kDNSFlag0_TC
) && m
->omsg
.h
.numQuestions
> 1)
4025 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m
->omsg
.h
.numQuestions
);
4026 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4027 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
4028 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
4029 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAuthorities
== 1 ? "" : "s", IIDPrintable(intf
->InterfaceID
), intf
->ifname
);
4030 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, useBackgroundTrafficClass
);
4031 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, useBackgroundTrafficClass
);
4032 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
4033 if (++pktcount
>= 1000)
4034 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
4035 // There might be more records left in the known answer list, or more questions to send
4036 // on this interface, so go around one more time and try again.
4038 else // Nothing more to send on this interface; go to next
4040 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
4041 #if MDNS_DEBUGMSGS && 0
4042 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4043 debugf(msg
, intf
, next
);
4049 // 4. Final housekeeping
4051 // 4a. Debugging check: Make sure we announced all our records
4052 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
4055 if (ar
->ARType
!= AuthRecordLocalOnly
&& ar
->ARType
!= AuthRecordP2P
)
4056 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4057 IIDPrintable(ar
->SendRNow
), IIDPrintable(ar
->resrec
.InterfaceID
), ARDisplayString(m
, ar
));
4058 ar
->SendRNow
= mDNSNULL
;
4061 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4062 // that their interface which went away might come back again, the logic will want to send queries
4063 // for those records, but we can't because their interface isn't here any more, so to keep the
4064 // state machine ticking over we just pretend we did so.
4065 // If the interface does not come back in time, the cache record will expire naturally
4066 FORALL_CACHERECORDS(slot
, cg
, cr
)
4068 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
4070 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
4072 cr
->UnansweredQueries
++;
4073 cr
->CRActiveQuestion
->SendQNow
= mDNSNULL
;
4074 SetNextCacheCheckTimeForRecord(m
, cr
);
4079 // 4c. Debugging check: Make sure we sent all our planned questions
4080 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4081 // we legitimately couldn't send because the interface is no longer available
4082 for (q
= m
->Questions
; q
; q
=q
->next
)
4087 for (x
= m
->NewQuestions
; x
; x
=x
->next
) if (x
== q
) break; // Check if this question is a NewQuestion
4088 // There will not be an active interface for questions applied to mDNSInterface_BLE
4089 // so don't log the warning in that case.
4090 if (q
->InterfaceID
!= mDNSInterface_BLE
)
4091 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4092 IIDPrintable(q
->SendQNow
), x
? "new" : "old", IIDPrintable(q
->InterfaceID
), q
->qname
.c
, DNSTypeName(q
->qtype
));
4093 q
->SendQNow
= mDNSNULL
;
4095 q
->CachedAnswerNeedsUpdate
= mDNSfalse
;
4099 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
)
4103 mDNSu8
*ptr
= m
->omsg
.data
;
4104 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
4105 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID
); return; }
4107 // 0x00 Destination address
4108 for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4110 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4111 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
4113 // 0x0C Ethertype (0x0842)
4117 // 0x0E Wakeup sync sequence
4118 for (i
=0; i
<6; i
++) *ptr
++ = 0xFF;
4121 for (j
=0; j
<16; j
++) for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4124 for (i
=0; i
<6; i
++) *ptr
++ = password
->b
[i
];
4126 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4130 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4131 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4132 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4133 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4134 // So, we send one of each, unicast first, then broadcast second.
4135 for (i
=0; i
<6; i
++) m
->omsg
.data
[i
] = 0xFF;
4136 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4140 // ***************************************************************************
4141 #if COMPILER_LIKES_PRAGMA_MARK
4143 #pragma mark - RR List Management & Task Management
4146 // Whenever a question is answered, reset its state so that we don't query
4147 // the network repeatedly. This happens first time when we answer the question and
4148 // and later when we refresh the cache.
4149 mDNSlocal
void ResetQuestionState(mDNS
*const m
, DNSQuestion
*q
)
4151 q
->LastQTime
= m
->timenow
;
4152 q
->LastQTxTime
= m
->timenow
;
4153 q
->RecentAnswerPkts
= 0;
4154 q
->ThisQInterval
= MaxQuestionInterval
;
4155 q
->RequestUnicast
= 0;
4156 // Reset unansweredQueries so that we don't penalize this server later when we
4157 // start sending queries when the cache expires.
4158 q
->unansweredQueries
= 0;
4159 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4162 mDNSlocal
void AdjustUnansweredQueries(mDNS
*const m
, CacheRecord
*const rr
)
4164 const mDNSs32 expireTime
= RRExpireTime(rr
);
4165 const mDNSu32 interval
= TicksTTL(rr
) / 20; // Calculate 5% of the cache record's TTL.
4168 // If the record is expired or UnansweredQueries is already at the max, then return early.
4169 if (((m
->timenow
- expireTime
) >= 0) || (rr
->UnansweredQueries
>= MaxUnansweredQueries
)) return;
4173 LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr
), CRDisplayString(m
, rr
));
4177 // Calculate the number of whole 5% TTL intervals between now and expiration time.
4178 rem
= ((mDNSu32
)(expireTime
- m
->timenow
)) / interval
;
4180 // Calculate the expected number of remaining refresher queries.
4181 // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4182 if (rem
> MaxUnansweredQueries
) rem
= MaxUnansweredQueries
;
4184 // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4185 // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4186 // refresher queries would have been sent if the cache record did have an active question. The cache record's
4187 // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4188 // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4189 // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4190 // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4191 // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4192 // Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4193 if ((MaxUnansweredQueries
- rr
->UnansweredQueries
) > (mDNSs32
)rem
)
4195 if (rem
== 0) rem
++;
4196 rr
->UnansweredQueries
= (mDNSu8
)(MaxUnansweredQueries
- rem
);
4200 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4201 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4202 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4203 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4204 mDNSexport
void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
)
4206 DNSQuestion
*const q
= m
->CurrentQuestion
;
4207 const mDNSBool followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
4209 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4210 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", MortalityDisplayString(rr
->resrec
.mortality
),
4211 rr
->resrec
.rroriginalttl
, CRDisplayString(m
, rr
));
4213 // When the response for the question was validated, the entire rrset was validated. If we deliver
4214 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
4215 // in the future, we will do the revalidation again.
4217 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
4218 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
4219 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
4220 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
4221 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
4222 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
4223 // a real negative response, we would reset the state here and validate the results at the end of this function.
4224 // or the real response again if we purge the cache.
4225 if (q
->ValidationRequired
&& ((AddRecord
== QC_rmv
) ||
4226 (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
&& (AddRecord
== QC_add
))))
4228 q
->ValidationStatus
= 0;
4229 q
->ValidationState
= DNSSECValRequired
;
4232 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4233 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4234 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4235 // we check to see if that query already has a unique local answer.
4236 if (q
->LOAddressAnswers
)
4238 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4239 "LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
),
4240 q
->LOAddressAnswers
);
4244 if (q
->Suppressed
&& (AddRecord
!= QC_suppressed
))
4246 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4247 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4248 // that are timing out, which we know are answered with negative cache record when timing out.
4249 if (!q
->TimeoutQuestion
|| rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| (m
->timenow
- q
->StopTime
< 0))
4253 // Set the record to immortal if appropriate
4254 if (AddRecord
== QC_add
&& Question_uDNS(q
) && rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&&
4255 q
->allowExpired
!= AllowExpired_None
&& rr
->resrec
.mortality
== Mortality_Mortal
) rr
->resrec
.mortality
= Mortality_Immortal
; // Update a non-expired cache record to immortal if appropriate
4257 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4258 if ((AddRecord
== QC_add
) && Question_uDNS(q
) && !followcname
)
4260 const domainname
* queryName
;
4261 mDNSu32 responseLatencyMs
;
4262 mDNSBool isForCellular
;
4264 queryName
= q
->metrics
.originalQName
? q
->metrics
.originalQName
: &q
->qname
;
4265 isForCellular
= (q
->qDNSServer
&& q
->qDNSServer
->isCell
);
4266 if (!q
->metrics
.answered
)
4268 if (q
->metrics
.querySendCount
> 0)
4270 responseLatencyMs
= ((m
->timenow
- q
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
4274 responseLatencyMs
= 0;
4277 MetricsUpdateDNSQueryStats(queryName
, q
->qtype
, &rr
->resrec
, q
->metrics
.querySendCount
, q
->metrics
.expiredAnswerState
, q
->metrics
.dnsOverTCPState
, responseLatencyMs
, isForCellular
);
4278 q
->metrics
.answered
= mDNStrue
;
4282 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4283 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4284 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4286 if (AddRecord
== QC_add
&& !q
->DuplicateOf
&& rr
->CRActiveQuestion
!= q
&& rr
->resrec
.mortality
!= Mortality_Ghost
)
4288 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4289 rr
->CRActiveQuestion
, q
, CRDisplayString(m
,rr
), q
->CurrentAnswers
);
4290 if (!rr
->CRActiveQuestion
)
4292 m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4293 AdjustUnansweredQueries(m
, rr
); // Adjust UnansweredQueries in case the record missed out on refresher queries
4295 rr
->CRActiveQuestion
= q
; // We know q is non-null
4296 SetNextCacheCheckTimeForRecord(m
, rr
);
4300 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4301 // (b) a normal add, where we have at least one unique-type answer,
4302 // then there's no need to keep polling the network.
4303 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4304 // We do this for mDNS questions and uDNS one-shot questions, but not for
4305 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4306 if ((AddRecord
== QC_addnocache
&& !q
->RequestUnicast
) ||
4307 (AddRecord
== QC_add
&& (q
->ExpectUnique
|| (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))))
4308 if (ActiveQuestion(q
) && (mDNSOpaque16IsZero(q
->TargetQID
) || !q
->LongLived
))
4310 ResetQuestionState(m
, q
);
4313 if (rr
->DelayDelivery
) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4315 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4316 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4317 if (!mDNSOpaque16IsZero(q
->TargetQID
) && DNS64StateMachine(m
, q
, &rr
->resrec
, AddRecord
)) return;
4321 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) // If negative answer, check if we need to try Punycode conversion
4324 if (PerformNextPunycodeConversion(q
, &newname
)) // Itertative Punycode conversion succeeded, so reissue question with new name
4326 UDPSocket
*const sock
= q
->LocalSocket
; // Save old socket and transaction ID
4327 const mDNSOpaque16 id
= q
->TargetQID
;
4328 q
->LocalSocket
= mDNSNULL
;
4329 mDNS_StopQuery_internal(m
, q
); // Stop old query
4330 AssignDomainName(&q
->qname
, &newname
); // Update qname
4331 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
4332 mDNS_StartQuery_internal(m
, q
); // Start new query
4334 if (sock
) // Transplant saved socket, if appropriate
4336 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
4337 else { q
->LocalSocket
= sock
; q
->TargetQID
= id
; }
4339 return; // All done for now; wait until we get the next answer
4342 #endif // USE_LIBIDN
4344 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4345 // for the purpose of retrying search domains/timeout OR the question is suppressed
4346 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
|| (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
)))
4347 if (!AddRecord
|| (AddRecord
!= QC_suppressed
&& AddRecord
!= QC_forceresponse
&& !q
->ReturnIntermed
)) return;
4349 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4350 if (q
->QuestionCallback
&& !q
->NoAnswer
&& (!followcname
|| q
->ReturnIntermed
))
4352 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4353 if (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
))
4356 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->qDNSServer
);
4357 q
->QuestionCallback(m
, q
, &neg
.resrec
, AddRecord
);
4361 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4362 if (DNS64ShouldAnswerQuestion(q
, &rr
->resrec
))
4364 DNS64AnswerCurrentQuestion(m
, &rr
->resrec
, AddRecord
);
4369 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4372 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4374 // Note: Proceed with caution after this point because client callback function
4375 // invoked above is allowed to do anything, such as starting/stopping queries
4376 // (including this one itself, or the next or previous query in the linked list),
4377 // registering/deregistering records, starting/stopping NAT traversals, etc.
4379 // If this is an "Add" operation and this question needs validation, validate the response.
4380 // In the case of negative responses, extra care should be taken. Negative cache records are
4381 // used for many purposes. For example,
4383 // 1) Suppressing questions (SuppressUnusable)
4384 // 2) Timeout questions
4385 // 3) The name does not exist
4386 // 4) No DNS servers are available and we need a quick response for the application
4388 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4389 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4390 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4391 // signature for (4) and hence the explicit check for q->qDNSServer.
4393 if (m
->CurrentQuestion
== q
&& (AddRecord
== QC_add
) && !q
->ValidatingResponse
&& q
->ValidationRequired
&&
4394 q
->ValidationState
== DNSSECValRequired
&& q
->qDNSServer
)
4396 q
->ValidationState
= DNSSECValInProgress
;
4397 // Treat it as callback call as that's what dnssec code expects
4398 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4399 VerifySignature(m
, mDNSNULL
, q
);
4400 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4404 if ((m
->CurrentQuestion
== q
) && !ValidatingQuestion(q
))
4406 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4407 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4408 // first before following it
4409 if (followcname
) AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
4411 // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4412 if (rr
->resrec
.mortality
== Mortality_Ghost
&& !q
->firstExpiredQname
.c
[0] && (q
->allowExpired
== AllowExpired_AllowExpiredAnswers
) && rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
4414 debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m
,rr
), q
);
4415 // Note: question->qname is already changed at this point if following a CNAME
4416 AssignDomainName(&q
->firstExpiredQname
, rr
->resrec
.name
); // Update firstExpiredQname
4421 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*cr
)
4423 cr
->DelayDelivery
= 0;
4424 if (m
->CurrentQuestion
)
4425 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4426 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4427 m
->CurrentQuestion
= m
->Questions
;
4428 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4430 DNSQuestion
*q
= m
->CurrentQuestion
;
4431 if (CacheRecordAnswersQuestion(cr
, q
))
4432 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
4433 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4434 m
->CurrentQuestion
= q
->next
;
4436 m
->CurrentQuestion
= mDNSNULL
;
4439 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
4441 const mDNSs32 threshold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
4442 const mDNSs32 start
= m
->timenow
- 0x10000000;
4443 mDNSs32 delay
= start
;
4444 CacheGroup
*cg
= CacheGroupForName(m
, namehash
, name
);
4445 const CacheRecord
*rr
;
4447 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4449 if (threshold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
4451 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
4452 delay
= RRExpireTime(rr
);
4455 if (delay
- start
> 0)
4456 return(NonZeroTime(delay
));
4461 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4462 // If new questions are created as a result of invoking client callbacks, they will be added to
4463 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4464 // rr is a new CacheRecord just received into our cache
4465 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4466 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4467 // which may change the record list and/or question list.
4468 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4469 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*cr
)
4473 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4474 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4475 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
4477 if (CacheRecordAnswersQuestion(cr
, q
))
4479 // If this question is one that's actively sending queries, and it's received ten answers within one
4480 // second of sending the last query packet, then that indicates some radical network topology change,
4481 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4482 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4483 // because we will anyway send another query within a few seconds. The first reset query is sent out
4484 // randomized over the next four seconds to reduce possible synchronization between machines.
4485 if (q
->LastAnswerPktNum
!= m
->PktNum
)
4487 q
->LastAnswerPktNum
= m
->PktNum
;
4488 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
4489 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4491 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4492 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
4493 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4494 q
->ThisQInterval
= InitialQuestionInterval
;
4495 SetNextQueryTime(m
,q
);
4498 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr
, cr
->resrec
.name
->c
,
4499 DNSTypeName(cr
->resrec
.rrtype
), cr
->resrec
.rroriginalttl
, cr
->resrec
.rDNSServer
?
4500 &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(cr
->resrec
.rDNSServer
?
4501 cr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
4502 q
->CurrentAnswers
++;
4504 q
->unansweredQueries
= 0;
4505 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4506 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4507 if (q
->CurrentAnswers
> 4000)
4509 static int msgcount
= 0;
4510 if (msgcount
++ < 10)
4511 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4512 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
4513 cr
->resrec
.rroriginalttl
= 0;
4514 cr
->UnansweredQueries
= MaxUnansweredQueries
;
4519 if (!cr
->DelayDelivery
)
4521 if (m
->CurrentQuestion
)
4522 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4523 m
->CurrentQuestion
= m
->Questions
;
4524 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4526 q
= m
->CurrentQuestion
;
4527 if (CacheRecordAnswersQuestion(cr
, q
))
4528 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
4529 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4530 m
->CurrentQuestion
= q
->next
;
4532 m
->CurrentQuestion
= mDNSNULL
;
4535 SetNextCacheCheckTimeForRecord(m
, cr
);
4538 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4539 // If new questions are created as a result of invoking client callbacks, they will be added to
4540 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4541 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4542 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4543 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4544 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4545 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4546 // which may change the record list and/or question list.
4547 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4548 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*cr
)
4550 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
4551 if (m
->CurrentQuestion
)
4552 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4553 m
->CurrentQuestion
= m
->Questions
;
4554 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4555 // since we're not caching the record and we'll get no opportunity to do this later
4556 while (m
->CurrentQuestion
)
4558 DNSQuestion
*q
= m
->CurrentQuestion
;
4559 if (CacheRecordAnswersQuestion(cr
, q
))
4560 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
4561 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4562 m
->CurrentQuestion
= q
->next
;
4564 m
->CurrentQuestion
= mDNSNULL
;
4567 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4568 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4569 // If new questions are created as a result of invoking client callbacks, they will be added to
4570 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4571 // cr is an existing cache CacheRecord that just expired and is being deleted
4572 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4573 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4574 // which may change the record list and/or question list.
4575 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4576 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*cr
)
4578 if (m
->CurrentQuestion
)
4579 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4580 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4581 m
->CurrentQuestion
= m
->Questions
;
4583 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4584 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4585 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4587 DNSQuestion
*q
= m
->CurrentQuestion
;
4588 // When a question enters suppressed state, we generate RMV events and generate a negative
4589 // response. A cache may be present that answers this question e.g., cache entry generated
4590 // before the question became suppressed. We need to skip the suppressed questions here as
4591 // the RMV event has already been generated.
4592 if (!q
->Suppressed
&& CacheRecordAnswersQuestion(cr
, q
) &&
4593 (q
->allowExpired
== AllowExpired_None
|| cr
->resrec
.mortality
== Mortality_Mortal
))
4595 verbosedebugf("CacheRecordRmv %p %s", cr
, CRDisplayString(m
, cr
));
4596 q
->FlappingInterface1
= mDNSNULL
;
4597 q
->FlappingInterface2
= mDNSNULL
;
4599 if (q
->CurrentAnswers
== 0)
4600 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4601 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
4602 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
4605 q
->CurrentAnswers
--;
4606 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4607 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4610 // If we have dropped below the answer threshold for this mDNS question,
4611 // restart the queries at InitialQuestionInterval.
4612 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->BrowseThreshold
> 0) && (q
->CurrentAnswers
< q
->BrowseThreshold
))
4614 q
->ThisQInterval
= InitialQuestionInterval
;
4615 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4616 SetNextQueryTime(m
,q
);
4617 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4618 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
4620 if (cr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
4622 if ((q
->CurrentAnswers
== 0) && mDNSOpaque16IsZero(q
->TargetQID
))
4624 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4625 q
->qname
.c
, DNSTypeName(q
->qtype
));
4626 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, cr
->resrec
.InterfaceID
, 0);
4628 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_rmv
);
4631 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4632 m
->CurrentQuestion
= q
->next
;
4634 m
->CurrentQuestion
= mDNSNULL
;
4637 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
4639 #if MDNS_MALLOC_DEBUGGING >= 1
4641 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
4643 e
->next
= m
->rrcache_free
;
4644 m
->rrcache_free
= e
;
4645 m
->rrcache_totalused
--;
4648 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
4650 CacheEntity
*e
= (CacheEntity
*)(*cp
);
4651 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4652 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
4653 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4654 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4655 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4656 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
4657 (*cp
)->name
= mDNSNULL
;
4658 *cp
= (*cp
)->next
; // Cut record from list
4659 ReleaseCacheEntity(m
, e
);
4662 mDNSlocal
void ReleaseAdditionalCacheRecords(mDNS
*const m
, CacheRecord
**rp
)
4666 CacheRecord
*rr
= *rp
;
4667 *rp
= (*rp
)->next
; // Cut record from list
4668 if (rr
->resrec
.rdata
&& rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
)
4670 mDNSPlatformMemFree(rr
->resrec
.rdata
);
4671 rr
->resrec
.rdata
= mDNSNULL
;
4673 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4674 // of the CacheGroup.
4675 if (rr
->resrec
.name
)
4677 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
4678 mDNSPlatformMemFree((void *)rr
->resrec
.name
);
4679 rr
->resrec
.name
= mDNSNULL
;
4681 // Don't count the NSEC3 records used by anonymous browse/reg
4682 if (!rr
->resrec
.InterfaceID
)
4684 m
->rrcache_totalused_unicast
-= rr
->resrec
.rdlength
;
4685 if (DNSSECRecordType(rr
->resrec
.rrtype
))
4686 BumpDNSSECStats(m
, kStatsActionDecrement
, kStatsTypeMemoryUsage
, rr
->resrec
.rdlength
);
4688 ReleaseCacheEntity(m
, (CacheEntity
*)rr
);
4692 mDNSexport
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
4696 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4697 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
4698 r
->resrec
.rdata
= mDNSNULL
;
4700 cg
= CacheGroupForRecord(m
, &r
->resrec
);
4704 // It is okay to have this printed for NSEC/NSEC3s
4705 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4707 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4708 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4709 // (which is handled below) and in that case it should be freed here.
4710 if (r
->resrec
.name
&& cg
&& r
->resrec
.name
!= cg
->name
)
4712 debugf("ReleaseCacheRecord: freeing %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4713 mDNSPlatformMemFree((void *)r
->resrec
.name
);
4715 r
->resrec
.name
= mDNSNULL
;
4717 if (!r
->resrec
.InterfaceID
)
4719 m
->rrcache_totalused_unicast
-= r
->resrec
.rdlength
;
4720 if (DNSSECRecordType(r
->resrec
.rrtype
))
4721 BumpDNSSECStats(m
, kStatsActionDecrement
, kStatsTypeMemoryUsage
, r
->resrec
.rdlength
);
4724 ReleaseAdditionalCacheRecords(m
, &r
->nsec
);
4725 ReleaseAdditionalCacheRecords(m
, &r
->soa
);
4727 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
4730 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4731 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4732 // callbacks for old records are delivered before callbacks for newer records.
4733 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
4735 CacheRecord
**rp
= &cg
->members
;
4737 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4738 m
->lock_rrcache
= 1;
4742 CacheRecord
*const rr
= *rp
;
4743 mDNSBool recordReleased
= mDNSfalse
;
4744 mDNSs32 event
= RRExpireTime(rr
);
4745 if (m
->timenow
- event
>= 0) // If expired, delete it
4747 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4749 DNSQuestion
*q
= rr
->CRActiveQuestion
;
4750 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4751 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4752 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4753 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4754 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4755 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4756 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4757 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4758 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4759 if (((mDNSOpaque16IsZero(q
->TargetQID
) && (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)) ||
4760 (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
)) && ActiveQuestion(q
))
4762 q
->ThisQInterval
= InitialQuestionInterval
;
4763 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4764 SetNextQueryTime(m
, q
);
4766 CacheRecordRmv(m
, rr
);
4767 m
->rrcache_active
--;
4770 event
+= MAX_GHOST_TIME
; // Adjust so we can check for a ghost expiration
4771 if (rr
->resrec
.mortality
== Mortality_Mortal
|| // Normal expired mortal record that needs released
4772 (rr
->resrec
.mortality
== Mortality_Ghost
&& m
->timenow
- event
>= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago
4773 { // Release as normal
4774 *rp
= rr
->next
; // Cut it from the list before ReleaseCacheRecord
4775 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4776 MortalityDisplayString(rr
->resrec
.mortality
),
4777 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4778 ReleaseCacheRecord(m
, rr
);
4779 recordReleased
= mDNStrue
;
4781 else // An immortal record needs to become a ghost when it expires
4782 { // Don't release this entry
4783 if (rr
->resrec
.mortality
== Mortality_Immortal
)
4785 rr
->resrec
.mortality
= Mortality_Ghost
; // Expired immortal records become ghosts
4786 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4787 MortalityDisplayString(rr
->resrec
.mortality
),
4788 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4792 else // else, not expired; see if we need to query
4794 // If waiting to delay delivery, do nothing until then
4795 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
4796 event
= rr
->DelayDelivery
;
4799 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
4800 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4802 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4803 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
4804 else // else trigger our question to go out now
4806 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4807 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4808 m
->NextScheduledQuery
= m
->timenow
;
4809 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4810 // which will correctly update m->NextCacheCheck for us.
4811 event
= m
->timenow
+ FutureTime
;
4817 if (!recordReleased
) // Schedule if we did not release the record
4819 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4820 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
4821 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
4822 m
->rrcache_nextcheck
[slot
] = event
;
4826 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
4827 cg
->rrcache_tail
= rp
;
4828 m
->lock_rrcache
= 0;
4831 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4833 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4834 // returns true if there is an answer.
4836 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4837 // returns true to indicate the same.
4838 mDNSlocal mDNSBool
AnswerQuestionWithLORecord(mDNS
*const m
, DNSQuestion
*q
, mDNSBool checkOnly
)
4843 if (m
->CurrentRecord
)
4844 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4846 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
4849 m
->CurrentRecord
= ag
->members
;
4850 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
4852 AuthRecord
*rr
= m
->CurrentRecord
;
4853 m
->CurrentRecord
= rr
->next
;
4855 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4856 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4858 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4859 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4860 // we handle both mDNSInterface_Any and scoped questions.
4862 if (rr
->ARType
== AuthRecordLocalOnly
|| (rr
->ARType
== AuthRecordP2P
&& (q
->InterfaceID
== mDNSInterface_Any
|| q
->InterfaceID
== mDNSInterface_BLE
)))
4863 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
4867 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q
->qname
.c
, DNSTypeName(q
->qtype
),
4868 ARDisplayString(m
, rr
));
4869 m
->CurrentRecord
= mDNSNULL
;
4872 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_add
);
4873 if (m
->CurrentQuestion
!= q
)
4874 break; // If callback deleted q, then we're finished here
4878 m
->CurrentRecord
= mDNSNULL
;
4880 if (m
->CurrentQuestion
!= q
)
4882 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4886 if (q
->LOAddressAnswers
)
4888 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4889 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4893 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4894 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4895 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4896 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4897 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4900 lr
= ag
->NewLocalOnlyRecords
;
4903 if (UniqueLocalOnlyRecord(lr
) && LocalOnlyRecordAnswersQuestion(lr
, q
))
4905 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4906 " LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4915 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4916 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4918 mDNSlocal
void AnswerSuppressedQuestion(mDNS
*const m
, DNSQuestion
*q
)
4920 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4921 // just deactivate the DNSQuestion.
4922 if (q
->ReturnIntermed
)
4924 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_suppressed
);
4928 q
->ThisQInterval
= 0;
4932 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4934 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4935 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
4936 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4937 if (!mDNSOpaque16IsZero(q
->TargetQID
)) DNS64HandleNewQuestion(m
, q
);
4939 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
4941 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4943 if (cg
) CheckCacheExpiration(m
, HashSlotFromNameHash(q
->qnamehash
), cg
);
4944 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
4945 m
->NewQuestions
= q
->next
;
4946 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4947 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4949 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4950 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4951 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4952 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4953 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4954 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4955 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4956 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4958 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4959 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4960 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4961 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4963 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4964 // This should be safe, because calling the client's question callback may cause the
4965 // question list to be modified, but should not ever cause the rrcache list to be modified.
4966 // If the client's question callback deletes the question, then m->CurrentQuestion will
4967 // be advanced, and we'll exit out of the loop
4968 m
->lock_rrcache
= 1;
4969 if (m
->CurrentQuestion
) {
4970 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4971 "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME
" (" PUB_S
")",
4972 m
->CurrentQuestion
->request_id
, mDNSVal16(m
->CurrentQuestion
->TargetQID
),
4973 DM_NAME_PARAM(m
->CurrentQuestion
->qname
.c
), DNSTypeName(m
->CurrentQuestion
->qtype
));
4976 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4978 if (q
->NoAnswer
== NoAnswer_Fail
)
4980 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4981 "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME
" (" PUB_S
")",
4982 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
4984 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
4985 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
4986 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
4987 // Don't touch the question if it has been stopped already
4988 if (m
->CurrentQuestion
== q
) q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
4989 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
4992 if (m
->CurrentQuestion
!= q
)
4994 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4998 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4999 // or P2P record, then we are done.
5000 if (AnswerQuestionWithLORecord(m
, q
, mDNSfalse
))
5003 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5004 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5005 // the question out.
5008 AnswerSuppressedQuestion(m
, q
);
5010 else if (!q
->ValidatingResponse
)
5013 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
5014 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
5016 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5017 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- cr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
5018 mDNSBool IsExpired
= (cr
->resrec
.rroriginalttl
<= SecsSinceRcvd
);
5019 if (IsExpired
&& q
->allowExpired
!= AllowExpired_AllowExpiredAnswers
) continue; // Go to next one in loop
5021 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5022 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5023 if ((cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
5024 ShouldQueryImmediately
= mDNSfalse
;
5025 q
->CurrentAnswers
++;
5026 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
5027 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
5028 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5029 if (q
->metrics
.expiredAnswerState
== ExpiredAnswer_Allowed
) q
->metrics
.expiredAnswerState
= IsExpired
? ExpiredAnswer_AnsweredWithExpired
: ExpiredAnswer_AnsweredWithCache
;
5031 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
5032 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5034 else if (mDNSOpaque16IsZero(q
->TargetQID
) && RRTypeIsAddressType(cr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
5035 ShouldQueryImmediately
= mDNSfalse
;
5037 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5038 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5039 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
5041 q
->InitialCacheMiss
= mDNStrue
; // Initial cache check is done, so mark as a miss from now on
5042 if (q
->allowExpired
== AllowExpired_AllowExpiredAnswers
)
5044 q
->allowExpired
= AllowExpired_MakeAnswersImmortal
; // After looking through the cache for an answer, demote to make immortal
5045 if (q
->firstExpiredQname
.c
[0]) // If an original query name was saved on an expired answer, start it over in case it is updated
5047 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
5048 "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME
" for allowExpiredAnswers question",
5049 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->firstExpiredQname
.c
));
5050 mDNS_StopQuery_internal(m
, q
); // Stop old query
5051 AssignDomainName(&q
->qname
, &q
->firstExpiredQname
); // Update qname
5052 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
5053 mDNS_StartQuery_internal(m
, q
); // start new query
5054 q
->CNAMEReferrals
= 0; // Reset referral count
5055 q
->firstExpiredQname
.c
[0] = 0; // Erase the domain name
5059 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5060 // Hence we don't execute the following block of code for those cases.
5061 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
5063 debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->request_id
, mDNSVal16(q
->TargetQID
), q
->qname
.c
, DNSTypeName(q
->qtype
));
5064 q
->ThisQInterval
= InitialQuestionInterval
;
5065 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5066 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
5068 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5069 if (!m
->RandomQueryDelay
)
5070 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
5071 q
->LastQTime
+= m
->RandomQueryDelay
;
5075 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5076 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5077 // answers for this question until *after* its scheduled transmission time, in which case
5078 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5079 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5080 SetNextQueryTime(m
,q
);
5083 m
->CurrentQuestion
= mDNSNULL
;
5084 m
->lock_rrcache
= 0;
5087 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5088 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
5089 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
5092 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
5093 mDNSBool retEv
= mDNSfalse
;
5094 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
5096 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5098 if (m
->CurrentQuestion
)
5099 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5100 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5101 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
5103 if (m
->CurrentRecord
)
5104 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
5106 // 1. First walk the LocalOnly records answering the LocalOnly question
5107 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5108 // walk the ResourceRecords list delivering the answers
5109 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
5112 m
->CurrentRecord
= ag
->members
;
5113 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
5115 AuthRecord
*rr
= m
->CurrentRecord
;
5116 m
->CurrentRecord
= rr
->next
;
5117 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
5120 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_add
);
5121 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5126 if (m
->CurrentQuestion
== q
)
5128 m
->CurrentRecord
= m
->ResourceRecords
;
5130 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
5132 AuthRecord
*ar
= m
->CurrentRecord
;
5133 m
->CurrentRecord
= ar
->next
;
5134 if (AuthRecordAnswersQuestion(ar
, q
))
5137 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, QC_add
);
5138 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5143 // The local host is the authoritative source for LocalOnly questions
5144 // so if no records exist and client requested intermediates, then generate a negative response
5145 if (!retEv
&& (m
->CurrentQuestion
== q
) && q
->ReturnIntermed
)
5146 GenerateNegativeResponse(m
, mDNSInterface_LocalOnly
, QC_forceresponse
);
5148 m
->CurrentQuestion
= mDNSNULL
;
5149 m
->CurrentRecord
= mDNSNULL
;
5152 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
5154 CacheEntity
*e
= mDNSNULL
;
5156 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
5157 m
->lock_rrcache
= 1;
5159 // If we have no free records, ask the client layer to give us some more memory
5160 if (!m
->rrcache_free
&& m
->MainCallback
)
5162 if (m
->rrcache_totalused
!= m
->rrcache_size
)
5164 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
5165 "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5166 m
->rrcache_totalused
, m
->rrcache_size
);
5169 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5170 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5171 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5172 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5173 // and recycle them, instead of allocating more memory.
5174 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
5176 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
5177 "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5178 m
->rrcache_size
, m
->rrcache_active
);
5182 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5183 m
->MainCallback(m
, mStatus_GrowCache
);
5184 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5188 // If we still have no free records, recycle all the records we can.
5189 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5190 if (!m
->rrcache_free
)
5192 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
5194 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5196 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5199 CacheRecord
**rp
= &(*cp
)->members
;
5202 // Records that answer still-active questions are not candidates for recycling
5203 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5204 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
5208 CacheRecord
*rr
= *rp
;
5209 *rp
= (*rp
)->next
; // Cut record from list
5210 ReleaseCacheRecord(m
, rr
);
5213 if ((*cp
)->rrcache_tail
!= rp
)
5214 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
5215 (*cp
)->rrcache_tail
= rp
;
5216 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
5217 else ReleaseCacheGroup(m
, cp
);
5220 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5221 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
5224 if (m
->rrcache_free
) // If there are records in the free list, take one
5226 e
= m
->rrcache_free
;
5227 m
->rrcache_free
= e
->next
;
5228 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
5230 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "RR Cache now using %u objects", m
->rrcache_totalused
);
5231 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
5232 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
5233 else m
->rrcache_report
+= 1000;
5235 mDNSPlatformMemZero(e
, sizeof(*e
));
5238 m
->lock_rrcache
= 0;
5243 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
5245 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
5248 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
5249 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
5251 r
->resrec
.rdata
= (RData
*) mDNSPlatformMemAllocateClear(sizeofRDataHeader
+ RDLength
);
5252 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
5253 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
5259 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
5261 mDNSu16 namelen
= DomainNameLength(rr
->name
);
5262 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
5263 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
5264 cg
->next
= m
->rrcache_hash
[slot
];
5265 cg
->namehash
= rr
->namehash
;
5266 cg
->members
= mDNSNULL
;
5267 cg
->rrcache_tail
= &cg
->members
;
5268 if (namelen
> sizeof(cg
->namestorage
))
5269 cg
->name
= (domainname
*) mDNSPlatformMemAllocate(namelen
);
5271 cg
->name
= (domainname
*)cg
->namestorage
;
5274 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
5275 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
5278 AssignDomainName(cg
->name
, rr
->name
);
5280 if (CacheGroupForRecord(m
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
5281 m
->rrcache_hash
[slot
] = cg
;
5282 if (CacheGroupForRecord(m
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
5287 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
5291 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5292 // a positive answer using an expired record (e.g. from an interface that has gone away).
5293 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5294 // summary deletion without giving the proper callback to any questions that are monitoring it.
5295 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5296 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
5297 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5298 rr
->resrec
.rroriginalttl
= 0;
5299 SetNextCacheCheckTimeForRecord(m
, rr
);
5302 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
5305 mDNSPlatformLock(m
);
5308 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5309 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
5312 if (m
->timenow
) time
= m
->timenow
;
5313 else time
= mDNS_TimeNow_NoLock(m
);
5314 mDNSPlatformUnlock(m
);
5318 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5319 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5320 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5321 #define SetSPSProxyListChanged(X) do { \
5322 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5323 m->SPSProxyListChanged = (X); } while(0)
5325 // Called from mDNS_Execute() to expire stale proxy records
5326 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
5328 m
->CurrentRecord
= list
;
5329 while (m
->CurrentRecord
)
5331 AuthRecord
*rr
= m
->CurrentRecord
;
5332 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
5334 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5335 // so we need to cease proxying for *all* records we may have, expired or not.
5336 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
5338 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
5339 m
->NextScheduledSPS
= rr
->TimeExpire
;
5341 else // else proxy record expired, so remove it
5343 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5344 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
5345 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
5346 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
5347 // Don't touch rr after this -- memory may have been free'd
5350 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5351 // new records could have been added to the end of the list as a result of that call.
5352 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
5353 m
->CurrentRecord
= rr
->next
;
5357 mDNSlocal
void CheckRmvEventsForLocalRecords(mDNS
*const m
)
5359 while (m
->CurrentRecord
)
5361 AuthRecord
*rr
= m
->CurrentRecord
;
5362 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
5364 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m
, rr
));
5365 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
5366 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_rmv
);
5367 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
5369 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
5370 rr
->AnsweredLocalQ
= mDNSfalse
;
5371 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5372 // For LocalOnly records, we don't do that and hence we need to do that here.
5373 if (RRLocalOnly(rr
)) CompleteDeregistration(m
, rr
);
5376 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5377 m
->CurrentRecord
= rr
->next
;
5381 mDNSlocal
void TimeoutQuestions_internal(mDNS
*const m
, DNSQuestion
* questions
, mDNSInterfaceID InterfaceID
)
5383 if (m
->CurrentQuestion
)
5384 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
,
5385 DNSTypeName(m
->CurrentQuestion
->qtype
));
5386 m
->CurrentQuestion
= questions
;
5387 while (m
->CurrentQuestion
)
5389 DNSQuestion
*const q
= m
->CurrentQuestion
;
5392 if (!q
->TimeoutQuestion
)
5393 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5395 if (m
->timenow
- q
->StopTime
>= 0)
5397 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q
, q
->qname
.c
, m
->timenow
- q
->StopTime
);
5398 q
->LOAddressAnswers
= 0; // unset since timing out the question
5399 GenerateNegativeResponse(m
, InterfaceID
, QC_forceresponse
);
5400 if (m
->CurrentQuestion
== q
) q
->StopTime
= 0;
5404 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
5405 m
->NextScheduledStopTime
= q
->StopTime
;
5408 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5409 // We can't do this at the start of the loop because GenerateNegativeResponse
5410 // depends on having m->CurrentQuestion point to the right question
5411 if (m
->CurrentQuestion
== q
)
5412 m
->CurrentQuestion
= q
->next
;
5414 m
->CurrentQuestion
= mDNSNULL
;
5417 mDNSlocal
void TimeoutQuestions(mDNS
*const m
)
5419 m
->NextScheduledStopTime
= m
->timenow
+ FutureTime
; // push reschedule of TimeoutQuestions to way off into the future
5420 TimeoutQuestions_internal(m
, m
->Questions
, mDNSInterface_Any
);
5421 TimeoutQuestions_internal(m
, m
->LocalOnlyQuestions
, mDNSInterface_LocalOnly
);
5424 mDNSlocal
void mDNSCoreFreeProxyRR(mDNS
*const m
)
5426 AuthRecord
*rrPtr
= m
->SPSRRSet
, *rrNext
= mDNSNULL
;
5427 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__
);
5430 rrNext
= rrPtr
->next
;
5431 mDNSPlatformMemFree(rrPtr
);
5434 m
->SPSRRSet
= mDNSNULL
;
5437 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
5439 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
5441 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
5444 AuthRecord
*head
, *tail
;
5448 verbosedebugf("mDNS_Execute");
5450 if (m
->CurrentQuestion
)
5451 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5452 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5454 if (m
->CurrentRecord
)
5455 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
5457 // 1. If we're past the probe suppression time, we can clear it
5458 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
5460 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5461 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
5463 // 3. Purge our cache of stale old records
5464 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
5466 mDNSu32 numchecked
= 0;
5467 m
->NextCacheCheck
= m
->timenow
+ FutureTime
;
5468 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5470 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
5472 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5473 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ FutureTime
;
5476 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
5478 CheckCacheExpiration(m
, slot
, *cp
);
5479 if ((*cp
)->members
) cp
=&(*cp
)->next
;
5480 else ReleaseCacheGroup(m
, cp
);
5483 // Even if we didn't need to actually check this slot yet, still need to
5484 // factor its nextcheck time into our overall NextCacheCheck value
5485 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
5486 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
5488 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
5491 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
5493 m
->NextScheduledSPS
= m
->timenow
+ FutureTime
;
5494 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
5495 CheckProxyRecords(m
, m
->ResourceRecords
);
5498 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
5500 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5501 // as records could have expired during that check
5502 if (m
->timenow
- m
->NextScheduledKA
>= 0)
5504 m
->NextScheduledKA
= m
->timenow
+ FutureTime
;
5505 mDNS_SendKeepalives(m
);
5508 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5509 if (m
->NextBonjourDisableTime
&& (m
->timenow
- m
->NextBonjourDisableTime
>= 0))
5511 // Schedule immediate network change processing to leave the multicast group
5512 // since the delay time has expired since the previous active registration or query.
5513 m
->NetworkChanged
= m
->timenow
;
5514 m
->NextBonjourDisableTime
= 0;
5515 m
->BonjourEnabled
= 0;
5517 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5521 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5522 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0)
5524 m
->AnnounceOwner
= 0;
5527 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
5530 if (m
->SleepState
== SleepState_Transferring
)
5532 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5533 BeginSleepProcessing(m
);
5537 // 4. See if we can answer any of our new local questions from the cache
5538 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
5540 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
5541 AnswerNewQuestion(m
);
5543 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5545 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5546 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5547 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
5549 m
->LocalRemoveEvents
= mDNSfalse
;
5550 m
->CurrentRecord
= m
->ResourceRecords
;
5551 CheckRmvEventsForLocalRecords(m
);
5552 // Walk the LocalOnly records and deliver the RMV events
5553 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5554 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5556 m
->CurrentRecord
= ag
->members
;
5557 if (m
->CurrentRecord
) CheckRmvEventsForLocalRecords(m
);
5561 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5563 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
5564 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5566 head
= tail
= mDNSNULL
;
5567 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
5569 AuthRecord
*rr
= m
->NewLocalRecords
;
5570 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
5571 if (LocalRecordReady(rr
))
5573 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5574 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_add
);
5578 // If we have just one record that is not ready, we don't have to unlink and
5579 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5580 // terminate and set the NewLocalRecords to rr.
5581 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
5582 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
5583 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
5589 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
5590 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
5591 // if this is the first record we are skipping, move to the end of the list.
5592 // if we have already skipped records before, append it at the end.
5593 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
5594 if (*p
) *p
= rr
->next
; // Cut this record from the list
5595 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
5598 while (*p
) p
=&(*p
)->next
;
5607 rr
->next
= mDNSNULL
;
5610 m
->NewLocalRecords
= head
;
5611 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
5613 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5615 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5616 // to our local questions
5617 if (m
->NewLocalOnlyRecords
)
5619 m
->NewLocalOnlyRecords
= mDNSfalse
;
5620 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5622 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5624 for (i
=0; i
<100 && ag
->NewLocalOnlyRecords
; i
++)
5626 AuthRecord
*rr
= ag
->NewLocalOnlyRecords
;
5627 ag
->NewLocalOnlyRecords
= ag
->NewLocalOnlyRecords
->next
;
5628 // LocalOnly records should always be ready as they never probe
5629 if (LocalRecordReady(rr
))
5631 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5632 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_add
);
5634 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m
, rr
));
5636 // We limit about 100 per AuthGroup that can be serviced at a time
5637 if (i
>= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5642 // 5. See what packets we need to send
5643 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
5644 DiscardDeregistrations(m
);
5645 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
5647 // If the platform code is ready, and we're not suppressing packet generation right now
5648 // then send our responses, probes, and questions.
5649 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5650 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5651 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5652 // Finally, we send responses, including the previously mentioned records that just completed probing.
5653 m
->SuppressSending
= 0;
5655 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5656 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
5657 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
5660 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5661 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
5662 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
5663 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
5664 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
5665 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5667 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
5669 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5670 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
5671 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
5674 // 7. Send Response packets, including probing records just advanced to announcing state
5675 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
5676 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
5678 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5679 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
5683 // Clear RandomDelay values, ready to pick a new different value next time
5684 m
->RandomQueryDelay
= 0;
5685 m
->RandomReconfirmDelay
= 0;
5687 // See if any questions (or local-only questions) have timed out
5688 if (m
->NextScheduledStopTime
&& m
->timenow
- m
->NextScheduledStopTime
>= 0) TimeoutQuestions(m
);
5689 #ifndef UNICAST_DISABLED
5690 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
5691 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
5692 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
5694 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5695 extern void serviceBLE();
5696 if (m
->NextBLEServiceTime
&& (m
->timenow
- m
->NextBLEServiceTime
>= 0)) serviceBLE();
5697 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5700 // Note about multi-threaded systems:
5701 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5702 // performing mDNS API operations that change our next scheduled event time.
5704 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5705 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5706 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5707 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5708 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5709 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5710 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5711 // without blocking. This avoids the race condition between the signal from the other thread arriving
5712 // just *before* or just *after* the main thread enters the blocking primitive.
5714 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5715 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5716 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5717 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5718 // by the time it gets to the timer callback function).
5720 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5721 return(m
->NextScheduledEvent
);
5724 #ifndef UNICAST_DISABLED
5725 mDNSlocal
void SuspendLLQs(mDNS
*m
)
5728 for (q
= m
->Questions
; q
; q
= q
->next
)
5729 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
5730 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
5732 #endif // UNICAST_DISABLED
5734 mDNSlocal mDNSBool
QuestionHasLocalAnswers(mDNS
*const m
, DNSQuestion
*q
)
5739 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
5742 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
5743 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5744 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
5746 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
));
5753 // ActivateUnicastQuery() is called from three places:
5754 // 1. When a new question is created
5755 // 2. On wake from sleep
5756 // 3. When the DNS configuration changes
5757 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5758 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5759 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
5761 if (!question
->DuplicateOf
)
5763 debugf("ActivateUnicastQuery: %##s %s%s",
5764 question
->qname
.c
, DNSTypeName(question
->qtype
), ScheduleImmediately
? " ScheduleImmediately" : "");
5765 question
->CNAMEReferrals
= 0;
5766 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
5767 if (question
->LongLived
)
5769 question
->state
= LLQ_Init
;
5770 question
->id
= zeroOpaque64
;
5771 question
->servPort
= zeroIPPort
;
5772 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
5774 // If the question has local answers, then we don't want answers from outside
5775 if (ScheduleImmediately
&& !QuestionHasLocalAnswers(m
, question
))
5777 question
->ThisQInterval
= InitialQuestionInterval
;
5778 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
5779 SetNextQueryTime(m
, question
);
5784 // Caller should hold the lock
5785 mDNSexport
void mDNSCoreRestartAddressQueries(mDNS
*const m
, mDNSBool SearchDomainsChanged
, FlushCache flushCacheRecords
,
5786 CallbackBeforeStartQuery BeforeStartCallback
, void *context
)
5789 DNSQuestion
*restart
= mDNSNULL
;
5793 // 1. Flush the cache records
5794 if (flushCacheRecords
) flushCacheRecords(m
);
5796 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5797 // we are going to stop the question. Hence we need to deliver the RMV event before we
5798 // stop the question.
5800 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5801 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5802 // *any* other question which could be the next one that we may process here. RestartQuestion
5803 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5804 // if the "next" question is stopped while the CurrentQuestion is stopped
5806 if (m
->RestartQuestion
)
5807 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5808 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
5810 m
->RestartQuestion
= m
->Questions
;
5811 while (m
->RestartQuestion
)
5813 q
= m
->RestartQuestion
;
5814 m
->RestartQuestion
= q
->next
;
5815 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5816 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5817 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5818 // question followed by the original query that refers to this GetZoneData question, we will end up
5819 // freeing the GetZoneData question and then start the "freed" question at the end.
5821 if (IsGetZoneDataQuestion(q
))
5823 DNSQuestion
*refq
= q
->next
;
5824 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5825 // debug stuff, we just try to find the referencing question and don't do much with it
5828 if (q
== &refq
->nta
->question
)
5830 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq
, refq
->qname
.c
, DNSTypeName(refq
->qtype
), q
);
5837 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5838 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
&& q
->qtype
!= kDNSType_CNAME
) continue;
5840 // If the search domains did not change, then we restart all the queries. Otherwise, only
5841 // for queries for which we "might" have appended search domains ("might" because we may
5842 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5843 if (!SearchDomainsChanged
|| q
->AppendSearchDomains
)
5845 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5846 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5847 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5848 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5849 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5850 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5851 // for the original query using these cache entries as ADDs were never delivered using these cache
5852 // entries and hence this order is needed.
5854 // If the query is suppressed, the RMV events won't be delivered
5855 if (!CacheRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5857 // Suppressed status does not affect questions that are answered using local records
5858 if (!LocalRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5860 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q
,
5861 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->AppendSearchDomains
);
5862 mDNS_StopQuery_internal(m
, q
);
5863 if (q
->ResetHandler
) q
->ResetHandler(q
);
5869 // 3. Callback before we start the query
5870 if (BeforeStartCallback
) BeforeStartCallback(m
, context
);
5872 // 4. Restart all the stopped queries
5876 restart
= restart
->next
;
5878 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5879 mDNS_StartQuery_internal(m
, q
);
5883 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
5887 #ifndef UNICAST_DISABLED
5888 // Retrigger all our uDNS questions
5889 if (m
->CurrentQuestion
)
5890 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5891 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5892 m
->CurrentQuestion
= m
->Questions
;
5893 while (m
->CurrentQuestion
)
5895 q
= m
->CurrentQuestion
;
5896 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
5897 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
)) ActivateUnicastQuery(m
, q
, mDNStrue
);
5901 // Retrigger all our mDNS questions
5902 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5903 mDNSCoreRestartQuestion(m
, q
);
5906 // restart question if it's multicast and currently active
5907 mDNSexport
void mDNSCoreRestartQuestion(mDNS
*const m
, DNSQuestion
*q
)
5909 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
5911 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
5912 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
5913 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5914 q
->RecentAnswerPkts
= 0;
5915 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
5916 m
->NextScheduledQuery
= m
->timenow
;
5920 // restart the probe/announce cycle for multicast record
5921 mDNSexport
void mDNSCoreRestartRegistration(mDNS
*const m
, AuthRecord
*rr
, int announceCount
)
5923 if (!AuthRecord_uDNS(rr
))
5925 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5926 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
5928 if (mDNS_KeepaliveRecord(&rr
->resrec
))
5930 rr
->AnnounceCount
= 0; // Do not announce keepalive records
5934 // announceCount < 0 indicates default announce count should be used
5935 if (announceCount
< 0)
5936 announceCount
= InitialAnnounceCount
;
5937 if (rr
->AnnounceCount
< (mDNSu8
)announceCount
)
5938 rr
->AnnounceCount
= (mDNSu8
)announceCount
;
5941 rr
->SendNSECNow
= mDNSNULL
;
5942 InitializeLastAPTime(m
, rr
);
5946 // ***************************************************************************
5947 #if COMPILER_LIKES_PRAGMA_MARK
5949 #pragma mark - Power Management (Sleep/Wake)
5952 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
5954 #ifndef IDLESLEEPCONTROL_DISABLED
5955 mDNSBool allowSleep
= mDNStrue
;
5960 if (m
->SystemSleepOnlyIfWakeOnLAN
)
5962 // Don't sleep if we are a proxy for any services
5963 if (m
->ProxyRecords
)
5965 allowSleep
= mDNSfalse
;
5966 mDNS_snprintf(reason
, sizeof(reason
), "sleep proxy for %d records", m
->ProxyRecords
);
5967 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
5970 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
5972 // Scan the list of active interfaces
5973 NetworkInterfaceInfo
*intf
;
5974 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
5976 if (intf
->McastTxRx
&& !intf
->Loopback
&& !mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
5978 // Disallow sleep if this interface doesn't support NetWake
5981 allowSleep
= mDNSfalse
;
5982 mDNS_snprintf(reason
, sizeof(reason
), "%s does not support NetWake", intf
->ifname
);
5983 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf
->ifname
);
5987 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5988 // that will be offloaded. If not, we should prevent sleep.
5989 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5990 #if APPLE_OSX_mDNSResponder
5991 if (!SupportsInNICProxy(intf
))
5994 // Disallow sleep if there is no sleep proxy server
5995 const CacheRecord
*cr
= FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
);
5996 if ( cr
== mDNSNULL
)
5998 allowSleep
= mDNSfalse
;
5999 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server on %s", intf
->ifname
);
6000 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf
->ifname
);
6003 else if (m
->SPSType
!= 0)
6005 mDNSu32 mymetric
= LocalSPSMetric(m
);
6006 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
6007 if (metric
>= mymetric
)
6009 allowSleep
= mDNSfalse
;
6010 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server with better metric on %s", intf
->ifname
);
6011 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf
->ifname
);
6021 // Call the platform code to enable/disable sleep
6022 mDNSPlatformSetAllowSleep(allowSleep
, reason
);
6025 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6028 mDNSlocal mDNSBool
mDNSUpdateOkToSend(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSu32 scopeid
)
6030 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6031 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6033 if (AuthRecord_uDNS(rr
) || (rr
->AuthFlags
& AuthFlagsWakeOnly
) || mDNSOpaque16IsZero(rr
->updateid
) ||
6034 m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
6039 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6040 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6041 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6042 // updateid and we should have returned from above.
6044 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6045 // platform function to extract the value from "intf" every time.
6047 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6048 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6054 mDNSexport
void UpdateRMAC(mDNS
*const m
, void *context
)
6056 IPAddressMACMapping
*addrmap
= (IPAddressMACMapping
*)context
;
6057 m
->CurrentRecord
= m
->ResourceRecords
;
6061 LogMsg("UpdateRMAC: Address mapping is NULL");
6065 while (m
->CurrentRecord
)
6067 AuthRecord
*rr
= m
->CurrentRecord
;
6068 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6069 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
6072 getKeepaliveRaddr(m
, rr
, &raddr
);
6073 if (mDNSSameAddress(&raddr
, &addrmap
->ipaddr
))
6075 // Update the MAC address only if it is not a zero MAC address
6076 mDNSEthAddr macAddr
;
6077 mDNSu8
*ptr
= GetValueForMACAddr((mDNSu8
*)(addrmap
->ethaddr
), (mDNSu8
*) (addrmap
->ethaddr
+ sizeof(addrmap
->ethaddr
)), &macAddr
);
6078 if (ptr
!= mDNSNULL
&& !mDNSEthAddressIsZero(macAddr
))
6080 UpdateKeepaliveRData(m
, rr
, mDNSNULL
, mDNStrue
, (char *)(addrmap
->ethaddr
));
6084 m
->CurrentRecord
= rr
->next
;
6088 mDNSPlatformMemFree(addrmap
);
6092 mDNSexport mStatus
UpdateKeepaliveRData(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSBool updateMac
, char *ethAddr
)
6094 mDNSu16 newrdlength
;
6095 mDNSAddr laddr
= zeroAddr
;
6096 mDNSAddr raddr
= zeroAddr
;
6097 mDNSEthAddr eth
= zeroEthAddr
;
6098 mDNSIPPort lport
= zeroIPPort
;
6099 mDNSIPPort rport
= zeroIPPort
;
6100 mDNSu32 timeout
= 0;
6110 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6111 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6112 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
6113 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
6115 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, &raddr
, rport
.NotAnInteger
);
6116 return mStatus_UnknownErr
;
6121 if (laddr
.type
== mDNSAddrType_IPv4
)
6122 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
);
6124 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
);
6129 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6130 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6131 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6132 mDNSPlatformMemZero(&mti
, sizeof (mDNSTCPInfo
));
6133 ret
= mDNSPlatformRetrieveTCPInfo(&laddr
, &lport
, &raddr
, &rport
, &mti
);
6134 if (ret
!= mStatus_NoError
)
6136 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret
);
6139 if ((intf
!= mDNSNULL
) && (mti
.IntfId
!= intf
->InterfaceID
))
6141 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti
.IntfId
, intf
->InterfaceID
);
6142 return mStatus_BadParamErr
;
6145 if (laddr
.type
== mDNSAddrType_IPv4
)
6146 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
);
6148 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
);
6151 // Did we insert a null byte at the end ?
6152 if (newrdlength
== (sizeof(txt
.c
) - 1))
6154 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m
, rr
));
6155 return mStatus_NoMemoryErr
;
6158 // Include the length for the null byte at the end
6159 txt
.c
[0] = newrdlength
+ 1;
6160 // Account for the first length byte and the null byte at the end
6163 rdsize
= newrdlength
> sizeof(RDataBody
) ? newrdlength
: sizeof(RDataBody
);
6164 newrd
= (RData
*) mDNSPlatformMemAllocate(sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
6165 if (!newrd
) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr
; }
6167 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
6168 mDNSPlatformMemCopy(&newrd
->u
, txt
.c
, newrdlength
);
6170 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6171 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6172 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6173 // free that memory here before copying in the new data.
6174 if ( rr
->resrec
.rdata
!= &rr
->rdatastorage
)
6176 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m
, rr
));
6177 mDNSPlatformMemFree(rr
->resrec
.rdata
);
6179 SetNewRData(&rr
->resrec
, newrd
, newrdlength
); // Update our rdata
6181 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m
, rr
));
6182 return mStatus_NoError
;
6185 mDNSlocal
void SendSPSRegistrationForOwner(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
, const OwnerOptData
*const owner
)
6187 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
6188 const int sps
= intf
->NextSPSAttempt
/ 3;
6193 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6194 if (!intf
->SPSAddr
[sps
].type
)
6196 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6197 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
6198 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
6199 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6203 // Mark our mDNS records (not unicast records) for transfer to SPS
6204 if (mDNSOpaque16IsZero(id
))
6206 // We may have to register this record over multiple interfaces and we don't want to
6207 // overwrite the id. We send the registration over interface X with id "IDX" and before
6208 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6209 // for "IDX". Hence, we want to use the same ID across all interfaces.
6211 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6212 // option check below will set the same ID across the records from the same owner. Records
6213 // with different owner option gets different ID.
6214 msgid
= mDNS_NewMessageID(m
);
6215 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6217 if (!(rr
->AuthFlags
& AuthFlagsWakeOnly
) && rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
6219 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
6221 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6223 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
6224 // When we are registering on the first interface, rr->updateid is zero in which case
6225 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6226 // At the end, all the updates sent across all the interfaces with the same ID.
6227 if (mDNSOpaque16IsZero(rr
->updateid
))
6228 rr
->updateid
= msgid
;
6230 msgid
= rr
->updateid
;
6241 mDNSu8
*p
= m
->omsg
.data
;
6242 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6243 // For now we follow that same logic for SPS registrations too.
6244 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6245 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6246 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
6248 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6249 if (rr
->SendRNow
|| mDNSUpdateOkToSend(m
, rr
, intf
, scopeid
))
6251 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6254 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
6256 // If we can't update the keepalive record, don't send it
6257 if (mDNS_KeepaliveRecord(&rr
->resrec
) && (UpdateKeepaliveRData(m
, rr
, intf
, mDNSfalse
, mDNSNULL
) != mStatus_NoError
))
6259 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
6261 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
6263 rr
->SendRNow
= mDNSNULL
;
6267 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
6268 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6269 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
6270 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
6272 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
6275 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
));
6276 rr
->SendRNow
= mDNSNULL
;
6277 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
6278 rr
->LastAPTime
= m
->timenow
;
6279 // should be initialized above
6280 if (mDNSOpaque16IsZero(rr
->updateid
)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m
, rr
));
6281 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6282 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
6288 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
6292 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
6293 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
6294 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
6295 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
6296 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
6297 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
6298 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
6299 if (!owner
->HMAC
.l
[0]) // If no owner data,
6300 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]); // use our own interface information
6301 else // otherwise, use the owner data we were given
6303 opt
.resrec
.rdata
->u
.opt
[1].u
.owner
= *owner
;
6304 opt
.resrec
.rdata
->u
.opt
[1].opt
= kDNSOpt_Owner
;
6305 opt
.resrec
.rdata
->u
.opt
[1].optlen
= DNSOpt_Owner_Space(&owner
->HMAC
, &owner
->IMAC
) - 4;
6307 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
6308 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
6310 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
6315 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
6316 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
6317 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6318 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSfalse
);
6319 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
6320 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv4
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
6322 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6323 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_AAAA
;
6324 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
6331 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
6334 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
6337 mDNSlocal mDNSBool
RecordIsFirstOccurrenceOfOwner(mDNS
*const m
, const AuthRecord
*const rr
)
6340 for (ar
= m
->ResourceRecords
; ar
&& ar
!= rr
; ar
=ar
->next
)
6341 if (mDNSPlatformMemSame(&rr
->WakeUp
, &ar
->WakeUp
, sizeof(rr
->WakeUp
))) return mDNSfalse
;
6345 mDNSlocal
void mDNSCoreStoreProxyRR(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, AuthRecord
*const rr
)
6347 AuthRecord
*newRR
= (AuthRecord
*) mDNSPlatformMemAllocateClear(sizeof(*newRR
));
6348 if (newRR
== mDNSNULL
)
6350 LogSPS("%s : could not allocate memory for new resource record", __func__
);
6354 mDNS_SetupResourceRecord(newRR
, mDNSNULL
, InterfaceID
, rr
->resrec
.rrtype
,
6355 rr
->resrec
.rroriginalttl
, rr
->resrec
.RecordType
,
6356 rr
->ARType
, mDNSNULL
, mDNSNULL
);
6358 AssignDomainName(&newRR
->namestorage
, &rr
->namestorage
);
6359 newRR
->resrec
.rdlength
= DomainNameLength(rr
->resrec
.name
);
6360 newRR
->resrec
.namehash
= DomainNameHashValue(newRR
->resrec
.name
);
6361 newRR
->resrec
.rrclass
= rr
->resrec
.rrclass
;
6363 if (rr
->resrec
.rrtype
== kDNSType_A
)
6365 newRR
->resrec
.rdata
->u
.ipv4
= rr
->resrec
.rdata
->u
.ipv4
;
6367 else if (rr
->resrec
.rrtype
== kDNSType_AAAA
)
6369 newRR
->resrec
.rdata
->u
.ipv6
= rr
->resrec
.rdata
->u
.ipv6
;
6371 SetNewRData(&newRR
->resrec
, mDNSNULL
, 0);
6373 // Insert the new node at the head of the list.
6374 newRR
->next
= m
->SPSRRSet
;
6375 m
->SPSRRSet
= newRR
;
6376 LogSPS("%s : Storing proxy record : %s ", __func__
, ARDisplayString(m
, rr
));
6379 // Some records are interface specific and some are not. The ones that are supposed to be registered
6380 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6381 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6382 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6383 // registration on all the interfaces
6384 mDNSlocal
void SPSInitRecordsBeforeUpdate(mDNS
*const m
, mDNSOpaque64 updateIntID
, mDNSBool
*WakeOnlyService
)
6387 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID
.l
[1], updateIntID
.l
[0]);
6389 *WakeOnlyService
= mDNSfalse
;
6391 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6392 // make sure that the old sleep proxy records are removed.
6393 mDNSCoreFreeProxyRR(m
);
6395 // For records that are registered only on a specific interface, mark only that bit as it will
6396 // never be registered on any other interface. For others, it should be sent on all interfaces.
6397 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6399 ar
->updateIntID
= zeroOpaque64
;
6400 ar
->updateid
= zeroID
;
6401 if (AuthRecord_uDNS(ar
))
6405 if (ar
->AuthFlags
& AuthFlagsWakeOnly
)
6407 if (ar
->resrec
.RecordType
== kDNSRecordTypeShared
&& ar
->RequireGoodbye
)
6409 ar
->ImmedAnswer
= mDNSInterfaceMark
;
6410 *WakeOnlyService
= mDNStrue
;
6414 if (!ar
->resrec
.InterfaceID
)
6416 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID
.l
[1], updateIntID
.l
[0], ARDisplayString(m
, ar
));
6417 ar
->updateIntID
= updateIntID
;
6421 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6423 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, ar
->resrec
.InterfaceID
, mDNStrue
);
6424 if ((scopeid
< (sizeof(updateIntID
) * mDNSNBBY
)) && bit_get_opaque64(updateIntID
, scopeid
))
6426 bit_set_opaque64(ar
->updateIntID
, scopeid
);
6427 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid
, ar
->updateIntID
.l
[1],
6428 ar
->updateIntID
.l
[0], ARDisplayString(m
, ar
));
6432 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid
);
6435 // Store the A and AAAA records that we registered with the sleep proxy.
6436 // We will use this to prevent spurious name conflicts that may occur when we wake up
6437 if (ar
->resrec
.rrtype
== kDNSType_A
|| ar
->resrec
.rrtype
== kDNSType_AAAA
)
6439 mDNSCoreStoreProxyRR(m
, ar
->resrec
.InterfaceID
, ar
);
6444 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
)
6447 OwnerOptData owner
= zeroOwner
;
6449 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6451 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6453 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)) && RecordIsFirstOccurrenceOfOwner(m
, ar
))
6456 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6461 // RetrySPSRegistrations is called from SendResponses, with the lock held
6462 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
6465 NetworkInterfaceInfo
*intf
;
6467 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6468 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6469 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
6470 intf
->NextSPSAttemptTime
++;
6472 // Retry any record registrations that are due
6473 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6474 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6476 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6478 // If we still have registrations pending on this interface, send it now
6479 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6480 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6481 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6483 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
6484 SendSPSRegistration(m
, intf
, rr
->updateid
);
6489 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6490 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6491 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
6492 intf
->NextSPSAttempt
++;
6495 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
6497 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
6498 int sps
= (int)(question
- intf
->NetWakeResolve
);
6500 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
6502 if (!AddRecord
) return; // Don't care about REMOVE events
6503 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
6505 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6507 if (answer
->rrtype
== kDNSType_SRV
)
6509 // 1. Got the SRV record; now look up the target host's IP address
6510 mDNS_StopQuery(m
, question
);
6511 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
6512 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
6513 question
->qtype
= kDNSType_A
;
6514 mDNS_StartQuery(m
, question
);
6516 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
6518 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6519 mDNS_StopQuery(m
, question
);
6520 question
->ThisQInterval
= -1;
6521 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
6522 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
6524 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6527 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== 0)
6529 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6530 mDNS_StopQuery(m
, question
);
6531 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps
, question
->qname
.c
);
6532 question
->qtype
= kDNSType_AAAA
;
6533 mDNS_StartQuery(m
, question
);
6535 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
6537 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6538 mDNS_StopQuery(m
, question
);
6539 question
->ThisQInterval
= -1;
6540 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
6541 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
6543 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6548 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
6551 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6552 if (mDNS_KeepaliveRecord(&rr
->resrec
) || (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
)))
6557 #define WAKE_ONLY_SERVICE 1
6558 #define AC_ONLY_SERVICE 2
6560 #ifdef APPLE_OSX_mDNSResponder
6561 mDNSlocal
void SendGoodbyesForSelectServices(mDNS
*const m
, mDNSBool
*servicePresent
, mDNSu32 serviceType
)
6564 *servicePresent
= mDNSfalse
;
6566 // Mark all the records we need to deregister and send them
6567 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6569 // If the service type is wake only service and the auth flags match and requires a goodbye
6570 // OR if the service type is AC only and it is not a keepalive record,
6571 // mark the records we need to deregister and send them
6572 if ((serviceType
== WAKE_ONLY_SERVICE
&& (rr
->AuthFlags
& AuthFlagsWakeOnly
) &&
6573 rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
) ||
6574 (serviceType
== AC_ONLY_SERVICE
&& !mDNS_KeepaliveRecord(&rr
->resrec
)))
6576 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6577 *servicePresent
= mDNStrue
;
6583 #ifdef APPLE_OSX_mDNSResponder
6584 // This function is used only in the case of local NIC proxy. For external
6585 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6586 // walk the resource records.
6587 mDNSlocal
void SendGoodbyesForWakeOnlyService(mDNS
*const m
, mDNSBool
*WakeOnlyService
)
6589 return SendGoodbyesForSelectServices(m
, WakeOnlyService
, WAKE_ONLY_SERVICE
);
6591 #endif // APPLE_OSX_mDNSResponder
6594 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
, mDNSBool AllInterfaces
, mDNSBool unicast
)
6597 m
->SleepState
= SleepState_Sleeping
;
6599 // If AllInterfaces is not set, the caller has already marked it appropriately
6600 // on which interfaces this should be sent.
6603 NetworkInterfaceInfo
*intf
;
6604 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6606 intf
->SendGoodbyes
= 1;
6611 #ifndef UNICAST_DISABLED
6612 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
6613 #endif /* UNICAST_DISABLED */
6616 // Mark all the records we need to deregister and send them
6617 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6618 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
6619 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6624 * This function attempts to detect if multiple interfaces are on the same subnet.
6625 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6626 * IPv6 link local addresses that are configured by default on all interfaces make
6627 * it hard to make this determination
6629 * The 'real' fix for this would be to send out multicast packets over one interface
6630 * and conclude that multiple interfaces are on the same subnet only if these packets
6631 * are seen on other interfaces on the same system
6633 mDNSlocal mDNSBool
skipSameSubnetRegistration(mDNS
*const m
, mDNSInterfaceID
*regID
, mDNSu32 count
, mDNSInterfaceID intfid
)
6635 NetworkInterfaceInfo
*intf
;
6636 NetworkInterfaceInfo
*newIntf
;
6639 for (newIntf
= FirstInterfaceForID(m
, intfid
); newIntf
; newIntf
= newIntf
->next
)
6641 if ((newIntf
->InterfaceID
!= intfid
) ||
6642 (newIntf
->ip
.type
!= mDNSAddrType_IPv4
))
6646 for ( i
= 0; i
< count
; i
++)
6648 for (intf
= FirstInterfaceForID(m
, regID
[i
]); intf
; intf
= intf
->next
)
6650 if ((intf
->InterfaceID
!= regID
[i
]) ||
6651 (intf
->ip
.type
!= mDNSAddrType_IPv4
))
6655 if ((intf
->ip
.ip
.v4
.NotAnInteger
& intf
->mask
.ip
.v4
.NotAnInteger
) == (newIntf
->ip
.ip
.v4
.NotAnInteger
& newIntf
->mask
.ip
.v4
.NotAnInteger
))
6657 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__
, intf
->ifname
);
6666 mDNSlocal
void DoKeepaliveCallbacks(mDNS
*m
)
6668 // Loop through the keepalive records and callback with an error
6669 m
->CurrentRecord
= m
->ResourceRecords
;
6670 while (m
->CurrentRecord
)
6672 AuthRecord
*const rr
= m
->CurrentRecord
;
6673 if ((mDNS_KeepaliveRecord(&rr
->resrec
)) && (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
))
6675 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m
, rr
));
6676 if (rr
->RecordCallback
)
6677 rr
->RecordCallback(m
, rr
, mStatus_BadStateErr
);
6679 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
6680 m
->CurrentRecord
= rr
->next
;
6684 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6685 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
6687 mDNSBool SendGoodbyes
= mDNStrue
;
6688 mDNSBool WakeOnlyService
= mDNSfalse
;
6689 mDNSBool invokeKACallback
= mDNStrue
;
6690 const CacheRecord
*sps
[3] = { mDNSNULL
};
6691 mDNSOpaque64 updateIntID
= zeroOpaque64
;
6692 mDNSInterfaceID registeredIntfIDS
[128] = { 0 };
6693 mDNSu32 registeredCount
= 0;
6694 int skippedRegistrations
= 0;
6696 m
->NextScheduledSPRetry
= m
->timenow
;
6698 // Clear out the SCDynamic entry that stores the external SPS information
6699 mDNSPlatformClearSPSData();
6701 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6702 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
6703 else // If we have at least one advertised service
6705 NetworkInterfaceInfo
*intf
;
6706 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6708 mDNSBool skipFullSleepProxyRegistration
= mDNSfalse
;
6709 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6710 intf
->SendGoodbyes
= 0;
6712 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6714 if (!intf
->McastTxRx
|| mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
6716 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf
->ifname
);
6720 // If we are not capable of WOMP, then don't register with sleep proxy.
6722 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6723 // We might find sleep proxy servers in the cache and start a resolve on them.
6724 // But then if the interface goes away, we won't stop these questions because
6725 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6726 // to stop both the browse and resolve questions.
6729 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
6730 intf
->SendGoodbyes
= 1;
6731 skippedRegistrations
++;
6735 // Check if we have already registered with a sleep proxy for this subnet.
6736 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6737 // to the interface.
6738 if (skipSameSubnetRegistration(m
, registeredIntfIDS
, registeredCount
, intf
->InterfaceID
))
6740 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__
, intf
->ifname
);
6741 skipFullSleepProxyRegistration
= mDNStrue
;
6744 #if APPLE_OSX_mDNSResponder
6745 if (SupportsInNICProxy(intf
))
6747 mDNSBool keepaliveOnly
= mDNSfalse
;
6748 const mStatus err
= ActivateLocalProxy(intf
, skipFullSleepProxyRegistration
, &keepaliveOnly
);
6749 if (!skipFullSleepProxyRegistration
&& !err
)
6751 SendGoodbyesForWakeOnlyService(m
, &WakeOnlyService
);
6753 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6754 SendGoodbyes
= (keepaliveOnly
) ? mDNStrue
: mDNSfalse
;
6755 invokeKACallback
= mDNSfalse
;
6756 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
6757 // This will leave m->SleepState set to SleepState_Transferring,
6758 // which is okay because with no outstanding resolves, or updates in flight,
6759 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6761 // Setting this flag activates the SleepLimit which delays sleep by 5 seconds and
6762 // will allow the system to deregister any BTMM records.
6763 m
->NextScheduledSPRetry
= m
->timenow
+ (5 * mDNSPlatformOneSecond
);
6764 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6769 #endif // APPLE_OSX_mDNSResponder
6770 if (!skipFullSleepProxyRegistration
)
6772 #if APPLE_OSX_mDNSResponder
6773 // If on battery, do not attempt to offload to external sleep proxies
6774 if (m
->SystemWakeOnLANEnabled
== mDNS_WakeOnBattery
)
6776 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6779 #endif // APPLE_OSX_mDNSResponder
6780 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
6781 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6782 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
6787 SendGoodbyes
= mDNSfalse
;
6788 intf
->NextSPSAttempt
= 0;
6789 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6791 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6792 // Now we know for sure that we have to wait for registration to complete on this interface.
6793 if (scopeid
< (sizeof(updateIntID
) * mDNSNBBY
))
6794 bit_set_opaque64(updateIntID
, scopeid
);
6796 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6800 if (intf
->SPSAddr
[i
].type
)
6801 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
);
6802 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
6803 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
);
6805 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
6806 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
6807 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
6810 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
6811 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
6812 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
6813 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
6815 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6816 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6825 // If we have at least one interface on which we are registering with an external sleep proxy,
6826 // initialize all the records appropriately.
6827 if (!mDNSOpaque64IsZero(&updateIntID
))
6828 SPSInitRecordsBeforeUpdate(m
, updateIntID
, &WakeOnlyService
);
6830 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6831 // the records to a sleep proxy.
6832 if (invokeKACallback
)
6834 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6835 DoKeepaliveCallbacks(m
);
6838 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6839 // interfaces and also deregister unicast registrations.
6841 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6842 // for both multicast and unicast.
6844 // - If we skipped registrations on some interfaces, then we have already marked
6845 // them appropriately above. We don't need to send goodbyes for unicast as
6846 // we have registered with at least one sleep proxy.
6848 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6850 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6851 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6852 // at WakeOnlyServices first.
6855 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6856 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
6858 else if (skippedRegistrations
)
6860 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6861 SendSleepGoodbyes(m
, mDNSfalse
, mDNSfalse
);
6863 else if (WakeOnlyService
)
6865 // If we saw WakeOnly service above, send the goodbyes now.
6866 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6871 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6872 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6873 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6874 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
6878 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_INFO
,
6879 PUB_S
" (old state %d) at %d", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
6881 if (sleep
&& !m
->SleepState
) // Going to sleep
6884 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6887 mDNSu8 oldstate
= m
->SPSState
;
6888 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6890 #ifndef SPC_DISABLED
6891 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
6895 mDNS_ReclaimLockAfterCallback();
6897 #ifdef _LEGACY_NAT_TRAVERSAL_
6900 mDNSPlatformUDPClose(m
->SSDPSocket
);
6901 m
->SSDPSocket
= mDNSNULL
;
6904 m
->SleepState
= SleepState_Transferring
;
6905 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
6907 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6908 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
6909 "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
6910 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
6915 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
6916 m
->mDNSStats
.Sleeps
++;
6917 BeginSleepProcessing(m
);
6920 #ifndef UNICAST_DISABLED
6923 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S
") seq %d",
6925 m
->SleepState
== SleepState_Transferring
? "Transferring" :
6926 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
6929 else if (!sleep
) // Waking up
6934 NetworkInterfaceInfo
*intf
;
6935 mDNSs32 currtime
, diff
;
6938 // Reset SleepLimit back to 0 now that we're awake again.
6941 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6942 if (m
->SleepState
!= SleepState_Awake
)
6944 m
->SleepState
= SleepState_Awake
;
6946 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6947 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6948 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6949 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6950 m
->DelaySleep
= NonZeroTime(m
->timenow
+ kDarkWakeDelaySleep
);
6953 if (m
->SPSState
== 3)
6956 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
);
6958 m
->mDNSStats
.Wakes
++;
6959 // ... and the same for NextSPSAttempt
6960 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
6962 // Restart unicast and multicast queries
6963 mDNSCoreRestartQueries(m
);
6965 // and reactivtate service registrations
6966 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
6967 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
6968 "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
6970 // 2. Re-validate our cache records
6971 currtime
= mDNSPlatformUTC();
6973 diff
= currtime
- m
->TimeSlept
;
6974 FORALL_CACHERECORDS(slot
, cg
, cr
)
6976 // Temporary fix: For unicast cache records, look at how much time we slept.
6977 // Adjust the RecvTime by the amount of time we slept so that we age the
6978 // cache record appropriately. If it is expired already, purge. If there
6979 // is a network change that happens after the wakeup, we might purge the
6980 // cache anyways and this helps only in the case where there are no network
6981 // changes across sleep/wakeup transition.
6983 // Note: If there is a network/DNS server change that already happened and
6984 // these cache entries are already refreshed and we are getting a delayed
6985 // wake up notification, we might adjust the TimeRcvd based on the time slept
6986 // now which can cause the cache to purge pre-maturely. As this is not a very
6987 // common case, this should happen rarely.
6988 if (!cr
->resrec
.InterfaceID
)
6992 mDNSu32 uTTL
= RRUnadjustedTTL(cr
->resrec
.rroriginalttl
);
6993 const mDNSs32 remain
= uTTL
- (m
->timenow
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
6995 // -if we have slept longer than the remaining TTL, purge and start fresh.
6996 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6997 // a sufficiently big value which could cause the value to go into the future
6998 // because of the signed comparison of time. For this to happen, we should have been
6999 // sleeping really long (~24 days). For now, we want to be conservative and flush even
7000 // if we have slept for more than two days.
7002 if (diff
>= remain
|| diff
> (2 * 24 * 3600))
7004 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7005 "mDNSCoreMachineSleep: " PRI_S
": Purging cache entry SleptTime %d, Remaining TTL %d",
7006 CRDisplayString(m
, cr
), diff
, remain
);
7007 mDNS_PurgeCacheResourceRecord(m
, cr
);
7010 cr
->TimeRcvd
-= (diff
* mDNSPlatformOneSecond
);
7011 if (m
->timenow
- (cr
->TimeRcvd
+ ((mDNSs32
)uTTL
* mDNSPlatformOneSecond
)) >= 0)
7013 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7014 "mDNSCoreMachineSleep: " PRI_S
": Purging after adjusting the remaining TTL %d by %d seconds",
7015 CRDisplayString(m
, cr
), remain
, diff
);
7016 mDNS_PurgeCacheResourceRecord(m
, cr
);
7020 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7021 "mDNSCoreMachineSleep: " PRI_S
": Adjusted the remain ttl %u by %d seconds",
7022 CRDisplayString(m
, cr
), remain
, diff
);
7028 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
7032 // 3. Retrigger probing and announcing for all our authoritative records
7033 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7035 if (AuthRecord_uDNS(rr
))
7037 ActivateUnicastRegistration(m
, rr
);
7041 mDNSCoreRestartRegistration(m
, rr
, -1);
7045 // 4. Refresh NAT mappings
7046 // We don't want to have to assume that all hardware can necessarily keep accurate
7047 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7048 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7049 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7050 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7051 // than five seconds from now.
7052 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7053 RecreateNATMappings(m
, mDNSPlatformOneSecond
* 5);
7058 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
7062 NetworkInterfaceInfo
*intf
;
7066 if (m
->DelaySleep
) goto notready
;
7068 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7069 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
7071 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
7073 // See if we might need to retransmit any lost Sleep Proxy Registrations
7074 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7075 if (intf
->NextSPSAttempt
>= 0)
7077 if (now
- intf
->NextSPSAttemptTime
>= 0)
7079 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7080 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
7081 SendSPSRegistration(m
, intf
, zeroID
);
7082 // Don't need to "goto notready" here, because if we do still have record registrations
7083 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7086 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
7087 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
7090 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7091 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7093 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
7094 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
7096 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7097 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
7102 // Scan list of registered records
7103 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7104 if (!AuthRecord_uDNS(rr
))
7105 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7106 { 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
; }
7108 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7109 for (q
= m
->Questions
; q
; q
= q
->next
)
7110 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
7112 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
7116 // Scan list of registered records
7117 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7118 if (AuthRecord_uDNS(rr
))
7120 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
7121 { 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
; }
7129 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7130 // and allow up to ten seconds more to complete wide-area deregistration instead
7131 if (now
- m
->SleepLimit
>= 0)
7133 LogMsg("Failed to register with SPS, now sending goodbyes");
7135 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7136 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
7138 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7139 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
7140 mDNS_DeactivateNetWake_internal(m
, intf
);
7143 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7144 if (!AuthRecord_uDNS(rr
))
7145 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7147 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
));
7148 rr
->updateIntID
= zeroOpaque64
;
7151 // We'd really like to allow up to ten seconds more here,
7152 // but if we don't respond to the sleep notification within 30 seconds
7153 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7154 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7155 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7156 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7157 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
7159 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
7167 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
)
7171 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7172 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7173 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7174 // and if that happens we don't want to just give up and go back to sleep and never try again.
7175 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
7177 NATTraversalInfo
*nat
;
7178 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
7179 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
7181 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
7182 if (e
- t
> 0) e
= t
;
7183 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7184 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
7185 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
7186 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
7187 nat
->retryInterval
/ mDNSPlatformOneSecond
,
7188 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
7189 (t
- now
) / mDNSPlatformOneSecond
);
7192 // This loop checks both the time we need to renew wide-area registrations,
7193 // and the time we need to renew Sleep Proxy registrations
7194 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
7195 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
7197 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
7198 if (e
- t
> 0) e
= t
;
7199 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7200 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
7201 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
7202 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
7203 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
7209 // ***************************************************************************
7210 #if COMPILER_LIKES_PRAGMA_MARK
7212 #pragma mark - Packet Reception Functions
7215 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7217 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
7218 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
7220 mDNSu8
*responseptr
= response
->data
;
7221 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
7222 const mDNSu8
*ptr
= query
->data
;
7224 mDNSu32 maxttl
= (!InterfaceID
) ? mDNSMaximumUnicastTTLSeconds
: mDNSMaximumMulticastTTLSeconds
;
7227 // Initialize the response fields so we can answer the questions
7228 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
7231 // *** 1. Write out the list of questions we are actually going to answer with this packet
7235 maxttl
= kStaticCacheTTL
;
7236 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7239 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
7240 if (!ptr
) return(mDNSNULL
);
7242 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
7244 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
7245 { // then put the question in the question section
7246 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
7247 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
7248 break; // break out of the ResponseRecords loop, and go on to the next question
7253 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
7257 // *** 2. Write Answers
7259 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7260 if (rr
->NR_AnswerTo
)
7262 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
7263 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7264 if (p
) responseptr
= p
;
7265 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
7269 // *** 3. Write Additionals
7271 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7272 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
7274 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
7275 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7276 if (p
) responseptr
= p
;
7277 else debugf("GenerateUnicastResponse: No more space for additionals");
7280 return(responseptr
);
7283 // AuthRecord *our is our Resource Record
7284 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7285 // Returns 0 if there is no conflict
7286 // Returns +1 if there was a conflict and we won
7287 // Returns -1 if there was a conflict and we lost and have to rename
7288 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
7290 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
7291 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
7292 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7293 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7295 #if defined(__clang_analyzer__)
7296 // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7297 // There are no clear indications from the analyzer of the cause of the supposed problem.
7298 mDNSPlatformMemZero(ourdata
, 1);
7299 mDNSPlatformMemZero(pktdata
, 1);
7301 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
7302 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
7303 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
7304 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
7306 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
7307 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
7308 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
7309 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
7311 LogMsg("CompareRData ERROR: Invalid state");
7315 mDNSlocal mDNSBool
PacketRecordMatches(const AuthRecord
*const rr
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7317 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7319 const AuthRecord
*r2
= rr
;
7320 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
7321 if (r2
== master
) return(mDNStrue
);
7326 // See if we have an authoritative record that's identical to this packet record,
7327 // whose canonical DependentOn record is the specified master record.
7328 // The DependentOn pointer is typically used for the TXT record of service registrations
7329 // It indicates that there is no inherent conflict detection for the TXT record
7330 // -- it depends on the SRV record to resolve name conflicts
7331 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7332 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7333 // If the record has no DependentOn, then just return that record's pointer
7334 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7335 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7337 const AuthRecord
*r1
;
7338 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
7340 if (PacketRecordMatches(r1
, pktrr
, master
)) return(mDNStrue
);
7342 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
7344 if (PacketRecordMatches(r1
, pktrr
, master
)) return(mDNStrue
);
7349 // Find the canonical RRSet pointer for this RR received in a packet.
7350 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7351 // pointers (if any) to make sure we return the canonical member of this name/type/class
7352 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7353 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
7355 const AuthRecord
*rr
;
7356 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7358 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7360 return(rr
->RRSet
? rr
->RRSet
: rr
);
7366 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7367 // as one of our records (our) but different rdata.
7368 // 1. If our record is not a type that's supposed to be unique, we don't care.
7369 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7370 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7371 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7372 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7373 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7374 // are members of the same RRSet, then this is not a conflict.
7375 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
7377 // If not supposed to be unique, not a conflict
7378 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
7380 // If a dependent record, not a conflict
7381 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
7384 // If the pktrr matches a member of ourset, not a conflict
7385 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
7386 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
7387 if (pktset
== ourset
) return(mDNSfalse
);
7389 // For records we're proxying, where we don't know the full
7390 // relationship between the records, having any matching record
7391 // in our AuthRecords list is sufficient evidence of non-conflict
7392 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
7395 // Okay, this is a conflict
7399 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7400 // the record list and/or question list.
7401 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7402 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7403 DNSQuestion
*q
, AuthRecord
*our
)
7406 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
7407 mDNSBool FoundUpdate
= mDNSfalse
;
7409 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
7411 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
7413 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& CacheRecordAnswersQuestion(&m
->rec
.r
, q
))
7415 FoundUpdate
= mDNStrue
;
7416 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
7418 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
7419 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
7420 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
7423 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
7424 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7425 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7427 // 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.
7428 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7429 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7432 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
7433 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
7434 our
->AnnounceCount
= InitialAnnounceCount
;
7435 InitializeLastAPTime(m
, our
);
7442 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7443 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7447 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7450 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
7452 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7455 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
7457 CacheGroup
*cg
= CacheGroupForRecord(m
, pktrr
);
7460 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7462 if (!pktrr
->InterfaceID
)
7464 const mDNSu32 id1
= (pktrr
->rDNSServer
? pktrr
->rDNSServer
->resGroupID
: 0);
7465 const mDNSu32 id2
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
7466 match
= (id1
== id2
);
7468 else match
= (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
);
7470 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
7474 mDNSlocal
void DeregisterProxyRecord(mDNS
*const m
, AuthRecord
*const rr
)
7476 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7477 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
7478 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7479 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7482 mDNSlocal
void ClearKeepaliveProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
, const mDNSInterfaceID InterfaceID
)
7484 if (m
->CurrentRecord
)
7485 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7486 m
->CurrentRecord
= thelist
;
7488 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7489 // clean up the keepalive record.
7490 while (m
->CurrentRecord
)
7492 AuthRecord
*const rr
= m
->CurrentRecord
;
7493 if (InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7495 if (mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
7497 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7498 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7499 DeregisterProxyRecord(m
, rr
);
7502 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7503 // new records could have been added to the end of the list as a result of that call.
7504 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7505 m
->CurrentRecord
= rr
->next
;
7509 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7510 // to check our lists and discard any stale duplicates of this record we already have
7511 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7513 if (m
->CurrentRecord
)
7514 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7515 m
->CurrentRecord
= thelist
;
7516 while (m
->CurrentRecord
)
7518 AuthRecord
*const rr
= m
->CurrentRecord
;
7519 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7520 if (IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
7522 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7523 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7524 DeregisterProxyRecord(m
, rr
);
7526 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7527 // new records could have been added to the end of the list as a result of that call.
7528 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7529 m
->CurrentRecord
= rr
->next
;
7533 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7534 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7536 if (m
->CurrentRecord
)
7537 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7538 m
->CurrentRecord
= thelist
;
7539 while (m
->CurrentRecord
)
7541 AuthRecord
*const rr
= m
->CurrentRecord
;
7542 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7543 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
7545 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
7547 // We don't do this here because we know that the host is waking up at this point, so we don't send
7548 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7549 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7550 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7551 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7552 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
7553 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
7556 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7557 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
7558 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7559 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
7560 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7561 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
7562 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7563 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7565 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7566 // new records could have been added to the end of the list as a result of that call.
7567 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7568 m
->CurrentRecord
= rr
->next
;
7572 // ProcessQuery examines a received query to see if we have any answers to give
7573 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7574 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
7575 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
7577 const mDNSBool FromLocalSubnet
= mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
7578 AuthRecord
*ResponseRecords
= mDNSNULL
;
7579 AuthRecord
**nrp
= &ResponseRecords
;
7582 mDNSBool notD2D
= !mDNSPlatformInterfaceIsD2D(InterfaceID
); // We don't run the POOF algorithm on D2D interfaces.
7583 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
7584 CacheRecord
**eap
= &ExpectedAnswers
;
7585 #endif // POOF_ENABLED
7587 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
7588 DNSQuestion
**dqp
= &DupQuestions
;
7589 mDNSs32 delayresponse
= 0;
7590 mDNSBool SendLegacyResponse
= mDNSfalse
;
7592 mDNSu8
*responseptr
= mDNSNULL
;
7595 CacheRecord
*McastNSEC3Records
= mDNSNULL
;
7598 // *** 1. Look in Additional Section for an OPT record
7600 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
7603 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
7604 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
7606 const rdataOPT
*opt
;
7607 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
7608 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7609 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7610 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
7611 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
7613 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
7614 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
7617 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7621 // Look in Authority Section for NSEC3 record
7624 mDNSParseNSEC3Records(m
, query
, end
, InterfaceID
, &McastNSEC3Records
);
7627 // *** 2. Parse Question Section and mark potential answers
7630 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7632 mDNSBool QuestionNeedsMulticastResponse
;
7633 int NumAnswersForThisQuestion
= 0;
7634 AuthRecord
*NSECAnswer
= mDNSNULL
;
7635 DNSQuestion pktq
, *q
;
7636 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
7637 if (!ptr
) goto exit
;
7639 // The only queries that *need* a multicast response are:
7640 // * Queries sent via multicast
7642 // * that don't have the kDNSQClass_UnicastResponse bit set
7643 // These queries need multicast responses because other clients will:
7644 // * suppress their own identical questions when they see these questions, and
7645 // * expire their cache records if they don't see the expected responses
7646 // For other queries, we may still choose to send the occasional multicast response anyway,
7647 // to keep our neighbours caches warm, and for ongoing conflict detection.
7648 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
7650 if (pktq
.qclass
& kDNSQClass_UnicastResponse
)
7651 m
->mDNSStats
.UnicastBitInQueries
++;
7653 m
->mDNSStats
.NormalQueries
++;
7655 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7656 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
7658 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7659 // can result in user callbacks which may change the record list and/or question list.
7660 // Also note: we just mark potential answer records here, without trying to build the
7661 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7662 // from that list while we're in the middle of trying to build it.
7663 if (m
->CurrentRecord
)
7664 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7665 m
->CurrentRecord
= m
->ResourceRecords
;
7666 while (m
->CurrentRecord
)
7668 rr
= m
->CurrentRecord
;
7669 m
->CurrentRecord
= rr
->next
;
7670 if (AnyTypeRecordAnswersQuestion(rr
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
7672 m
->mDNSStats
.MatchingAnswersForQueries
++;
7673 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
7675 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
7676 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
7677 else if (ResourceRecordIsValidAnswer(rr
))
7679 NumAnswersForThisQuestion
++;
7681 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7682 // unicast answer back to the source, because timeliness in answering probes is important.
7685 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7686 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7687 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7688 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7689 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7690 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7691 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
7693 // We only mark this question for sending if it is at least one second since the last time we multicast it
7694 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7695 // This is to guard against the case where someone blasts us with queries as fast as they can.
7696 if ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) >= (mDNSu32
)mDNSPlatformOneSecond
||
7697 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
7698 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7700 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: NR_AnswerUnicast
;
7703 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
7705 // If we don't have any answers for this question, but we do own another record with the same name,
7706 // then we'll want to mark it to generate an NSEC record on this interface
7707 if (!NSECAnswer
) NSECAnswer
= rr
;
7712 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
7714 NumAnswersForThisQuestion
++;
7715 NSECAnswer
->SendNSECNow
= InterfaceID
;
7716 m
->NextScheduledResponse
= m
->timenow
;
7719 // If we couldn't answer this question, someone else might be able to,
7720 // so use random delay on response to reduce collisions
7721 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7723 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
)
7724 m
->mDNSStats
.KnownAnswerMultiplePkts
++;
7725 // We only do the following accelerated cache expiration and duplicate question suppression processing
7726 // for non-truncated multicast queries with multicast responses.
7727 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7728 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7729 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7730 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7735 CacheGroup
*cg
= CacheGroupForName(m
, pktq
.qnamehash
, &pktq
.qname
);
7738 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7739 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7740 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
7742 if (SameNameCacheRecordAnswersQuestion(cr
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
7744 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
7747 eap
= &cr
->NextInKAList
;
7752 #endif // POOF_ENABLED
7754 // Check if this question is the same as any of mine.
7755 // We only do this for non-truncated queries. Right now it would be too complicated to try
7756 // to keep track of duplicate suppression state between multiple packets, especially when we
7757 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7758 for (q
= m
->Questions
; q
; q
=q
->next
)
7760 if (ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
7762 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
7764 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
7766 if (q
->qtype
== pktq
.qtype
&&
7767 q
->qclass
== pktq
.qclass
&&
7768 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
7769 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
7778 // *** 3. Now we can safely build the list of marked answers
7780 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
7781 if (rr
->NR_AnswerTo
) // If we marked the record...
7782 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
7785 // *** 4. Add additional records
7787 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
7790 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7792 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
7794 // Get the record...
7795 CacheRecord
*ourcacherr
;
7796 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
7797 if (!ptr
) goto exit
;
7798 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
7800 // See if this Known-Answer suppresses any of our currently planned answers
7801 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7803 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7805 m
->mDNSStats
.KnownAnswerSuppressions
++;
7806 rr
->NR_AnswerTo
= mDNSNULL
;
7807 rr
->NR_AdditionalTo
= mDNSNULL
;
7811 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7812 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
7814 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7815 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7817 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7819 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
7821 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7823 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
7825 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
7827 m
->mDNSStats
.KnownAnswerSuppressions
++;
7828 rr
->ImmedAnswer
= mDNSNULL
;
7829 rr
->ImmedUnicast
= mDNSfalse
;
7830 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7831 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
7837 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
7842 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7843 // any records that are suppressed by the Known Answer list in this packet.
7844 eap
= &ExpectedAnswers
;
7847 CacheRecord
*cr
= *eap
;
7848 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
7849 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
7850 else eap
= &cr
->NextInKAList
;
7853 #endif // POOF_ENABLED
7855 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7858 dqp
= &DupQuestions
;
7861 DNSQuestion
*q
= *dqp
;
7862 if (CacheRecordAnswersQuestion(&m
->rec
.r
, q
))
7863 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
7864 else dqp
= &q
->NextInDQList
;
7868 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7872 // *** 6. Cancel any additionals that were added because of now-deleted records
7874 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7875 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
7876 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
7879 // *** 7. Mark the send flags on the records we plan to send
7881 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7883 if (rr
->NR_AnswerTo
)
7885 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
7886 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
7888 // If it's been one TTL/4 since we multicast this, then send a multicast response
7889 // for conflict detection, etc.
7890 if ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) >= (mDNSu32
)TicksTTL(rr
)/4)
7892 SendMulticastResponse
= mDNStrue
;
7893 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7894 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7895 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7896 if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7898 m
->mDNSStats
.UnicastDemotedToMulticast
++;
7899 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7903 // If the client insists on a multicast response, then we'd better send one
7904 if (rr
->NR_AnswerTo
== NR_AnswerMulticast
)
7906 m
->mDNSStats
.MulticastResponses
++;
7907 SendMulticastResponse
= mDNStrue
;
7909 else if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7911 m
->mDNSStats
.UnicastResponses
++;
7912 SendUnicastResponse
= mDNStrue
;
7914 else if (rr
->NR_AnswerTo
)
7916 SendLegacyResponse
= mDNStrue
;
7919 if (SendMulticastResponse
|| SendUnicastResponse
)
7921 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7922 rr
->ImmedAnswerMarkTime
= m
->timenow
;
7924 m
->NextScheduledResponse
= m
->timenow
;
7925 // If we're already planning to send this on another interface, just send it on all interfaces
7926 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
7927 rr
->ImmedAnswer
= mDNSInterfaceMark
;
7930 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
7931 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
7932 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7934 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
7935 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
7937 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7939 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
7940 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
7944 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7945 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7946 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7947 // else, for a simple unique record reply, we can reply immediately; no need for delay
7948 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
7949 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7951 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== NR_AnswerMulticast
)
7953 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7954 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7955 // then the earlier client is out of luck
7956 rr
->ImmedAdditional
= InterfaceID
;
7957 // No need to set m->NextScheduledResponse here
7958 // We'll send these additional records when we send them, or not, as the case may be
7963 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7965 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
7967 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7968 mDNSs32 oldss
= m
->SuppressSending
;
7969 if (oldss
&& delayresponse
)
7970 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
7972 // Pick a random delay:
7973 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7974 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7975 // This is an integer value, with resolution determined by the platform clock rate.
7976 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7977 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7978 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7979 // on platforms where the native clock rate is less than fifty ticks per second,
7980 // we still guarantee that the final calculated delay is at least one platform tick.
7981 // We want to make sure we don't ever allow the delay to be zero ticks,
7982 // because if that happens we'll fail the Bonjour Conformance Test.
7983 // Our final computed delay is 20-120ms for normal delayed replies,
7984 // or 400-500ms in the case of multi-packet known-answer lists.
7985 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
7986 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
7987 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7988 if (oldss
&& delayresponse
)
7989 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
7994 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7996 if (SendLegacyResponse
)
7997 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
8000 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8003 // *** 10. Finally, clear our link chains ready for use next time
8005 while (ResponseRecords
)
8007 rr
= ResponseRecords
;
8008 ResponseRecords
= rr
->NextResponse
;
8009 rr
->NextResponse
= mDNSNULL
;
8010 rr
->NR_AnswerTo
= mDNSNULL
;
8011 rr
->NR_AdditionalTo
= mDNSNULL
;
8015 while (ExpectedAnswers
&& notD2D
)
8017 CacheRecord
*cr
= ExpectedAnswers
;
8018 ExpectedAnswers
= cr
->NextInKAList
;
8019 cr
->NextInKAList
= mDNSNULL
;
8021 // For non-truncated queries, we can definitively say that we should expect
8022 // to be seeing a response for any records still left in the ExpectedAnswers list
8023 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
8024 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
* 3/4)
8026 cr
->UnansweredQueries
++;
8027 cr
->LastUnansweredTime
= m
->timenow
;
8028 if (cr
->UnansweredQueries
> 1)
8029 debugf("ProcessQuery: UnansweredQueries %lu %s", cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
8030 SetNextCacheCheckTimeForRecord(m
, cr
);
8033 // If we've seen multiple unanswered queries for this record,
8034 // then mark it to expire in five seconds if we don't get a response by then.
8035 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
8037 // Only show debugging message if this record was not about to expire anyway
8038 if (RRExpireTime(cr
) - m
->timenow
> (mDNSs32
) kDefaultReconfirmTimeForNoAnswer
* 4 / 3 + mDNSPlatformOneSecond
)
8039 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8040 cr
->UnansweredQueries
, InterfaceID
, (RRExpireTime(cr
) - m
->timenow
+ mDNSPlatformOneSecond
-1) / mDNSPlatformOneSecond
, CRDisplayString(m
, cr
));
8042 m
->mDNSStats
.PoofCacheDeletions
++;
8043 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
8046 #endif // POOF_ENABLED
8048 while (DupQuestions
)
8050 DNSQuestion
*q
= DupQuestions
;
8051 DupQuestions
= q
->NextInDQList
;
8052 q
->NextInDQList
= mDNSNULL
;
8053 RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
8054 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
8055 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6");
8058 if (McastNSEC3Records
)
8060 debugf("ProcessQuery: McastNSEC3Records not used");
8061 FreeNSECRecords(m
, McastNSEC3Records
);
8064 return(responseptr
);
8067 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
8068 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8069 const mDNSInterfaceID InterfaceID
)
8071 mDNSu8
*responseend
= mDNSNULL
;
8072 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
8073 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8075 if (!dstaddr
|| (!InterfaceID
&& mDNSAddrIsDNSMulticast(dstaddr
)))
8077 const char *const reason
= !dstaddr
? "Received over TCP connection" : "Multicast, but no InterfaceID";
8078 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8079 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8080 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8081 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8082 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8083 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8084 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
, reason
);
8088 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8089 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8090 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8091 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8092 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8093 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8094 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
8096 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
8097 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
8099 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
8101 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8102 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
8103 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
8104 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
8105 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
8106 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
8111 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
8115 (void)srcaddr
; // Unused
8116 for (s
= m
->DNSServers
; s
; s
= s
->next
)
8117 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
8122 struct UDPSocket_struct
8124 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8127 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
, const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
, DNSQuestion
** suspiciousQ
)
8130 for (q
= m
->Questions
; q
; q
=q
->next
)
8132 if (!tcp
&& !q
->LocalSocket
) continue;
8133 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
8134 q
->qtype
== question
->qtype
&&
8135 q
->qclass
== question
->qclass
&&
8136 q
->qnamehash
== question
->qnamehash
&&
8137 SameDomainName(&q
->qname
, &question
->qname
))
8139 if (mDNSSameOpaque16(q
->TargetQID
, id
)) return(q
);
8142 // Everything but the QIDs match up, should we be suspicious?
8143 if (!tcp
&& suspiciousQ
)
8145 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
8146 if (mDNSSameOpaque16(q
->LastTargetQID
, id
)) // Only be suspicious if this is also not the "last" used QID (on a DNS server set change)
8148 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
, "Ignored but not suspicious LastTargetQID %d TargetQID %d", mDNSVal16(q
->LastTargetQID
), mDNSVal16(q
->TargetQID
));
8161 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8162 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8163 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
8164 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
8169 for (q
= m
->Questions
; q
; q
=q
->next
)
8171 if (!q
->DuplicateOf
&& ResourceRecordAnswersUnicastResponse(&rr
->resrec
, q
))
8173 if (!mDNSOpaque16IsZero(q
->TargetQID
))
8175 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
8177 if (mDNSSameOpaque16(q
->TargetQID
, id
))
8182 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
8186 srcp
= q
->tcpSrcPort
;
8188 if (mDNSSameIPPort(srcp
, port
)) return(q
);
8190 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8191 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8192 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8193 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8194 q
->qname
.c
, DNSTypeName(q
->qtype
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
8200 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
8208 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8209 // Currently this applies only to rdata types containing more than one domainname,
8210 // or types where the domainname is not the last item in the structure.
8211 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
8215 case kDNSType_SOA
: return sizeof(rdataSOA
);
8216 case kDNSType_RP
: return sizeof(rdataRP
);
8217 case kDNSType_PX
: return sizeof(rdataPX
);
8218 default: return rr
->rdlength
;
8222 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
, mDNSBool Add
, const mDNSAddr
*sourceAddress
)
8224 CacheRecord
*rr
= mDNSNULL
;
8225 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
8227 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
8229 //if (RDLength > InlineCacheRDSize)
8230 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8232 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
8233 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
8234 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
8237 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
8238 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
8239 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
8240 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
8241 rr
->resrec
.mortality
= Mortality_Mortal
;
8243 rr
->DelayDelivery
= delay
;
8245 // If this is an oversized record with external storage allocated, copy rdata to external storage
8246 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
8247 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8248 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
8249 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8250 if (RDLength
> InlineCacheRDSize
)
8251 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
8253 rr
->next
= mDNSNULL
; // Clear 'next' pointer
8254 rr
->nsec
= mDNSNULL
;
8258 rr
->sourceAddress
= *sourceAddress
;
8260 if (!rr
->resrec
.InterfaceID
)
8262 m
->rrcache_totalused_unicast
+= rr
->resrec
.rdlength
;
8263 if (DNSSECRecordType(rr
->resrec
.rrtype
))
8264 BumpDNSSECStats(m
, kStatsActionIncrement
, kStatsTypeMemoryUsage
, rr
->resrec
.rdlength
);
8269 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
8270 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
8271 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8275 // Can't use the "cg->name" if we are not adding to the cache as the
8276 // CacheGroup may be released anytime if it is empty
8277 domainname
*name
= (domainname
*) mDNSPlatformMemAllocate(DomainNameLength(cg
->name
));
8280 AssignDomainName(name
, cg
->name
);
8281 rr
->resrec
.name
= name
;
8285 ReleaseCacheRecord(m
, rr
);
8286 NoCacheAnswer(m
, &m
->rec
.r
);
8294 mDNSlocal
void RefreshCacheRecordCacheGroupOrder(CacheGroup
*cg
, CacheRecord
*cr
)
8295 { // Move the cache record to the tail of the cache group to maintain a fresh ordering
8296 if (cg
->rrcache_tail
!= &cr
->next
) // If not already at the tail
8299 for (rp
= &cg
->members
; *rp
; rp
= &(*rp
)->next
)
8301 if (*rp
== cr
) // This item points to this record
8303 *rp
= cr
->next
; // Remove this record
8307 cr
->next
= mDNSNULL
; // This record is now last
8308 *(cg
->rrcache_tail
) = cr
; // Append this record to tail of cache group
8309 cg
->rrcache_tail
= &(cr
->next
); // Advance tail pointer
8313 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
8315 rr
->TimeRcvd
= m
->timenow
;
8316 rr
->resrec
.rroriginalttl
= ttl
;
8317 rr
->UnansweredQueries
= 0;
8318 if (rr
->resrec
.mortality
!= Mortality_Mortal
) rr
->resrec
.mortality
= Mortality_Immortal
;
8319 SetNextCacheCheckTimeForRecord(m
, rr
);
8322 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
8325 CacheGroup
*cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
8326 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
8327 if (rr
->CRActiveQuestion
== q
)
8329 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8330 RefreshCacheRecord(m
, rr
, lease
);
8334 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
8336 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
8337 else if (LLQType
== uDNS_LLQ_Events
)
8339 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8340 if (ttl
== 0xFFFFFFFF) ttl
= 0;
8341 else ttl
= kLLQ_DefLease
;
8343 else // else not LLQ (standard uDNS response)
8345 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8346 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8347 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
8349 ttl
= RRAdjustTTL(ttl
);
8351 // For mDNS, TTL zero means "delete this record"
8352 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8353 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8354 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8355 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8356 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8357 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8358 // (with the current code) result in the server having even less than three seconds to respond
8359 // before we deleted the record and reported a "remove" event to any active questions.
8360 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8361 // then things really break (e.g. we end up making a negative cache entry).
8362 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8363 if (ttl
< 15) ttl
= 15;
8369 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8371 mDNSlocal mDNSBool
IsResponseAcceptable(mDNS
*const m
, const CacheRecord
*crlist
, DNSQuestion
*q
, mDNSBool
*nseclist
)
8373 CacheRecord
*const newcr
= &m
->rec
.r
;
8374 ResourceRecord
*rr
= &newcr
->resrec
;
8375 const CacheRecord
*cr
;
8377 *nseclist
= mDNSfalse
;
8378 for (cr
= crlist
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
8380 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
8381 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8382 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8383 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8384 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8385 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8387 if (target
&& cr
->resrec
.rdatahash
== rr
->namehash
&& SameDomainName(target
, rr
->name
))
8389 LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr
->name
->c
, CRDisplayString(m
, cr
));
8394 // Either the question requires validation or we are validating a response with DNSSEC in which case
8395 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8396 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8397 // too. nseclist is set if they have to be cached as part of the negative cache record.
8398 if (q
&& DNSSECQuestion(q
))
8400 mDNSBool same
= SameDomainName(&q
->qname
, rr
->name
);
8401 if (same
&& (q
->qtype
== rr
->rrtype
|| rr
->rrtype
== kDNSType_CNAME
))
8403 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q
->qtype
),
8404 CRDisplayString(m
, newcr
));
8407 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8408 // "nseclist" is set
8409 if (rr
->rrtype
== kDNSType_RRSIG
)
8411 RDataBody2
*const rdb
= (RDataBody2
*)newcr
->smallrdatastorage
.data
;
8412 rdataRRSig
*rrsig
= &rdb
->rrsig
;
8413 mDNSu16 typeCovered
= swap16(rrsig
->typeCovered
);
8415 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8416 // would match the qtype and they are cached normally as they are not used to prove the
8417 // non-existence of any name. In that case, it is like any other normal dnssec validation
8418 // and hence nseclist should not be set.
8420 if (same
&& ((typeCovered
== q
->qtype
) || (typeCovered
== kDNSType_CNAME
)))
8422 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m
, newcr
),
8423 DNSTypeName(q
->qtype
));
8426 else if (typeCovered
== kDNSType_NSEC
|| typeCovered
== kDNSType_NSEC3
)
8428 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m
, newcr
), DNSTypeName(typeCovered
));
8429 *nseclist
= mDNStrue
;
8432 else if (typeCovered
== kDNSType_SOA
)
8434 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m
, newcr
));
8435 *nseclist
= mDNStrue
;
8438 else return mDNSfalse
;
8440 if (rr
->rrtype
== kDNSType_NSEC
)
8442 if (!UNICAST_NSEC(rr
))
8444 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m
, newcr
));
8447 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8448 *nseclist
= mDNStrue
;
8451 if (rr
->rrtype
== kDNSType_SOA
)
8453 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8454 *nseclist
= mDNStrue
;
8457 else if (rr
->rrtype
== kDNSType_NSEC3
)
8459 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m
, newcr
));
8460 *nseclist
= mDNStrue
;
8467 mDNSlocal
void FreeNSECRecords(mDNS
*const m
, CacheRecord
*NSECRecords
)
8469 CacheRecord
*rp
, *next
;
8471 for (rp
= NSECRecords
; rp
; rp
= next
)
8474 ReleaseCacheRecord(m
, rp
);
8478 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8479 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8480 mDNSlocal
void mDNSCoreReceiveNoDNSSECAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
8481 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
)
8484 const mDNSu8
*ptr
= response
->data
;
8486 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8489 DNSQuestion
*qptr
= mDNSNULL
;
8490 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &pktq
);
8491 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &pktq
, !dstaddr
, mDNSNULL
)) &&
8492 qptr
->ValidatingResponse
)
8494 DNSQuestion
*next
, *q
;
8496 if (qptr
->DuplicateOf
)
8497 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr
->qname
.c
, DNSTypeName(qptr
->qtype
));
8499 // Be careful to call the callback for duplicate questions first and then the original
8500 // question. If we called the callback on the original question, it could stop and
8501 // a duplicate question would become the original question.
8502 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8503 for (q
= qptr
->next
; q
&& q
!= m
->NewQuestions
; q
= next
)
8506 if (q
->DuplicateOf
== qptr
)
8508 if (q
->ValidatingResponse
)
8509 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q
->qname
.c
, DNSTypeName(q
->qtype
));
8511 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q
->qname
.c
, DNSTypeName(q
->qtype
));
8512 if (q
->QuestionCallback
)
8513 q
->QuestionCallback(m
, q
, mDNSNULL
, QC_nodnssec
);
8516 if (qptr
->QuestionCallback
)
8517 qptr
->QuestionCallback(m
, qptr
, mDNSNULL
, QC_nodnssec
);
8518 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8523 mDNSlocal
void mDNSCoreReceiveNoUnicastAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
, const mDNSAddr
*dstaddr
,
8524 mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
, uDNS_LLQType LLQType
, mDNSu8 rcode
, CacheRecord
*NSECRecords
)
8527 const mDNSu8
*ptr
= response
->data
;
8528 CacheRecord
*SOARecord
= mDNSNULL
;
8530 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8533 DNSQuestion
*qptr
= mDNSNULL
;
8534 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
8535 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
, mDNSNULL
)))
8537 CacheRecord
*cr
, *neg
= mDNSNULL
;
8538 CacheGroup
*cg
= CacheGroupForName(m
, q
.qnamehash
, &q
.qname
);
8539 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
8541 if (SameNameCacheRecordAnswersQuestion(cr
, qptr
))
8543 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8544 if (RRExpireTime(cr
) - m
->timenow
> 0) break;
8545 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8546 if (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= cr
;
8549 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8550 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8551 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8552 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8553 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8554 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8555 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8556 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8557 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8558 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8560 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8561 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8562 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8563 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8564 // do the appropriate thing. This negative response is also needed for appending new search domains.
8565 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
8569 const mDNSBool noData
= ((response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
) == kDNSFlag1_RC_NoErr
) ? mDNStrue
: mDNSfalse
;
8570 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8571 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME
" (" PUB_S
")",
8572 q
.request_id
, mDNSVal16(q
.TargetQID
), DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
8573 m
->CurrentQuestion
= qptr
;
8574 // We are not creating a cache record in this case, we need to pass back
8575 // the error we got so that the proxy code can return the right one to
8577 if (qptr
->ProxyQuestion
)
8578 qptr
->responseFlags
= response
->h
.flags
;
8579 GenerateNegativeResponseEx(m
, mDNSInterface_Any
, QC_forceresponse
, noData
);
8580 m
->CurrentQuestion
= mDNSNULL
;
8584 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8585 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME
" (" PUB_S
")",
8586 q
.request_id
, mDNSVal16(q
.TargetQID
), DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
8593 // We start off assuming a negative caching TTL of 60 seconds
8594 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8595 mDNSu32 negttl
= 60;
8597 const domainname
*name
= &q
.qname
;
8598 mDNSu32 hash
= q
.qnamehash
;
8600 // Special case for our special Microsoft Active Directory "local SOA" check.
8601 // Some cheap home gateways don't include an SOA record in the authority section when
8602 // they send negative responses, so we don't know how long to cache the negative result.
8603 // Because we don't want to keep hitting the root name servers with our query to find
8604 // if we're on a network using Microsoft Active Directory using "local" as a private
8605 // internal top-level domain, we make sure to cache the negative result for at least one day.
8606 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
8608 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8609 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
8611 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8612 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
8614 CacheGroup
*cgSOA
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
8615 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
8616 mDNSu32 ttl_s
= soa
->min
;
8617 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8618 // for the SOA record for ".", where the record is reported as non-cacheable
8619 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8620 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
8621 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
8622 if (negttl
< ttl_s
) negttl
= ttl_s
;
8624 // Create the SOA record as we may have to return this to the questions
8625 // that we are acting as a proxy for currently or in the future.
8626 SOARecord
= CreateNewCacheEntry(m
, HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
), cgSOA
, 1, mDNSfalse
, mDNSNULL
);
8628 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8629 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8630 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8631 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8633 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8634 // along with the negative cache record. For simplicity, we don't create the additional records.
8635 if (!qptr
->ProxyQuestion
&& q
.qtype
== kDNSType_SOA
)
8637 int qcount
= CountLabels(&q
.qname
);
8638 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
8639 if (qcount
- 1 > scount
)
8640 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
8641 repeat
= qcount
- 1 - scount
;
8644 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8647 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8648 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8649 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8650 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8651 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8652 // so that we back off our polling rate and don't keep hitting the server continually.
8655 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
8656 negttl
= neg
->resrec
.rroriginalttl
* 2;
8661 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
8663 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8666 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8667 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S
,
8668 q
.request_id
, mDNSVal16(q
.TargetQID
), neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
8669 RefreshCacheRecord(m
, neg
, negttl
);
8670 // When we created the cache for the first time and answered the question, the question's
8671 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8672 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8673 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8674 // we should reset its question interval here to MaxQuestionInterval.
8675 ResetQuestionState(m
, qptr
);
8676 if (DNSSECQuestion(qptr
))
8677 neg
->CRDNSSECQuestion
= 1;
8678 // Update the NSEC records again.
8679 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8682 if (!AddNSECSForCacheRecord(m
, NSECRecords
, neg
, rcode
))
8684 // We might just have an SOA record for zones that are not signed and hence don't log
8686 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
8687 "[R%u->Q%d] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr " PRI_S
" during refresh",
8688 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, neg
));
8689 FreeNSECRecords(m
, NSECRecords
);
8690 neg
->CRDNSSECQuestion
= 0;
8692 NSECRecords
= mDNSNULL
;
8697 ReleaseCacheRecord(m
, neg
->soa
);
8698 neg
->soa
= SOARecord
;
8699 SOARecord
= mDNSNULL
;
8705 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
8706 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
8707 m
->rec
.r
.responseFlags
= response
->h
.flags
;
8708 // We create SOA records above which might create new cache groups. Earlier
8709 // in the function we looked up the cache group for the name and it could have
8710 // been NULL. If we pass NULL cg to new cache entries that we create below,
8711 // it will create additional cache groups for the same name. To avoid that,
8712 // look up the cache group again to re-initialize cg again.
8713 cg
= CacheGroupForName(m
, hash
, name
);
8714 if (NSECRecords
&& DNSSECQuestion(qptr
))
8716 // Create the cache entry with delay and then add the NSEC records
8717 // to it and add it immediately.
8718 negcr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(hash
), cg
, 1, mDNStrue
, mDNSNULL
);
8721 negcr
->CRDNSSECQuestion
= 0;
8722 if (!AddNSECSForCacheRecord(m
, NSECRecords
, negcr
, rcode
))
8724 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
8725 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr " PRI_S
,
8726 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, negcr
));
8727 FreeNSECRecords(m
, NSECRecords
);
8731 negcr
->CRDNSSECQuestion
= 1;
8732 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8733 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for " PRI_S
,
8734 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, negcr
));
8736 NSECRecords
= mDNSNULL
;
8737 negcr
->DelayDelivery
= 0;
8738 CacheRecordDeferredAdd(m
, negcr
);
8740 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8745 // Need to add with a delay so that we can tag the SOA record
8746 negcr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(hash
), cg
, 1, mDNStrue
, mDNSNULL
);
8749 negcr
->CRDNSSECQuestion
= 0;
8750 if (DNSSECQuestion(qptr
))
8751 negcr
->CRDNSSECQuestion
= 1;
8752 negcr
->DelayDelivery
= 0;
8757 ReleaseCacheRecord(m
, negcr
->soa
);
8758 negcr
->soa
= SOARecord
;
8759 SOARecord
= mDNSNULL
;
8761 CacheRecordDeferredAdd(m
, negcr
);
8764 m
->rec
.r
.responseFlags
= zeroID
;
8765 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8768 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
8769 hash
= DomainNameHashValue(name
);
8777 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used");
8778 FreeNSECRecords(m
, NSECRecords
);
8782 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8783 ReleaseCacheRecord(m
, SOARecord
);
8787 mDNSlocal
void mDNSCorePrintStoredProxyRecords(mDNS
*const m
)
8789 AuthRecord
*rrPtr
= mDNSNULL
;
8790 if (!m
->SPSRRSet
) return;
8791 LogSPS("Stored Proxy records :");
8792 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8794 LogSPS("%s", ARDisplayString(m
, rrPtr
));
8798 mDNSlocal mDNSBool
mDNSCoreRegisteredProxyRecord(mDNS
*const m
, AuthRecord
*rr
)
8800 AuthRecord
*rrPtr
= mDNSNULL
;
8802 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8804 if (IdenticalResourceRecord(&rrPtr
->resrec
, &rr
->resrec
))
8806 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m
, rr
));
8810 mDNSCorePrintStoredProxyRecords(m
);
8814 mDNSexport CacheRecord
* mDNSCoreReceiveCacheCheck(mDNS
*const m
, const DNSMessage
*const response
, uDNS_LLQType LLQType
,
8815 const mDNSu32 slot
, CacheGroup
*cg
, DNSQuestion
*unicastQuestion
, CacheRecord
***cfp
, CacheRecord
**NSECCachePtr
,
8816 mDNSInterfaceID InterfaceID
)
8819 CacheRecord
**cflocal
= *cfp
;
8821 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
8824 // Resource record received via unicast, the resGroupID should match ?
8827 const mDNSu32 id1
= (cr
->resrec
.rDNSServer
? cr
->resrec
.rDNSServer
->resGroupID
: 0);
8828 const mDNSu32 id2
= (m
->rec
.r
.resrec
.rDNSServer
? m
->rec
.r
.resrec
.rDNSServer
->resGroupID
: 0);
8829 match
= (id1
== id2
);
8832 match
= (cr
->resrec
.InterfaceID
== InterfaceID
);
8833 // If we found this exact resource record, refresh its TTL
8834 if (match
&& IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
8836 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
8837 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8838 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
8840 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8842 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8843 if (cr
->NextInCFList
== mDNSNULL
&& *cfp
!= &cr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
8846 cflocal
= &cr
->NextInCFList
;
8847 *cflocal
= (CacheRecord
*)1;
8848 *cfp
= &cr
->NextInCFList
;
8851 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8852 if (!(cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
8855 for (q
= m
->Questions
; q
; q
=q
->next
)
8857 if (CacheRecordAnswersQuestion(cr
, q
))
8860 cr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
8864 if (!SameRDataBody(&m
->rec
.r
.resrec
, &cr
->resrec
.rdata
->u
, SameDomainNameCS
))
8866 // If the rdata of the packet record differs in name capitalization from the record in our cache
8867 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8868 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8869 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8870 cr
->resrec
.rroriginalttl
= 0;
8871 cr
->TimeRcvd
= m
->timenow
;
8872 cr
->UnansweredQueries
= MaxUnansweredQueries
;
8873 SetNextCacheCheckTimeForRecord(m
, cr
);
8874 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S
, CRDisplayString(m
, cr
));
8875 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S
, CRDisplayString(m
, &m
->rec
.r
));
8876 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8877 NextCacheCheckEvent(cr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
8878 // DO NOT break out here -- we want to continue as if we never found it
8880 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
8884 m
->mDNSStats
.CacheRefreshed
++;
8886 if (cr
->resrec
.mortality
== Mortality_Ghost
&& unicastQuestion
&& (unicastQuestion
->allowExpired
!= AllowExpired_AllowExpiredAnswers
) && !cr
->DelayDelivery
)
8888 cr
->DelayDelivery
= NonZeroTime(m
->timenow
);
8889 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m
->timenow
- RRExpireTime(cr
), CRDisplayString(m
, cr
));
8892 if (cr
->resrec
.rroriginalttl
== 0) debugf("uDNS rescuing %s", CRDisplayString(m
, cr
));
8893 RefreshCacheRecord(m
, cr
, m
->rec
.r
.resrec
.rroriginalttl
);
8894 // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop.
8895 // It is safe to call because the else-if body will unconditionally break out of the for-loop now that it has found the entry to update.
8896 RefreshCacheRecordCacheGroupOrder(cg
, cr
);
8897 cr
->responseFlags
= response
->h
.flags
;
8899 // If we may have NSEC records returned with the answer (which we don't know yet as it
8900 // has not been processed), we need to cache them along with the first cache
8901 // record in the list that answers the question so that it can be used for validation
8902 // later. The "type" check below is to make sure that we cache on the cache record
8903 // that would answer the question. It is possible that we might cache additional things
8904 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8905 // the record that answers the question.
8906 if (response
->h
.numAnswers
&& unicastQuestion
&& unicastQuestion
->qtype
== cr
->resrec
.rrtype
8907 && !(*NSECCachePtr
))
8909 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S
, CRDisplayString(m
, cr
));
8912 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8913 // polling the network once we get a valid response back. For the first time when a new
8914 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8915 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8916 // configuration changed, without flushing the cache, we reset the question interval here.
8917 // Currently, we do this for for both multicast and unicast questions as long as the record
8918 // type is unique. For unicast, resource record is always unique and for multicast it is
8919 // true for records like A etc. but not for PTR.
8920 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8922 for (q
= m
->Questions
; q
; q
=q
->next
)
8924 if (!q
->DuplicateOf
&& !q
->LongLived
&&
8925 ActiveQuestion(q
) && CacheRecordAnswersQuestion(cr
, q
))
8927 ResetQuestionState(m
, q
);
8928 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
8929 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8933 break; // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above)
8937 // If the packet TTL is zero, that means we're deleting this record.
8938 // To give other hosts on the network a chance to protest, we push the deletion
8939 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8940 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8941 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8942 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8943 // If the record is already going to expire in less than one second anyway, we leave it alone --
8944 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8945 debugf("DE for %s", CRDisplayString(m
, cr
));
8946 if (RRExpireTime(cr
) - m
->timenow
> mDNSPlatformOneSecond
)
8948 cr
->resrec
.rroriginalttl
= 1;
8949 cr
->TimeRcvd
= m
->timenow
;
8950 cr
->UnansweredQueries
= MaxUnansweredQueries
;
8951 SetNextCacheCheckTimeForRecord(m
, cr
);
8960 mDNSlocal
void mDNSParseNSEC3Records(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
8961 const mDNSInterfaceID InterfaceID
, CacheRecord
**NSEC3Records
)
8967 if (!response
->h
.numAuthorities
)
8969 ptr
= LocateAuthorities(response
, end
);
8972 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8975 for (i
= 0; i
< response
->h
.numAuthorities
&& ptr
&& ptr
< end
; i
++)
8979 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8980 if (!ptr
|| m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
|| m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC3
)
8982 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr
, CRDisplayString(m
, &m
->rec
.r
));
8983 m
->rec
.r
.resrec
.RecordType
= 0;
8986 cg
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
8987 // Create the cache entry but don't add it to the cache it. We need
8988 // to cache this along with the main cache record.
8989 rr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
), cg
, 0, mDNSfalse
, mDNSNULL
);
8992 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m
, rr
));
8994 NSEC3Records
= &rr
->next
;
8996 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
9000 mDNSlocal
void mDNSCoreResetRecord(mDNS
*const m
)
9002 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
9005 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
9006 // the record list and/or question list.
9007 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9008 // InterfaceID non-NULL tells us the interface this multicast response was received on
9009 // InterfaceID NULL tells us this was a unicast response
9010 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
9011 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
,
9012 const DNSMessage
*const response
, const mDNSu8
*end
,
9013 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
9014 const mDNSInterfaceID InterfaceID
)
9017 const mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
9018 mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
9019 DNSQuestion
*llqMatch
= mDNSNULL
;
9020 DNSQuestion
*unicastQuestion
= mDNSNULL
;
9021 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
9023 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
9024 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
9025 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
9026 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
9027 CacheRecord
**cfp
= &CacheFlushRecords
;
9028 CacheRecord
*NSECRecords
= mDNSNULL
;
9029 CacheRecord
*NSECCachePtr
= mDNSNULL
;
9030 CacheRecord
**nsecp
= &NSECRecords
;
9031 CacheRecord
*McastNSEC3Records
= mDNSNULL
;
9033 mDNSu8 rcode
= '\0';
9034 mDNSBool rrsigsCreated
= mDNSfalse
;
9035 mDNSBool DNSSECQuestion
= mDNSfalse
;
9036 NetworkInterfaceInfo
*llintf
= FirstIPv4LLInterfaceForID(m
, InterfaceID
);
9037 mDNSBool recordAcceptedInResponse
= mDNSfalse
; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
9039 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
9040 // to guard against spoof responses, then the only credible protection against that is cryptographic
9041 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
9042 int firstauthority
= response
->h
.numAnswers
;
9043 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
9044 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
9045 const mDNSu8
*ptr
= response
->data
;
9046 DNSServer
*uDNSServer
= mDNSNULL
;
9048 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
9049 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
9050 srcaddr
, dstaddr
, InterfaceID
,
9051 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
9052 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
9053 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
9054 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
9056 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9057 if (mDNSSameIPPort(srcport
, UnicastDNSPort
))
9059 MetricsUpdateDNSResponseSize((mDNSu32
)(end
- (mDNSu8
*)response
));
9063 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
9064 // When a DNS client receives a reply with TC
9065 // set, it should ignore that response, and query again, using a
9066 // mechanism, such as a TCP connection, that will permit larger replies.
9067 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
9068 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
9069 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
9070 // <rdar://problem/6690034> Can't bind to Active Directory
9071 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
9072 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
9073 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
9074 // and not even do the TCP query.
9075 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
9076 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
9077 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
9078 // section, and the answer section is therefore assumed to be complete.
9080 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
9081 // When a response is so long that truncation is required, the truncation
9082 // should start at the end of the response and work forward in the
9083 // datagram. Thus if there is any data for the authority section, the
9084 // answer section is guaranteed to be unique.
9085 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
) &&
9086 ((response
->h
.numAnswers
== 0) || ((response
->h
.numAuthorities
== 0) && (response
->h
.numAdditionals
== 0)))) return;
9088 if (LLQType
== uDNS_LLQ_Ignore
) return;
9090 // 1. We ignore questions (if any) in mDNS response packets
9091 // 2. If this is an LLQ response, we handle it much the same
9092 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9093 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
)
9094 ptr
= LocateAnswers(response
, end
);
9095 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9096 // in this response packet are immediately deemed to be invalid.
9099 mDNSBool failure
, returnEarly
;
9100 rcode
= (mDNSu8
)(response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
);
9101 failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
9102 returnEarly
= mDNSfalse
;
9103 // We could possibly combine this with the similar loop at the end of this function --
9104 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9105 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9106 // which it was received (or refreshed), and then at the end if we find any cache records which
9107 // answer questions in this packet's question section, but which aren't tagged with this packet's
9108 // packet number, then we deduce they are old and delete them
9109 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
9111 DNSQuestion q
, *qptr
= mDNSNULL
, *suspiciousForQ
= mDNSNULL
;
9112 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
9113 if (ptr
&& (qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
, &suspiciousForQ
)))
9118 // Remember the unicast question that we found, which we use to make caching
9119 // decisions later on in this function
9120 CacheGroup
*cg
= CacheGroupForName(m
, q
.qnamehash
, &q
.qname
);
9121 if (!mDNSOpaque16IsZero(response
->h
.id
))
9123 unicastQuestion
= qptr
;
9124 if (qptr
->qDNSServer
&& DNSSECQuestion(qptr
))
9126 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9127 "[R%d->Q%d] mDNSCoreReceiveResponse: Setting aware for " PRI_DM_NAME
" (" PUB_S
") on " PRI_IP_ADDR
,
9128 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), DM_NAME_PARAM(qptr
->qname
.c
),
9129 DNSTypeName(qptr
->qtype
), &qptr
->qDNSServer
->addr
);
9131 qptr
->qDNSServer
->DNSSECAware
= mDNStrue
;
9132 qptr
->qDNSServer
->req_DO
= mDNStrue
;
9134 if (qptr
->ValidatingResponse
)
9135 DNSSECQuestion
= mDNStrue
;
9137 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
9139 if (SameNameCacheRecordAnswersQuestion(cr
, qptr
))
9141 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
9142 cr
->resrec
.InterfaceID
, CRDisplayString(m
, cr
));
9143 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9144 cr
->TimeRcvd
= m
->timenow
- TicksTTL(cr
) - 1;
9145 cr
->UnansweredQueries
= MaxUnansweredQueries
;
9146 cr
->CRDNSSECQuestion
= 0;
9147 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9149 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9150 "[R%d->Q%d] mDNSCoreReceiveResponse: CRDNSSECQuestion set for record " PRI_S
", question " PRI_DM_NAME
" (" PUB_S
")",
9151 unicastQuestion
->request_id
, mDNSVal16(unicastQuestion
->TargetQID
),
9152 CRDisplayString(m
, cr
), DM_NAME_PARAM(unicastQuestion
->qname
.c
),
9153 DNSTypeName(unicastQuestion
->qtype
));
9154 cr
->CRDNSSECQuestion
= 1;
9163 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
9164 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
9165 // req_DO to false here, the next retransmission for this question will turn off validation
9166 // and hence retransmit without the EDNS0/DOK option.
9167 if (DNSSECOptionalQuestion(qptr
) && qptr
->qDNSServer
&& !qptr
->qDNSServer
->DNSSECAware
)
9169 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9170 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query " PRI_DM_NAME
" (" PUB_S
"), clear DO flag",
9171 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), qptr
->qDNSServer
, rcode
,
9172 DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
9173 qptr
->qDNSServer
->req_DO
= mDNSfalse
;
9175 // For Unicast DNS Queries, penalize the DNSServer
9178 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9179 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME
" (" PUB_S
")",
9180 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), qptr
->qDNSServer
, rcode
,
9181 DM_NAME_PARAM(q
.qname
.c
), DNSTypeName(q
.qtype
));
9182 PenalizeDNSServer(m
, qptr
, response
->h
.flags
);
9185 returnEarly
= mDNStrue
;
9188 else if (!InterfaceID
&& suspiciousForQ
)
9190 // If a response is suspicious for a question, then reissue the question via TCP
9191 LogInfo("[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded suspiciously to query %##s (%s) qID %d != rID: %d",
9192 suspiciousForQ
->request_id
, mDNSVal16(suspiciousForQ
->TargetQID
),
9193 suspiciousForQ
->qDNSServer
, q
.qname
.c
, DNSTypeName(q
.qtype
),
9194 mDNSVal16(suspiciousForQ
->TargetQID
), mDNSVal16(response
->h
.id
));
9195 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
9196 m
->NextSuspiciousTimeout
= NonZeroTime(m
->timenow
+ (SUSPICIOUS_REPLY_DEFENSE_SECS
* mDNSPlatformOneSecond
));
9198 uDNS_RestartQuestionAsTCP(m
, suspiciousForQ
, srcaddr
, srcport
);
9199 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9200 suspiciousForQ
->metrics
.dnsOverTCPState
= DNSOverTCP_Suspicious
;
9207 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9208 "[Q%d] Ignoring %2d Answer" PUB_S
" %2d Authorit" PUB_S
" %2d Additional" PUB_S
,
9209 mDNSVal16(response
->h
.id
),
9210 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
9211 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
9212 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
9213 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9214 // generate negative cache entries (we want to query the next server)
9217 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9219 BumpDNSSECStats(m
, kStatsActionSet
, kStatsTypeMsgSize
, (end
- response
->data
));
9223 // Parse the NSEC3 records from the Authority section before we process
9224 // the Answer section so that we can cache them along with the proper
9225 // cache records we create.
9226 if (mDNSOpaque16IsZero(response
->h
.id
))
9227 mDNSParseNSEC3Records(m
, response
, end
, InterfaceID
, &McastNSEC3Records
);
9229 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
9231 // All responses sent via LL multicast are acceptable for caching
9232 // All responses received over our outbound TCP connections are acceptable for caching
9233 // We accept all records in a unicast response to a multicast query once we find one that
9234 // answers an active question.
9235 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
|| recordAcceptedInResponse
;
9236 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9237 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9239 const mDNSu8 RecordType
=
9240 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
9241 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
9242 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
9243 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9245 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
)
9247 mDNSCoreResetRecord(m
);
9251 // We have already parsed the NSEC3 records and cached them approrpriately for
9252 // multicast responses.
9253 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
== kDNSType_NSEC3
)
9255 mDNSCoreResetRecord(m
);
9258 // Don't want to cache OPT or TSIG pseudo-RRs
9259 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
)
9261 mDNSCoreResetRecord(m
);
9264 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
9266 const rdataOPT
*opt
;
9267 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
9268 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9269 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9270 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
9271 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
9273 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
9274 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
9276 mDNSCoreResetRecord(m
);
9279 // if a CNAME record points to itself, then don't add it to the cache
9280 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
9282 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
9283 mDNSCoreResetRecord(m
);
9287 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9288 // In the case of active LLQs, we'll get remove events when the records actually do go away
9289 // In the case of polling LLQs, we assume the record remains valid until the next poll
9290 if (!mDNSOpaque16IsZero(response
->h
.id
))
9291 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
9293 // If response was not sent via LL multicast,
9294 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9299 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9300 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9301 // queries to get ADD/RMV events. To lookup the question, we can't use
9302 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9303 // has already matched the question using the 64 bit Id in the packet and we use that here.
9305 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
9307 // If this is a DNSSEC question that is also LongLived, don't accept records from the
9308 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
9309 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
9310 // for both negative responses and wildcard expanded positive responses as both of come
9311 // back with NSEC/NSEC3s.
9312 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9313 AcceptableResponse
= mDNSfalse
;
9315 else if (!AcceptableResponse
|| !dstaddr
)
9317 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9318 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9319 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9322 DNSQuestion
*q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
9324 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9327 // We could potentially lookup the DNS server based on the source address, but that may not work always
9328 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9329 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9330 // on the "id" and "source port", then this response answers the question and assume the response
9331 // came from the same DNS server that we sent the query to.
9335 AcceptableResponse
= mDNStrue
;
9338 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9339 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
9340 if (!unicastQuestion
) unicastQuestion
= q
; // Acceptable responses to unicast questions need to have (unicastQuestion != nil)
9344 // Accept all remaining records in this unicast response to an mDNS query.
9345 recordAcceptedInResponse
= mDNStrue
;
9346 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9347 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME
" (" PUB_S
")",
9348 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
9353 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9354 // the question. The code below does that. So, make this record unacceptable for now
9357 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
9358 AcceptableResponse
= mDNSfalse
;
9363 else if (llintf
&& llintf
->IgnoreIPv4LL
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_A
)
9365 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9366 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9367 // To work with these broken routers, client devices need to blacklist these broken
9368 // routers and ignore their bogus ARP responses. Some devices implement a technique
9369 // such as the one described in US Patent 7436783, which lets clients detect and
9370 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9372 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9373 // approach of just detecting these broken routers and completely disabling IPv4
9374 // link-local communication on interfaces where a broken router is detected.
9375 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9376 // that are deemed “safe” for IPv4 link-local communication;
9377 // the flag is cleared on interfaces where a broken router is detected.
9379 // OS X and iOS will not even try to communicate with an IPv4
9380 // link-local destination on an interface without the IFEF_ARPLL flag set.
9381 // This can cause some badly written applications to freeze for a long time if they
9382 // attempt to connect to an IPv4 link-local destination address and then wait for
9383 // that connection attempt to time out before trying other candidate addresses.
9385 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9386 // records on interfaces where we know the OS will be unwilling even to attempt
9387 // communication with those IPv4 link-local destination addresses.
9388 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9390 const CacheRecord
*const rr
= &m
->rec
.r
;
9391 const RDataBody2
*const rdb
= (RDataBody2
*)rr
->smallrdatastorage
.data
;
9392 if (mDNSv4AddressIsLinkLocal(&rdb
->ipv4
))
9394 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m
, &m
->rec
.r
));
9395 mDNSCoreResetRecord(m
);
9400 // 1. Check that this packet resource record does not conflict with any of ours
9401 if (mDNSOpaque16IsZero(response
->h
.id
) && m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
9403 if (m
->CurrentRecord
)
9404 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
9405 m
->CurrentRecord
= m
->ResourceRecords
;
9406 while (m
->CurrentRecord
)
9408 AuthRecord
*rr
= m
->CurrentRecord
;
9409 m
->CurrentRecord
= rr
->next
;
9410 // We accept all multicast responses, and unicast responses resulting from queries we issued
9411 // For other unicast responses, this code accepts them only for responses with an
9412 // (apparently) local source address that pertain to a record of our own that's in probing state
9413 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
9415 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
9417 // ... check to see if type and rdata are identical
9418 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
9420 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9421 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
9423 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9424 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
9428 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
9429 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9432 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9433 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
9435 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9436 m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
), IIDPrintable(InterfaceID
));
9437 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9439 // If this record is marked DependentOn another record for conflict detection purposes,
9440 // then *that* record has to be bumped back to probing state to resolve the conflict
9441 if (rr
->DependentOn
)
9443 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
9444 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9447 // If we've just whacked this record's ProbeCount, don't need to do it again
9448 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
9449 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
9450 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
9451 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
9454 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
9455 // If we'd previously verified this record, put it back to probing state and try again
9456 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
9458 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m
, rr
));
9459 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
9460 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9461 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9462 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9463 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9464 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
9465 rr
->AnnounceCount
= InitialAnnounceCount
;
9466 InitializeLastAPTime(m
, rr
);
9467 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
9469 // If we're probing for this record, we just failed
9470 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
9472 // At this point in the code, we're probing for uniqueness.
9473 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9474 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9475 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9476 if (!mDNSCoreRegisteredProxyRecord(m
, rr
))
9478 if ((rr
->ProbingConflictCount
== 0) || (m
->MPktNum
!= rr
->LastConflictPktNum
))
9480 const NetworkInterfaceInfo
*const intf
= FirstInterfaceForID(m
, InterfaceID
);
9481 rr
->ProbingConflictCount
++;
9482 rr
->LastConflictPktNum
= m
->MPktNum
;
9483 if (ResponseMCast
&& (!intf
|| intf
->SupportsUnicastMDNSResponse
) &&
9484 (rr
->ProbingConflictCount
<= kMaxAllowedMCastProbingConflicts
))
9486 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9487 "spurious multicast conflict (%d/%d) via interface %d for %s",
9488 rr
->ProbeCount
, kProbingConflictPauseDuration
, rr
->ProbingConflictCount
,
9489 kMaxAllowedMCastProbingConflicts
, IIDPrintable(InterfaceID
), ARDisplayString(m
, rr
));
9490 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
9491 rr
->LastAPTime
= m
->timenow
+ kProbingConflictPauseDuration
- rr
->ThisAPInterval
;
9492 SetNextAnnounceProbeTime(m
, rr
);
9496 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9497 rr
->ProbeCount
, ARDisplayString(m
, rr
), ResponseMCast
? "multi" : "uni", IIDPrintable(InterfaceID
));
9498 m
->mDNSStats
.NameConflicts
++;
9499 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9500 // See if this record was also registered with any D2D plugins.
9501 D2D_stop_advertising_record(rr
);
9503 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9508 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9509 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9510 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9511 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9512 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9513 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
9515 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
9516 m
->mDNSStats
.KnownUniqueNameConflicts
++;
9517 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9518 D2D_stop_advertising_record(rr
);
9520 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9523 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
9526 // Else, matching signature, different type or rdata, but not a considered a conflict.
9527 // If the packet record has the cache-flush bit set, then we check to see if we
9528 // have any record(s) of the same type that we should re-assert to rescue them
9529 // (see note about "multi-homing and bridged networks" at the end of this function).
9530 else if (m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
)
9531 if ((m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (mDNSu32
)(m
->timenow
- rr
->LastMCTime
) > (mDNSu32
)mDNSPlatformOneSecond
/2)
9532 { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9537 nseclist
= mDNSfalse
;
9538 if (!AcceptableResponse
)
9540 AcceptableResponse
= IsResponseAcceptable(m
, CacheFlushRecords
, unicastQuestion
, &nseclist
);
9541 if (AcceptableResponse
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
9544 // 2. See if we want to add this packet resource record to our cache
9545 // We only try to cache answers if we have a cache to put them in
9546 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9547 if (!AcceptableResponse
) {
9548 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S
,
9549 mDNSVal16(response
->h
.id
), CRDisplayString(m
, &m
->rec
.r
));
9551 if (m
->rrcache_size
&& AcceptableResponse
)
9553 const mDNSu32 slot
= HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
);
9554 CacheGroup
*cg
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
9555 CacheRecord
*rr
= mDNSNULL
;
9557 // 2a. Check if this packet resource record is already in our cache.
9559 // If this record should go in the nseclist, don't look in the cache for updating it.
9560 // They are supposed to be cached under the "nsec" field of the cache record for
9561 // validation. Just create the cache record.
9564 rr
= mDNSCoreReceiveCacheCheck(m
, response
, LLQType
, slot
, cg
, unicastQuestion
, &cfp
, &NSECCachePtr
, InterfaceID
);
9567 // If packet resource record not in our cache, add it now
9568 // (unless it is just a deletion of a record we never had, in which case we don't care)
9569 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
9571 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
9575 delay
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
9577 delay
= CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
);
9579 // If unique, assume we may have to delay delivery of this 'add' event.
9580 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9581 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9582 // to schedule an mDNS_Execute task at the appropriate time.
9583 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
, !nseclist
, srcaddr
);
9586 rr
->responseFlags
= response
->h
.flags
;
9587 // If we are not creating signatures, then we need to inform DNSSEC so that
9588 // it does not wait forever. Don't do this if we got NSEC records
9589 // as it indicates that this name does not exist.
9590 if (rr
->resrec
.rrtype
== kDNSType_RRSIG
&& !nseclist
)
9592 rrsigsCreated
= mDNStrue
;
9594 // Remember whether we created a cache record in response to a DNSSEC question.
9595 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9596 rr
->CRDNSSECQuestion
= 0;
9597 if (unicastQuestion
&& DNSSECQuestion(unicastQuestion
))
9599 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9600 "[R%d->Q%d] mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record " PRI_S
", question " PRI_DM_NAME
" (" PUB_S
")",
9601 unicastQuestion
->request_id
, mDNSVal16(unicastQuestion
->TargetQID
), CRDisplayString(m
, rr
),
9602 DM_NAME_PARAM(unicastQuestion
->qname
.c
), DNSTypeName(unicastQuestion
->qtype
));
9603 rr
->CRDNSSECQuestion
= 1;
9605 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9606 // which we should be creating below. It is also needed in the wildcard
9607 // expanded answer case and in that case it is cached along with the answer.
9610 rr
->TimeRcvd
= m
->timenow
;
9614 else if (AddToCFList
)
9617 cfp
= &rr
->NextInCFList
;
9618 *cfp
= (CacheRecord
*)1;
9620 else if (rr
->DelayDelivery
)
9622 ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
9627 mDNSCoreResetRecord(m
);
9631 mDNSCoreResetRecord(m
);
9633 // If we've just received one or more records with their cache flush bits set,
9634 // then scan that cache slot to see if there are any old stale records we need to flush
9635 while (CacheFlushRecords
!= (CacheRecord
*)1)
9637 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
9638 const mDNSu32 slot
= HashSlotFromNameHash(r1
->resrec
.namehash
);
9639 const CacheGroup
*cg
= CacheGroupForRecord(m
, &r1
->resrec
);
9640 mDNSBool purgedRecords
= mDNSfalse
;
9641 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
9642 r1
->NextInCFList
= mDNSNULL
;
9644 // Look for records in the cache with the same signature as this new one with the cache flush
9645 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9646 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9647 // We make these TTL adjustments *only* for records that still have *more* than one second
9648 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9649 // (and now has half a second remaining) could inadvertently get its life extended, by either
9650 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9651 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9652 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9653 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9654 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9655 // To avoid this, we need to ensure that the cache flushing operation will only act to
9656 // *decrease* a record's remaining lifetime, never *increase* it.
9657 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
9661 if (!r1
->resrec
.InterfaceID
)
9663 id1
= (r1
->resrec
.rDNSServer
? r1
->resrec
.rDNSServer
->resGroupID
: 0);
9664 id2
= (r2
->resrec
.rDNSServer
? r2
->resrec
.rDNSServer
->resGroupID
: 0);
9670 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9671 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9672 // the new RRSIG that we received. Process only if the typeCovered matches.
9673 if ((r1
->resrec
.rrtype
== r2
->resrec
.rrtype
) && (r1
->resrec
.rrtype
== kDNSType_RRSIG
))
9675 rdataRRSig
*rrsig1
= (rdataRRSig
*)(((RDataBody2
*)(r1
->resrec
.rdata
->u
.data
))->data
);
9676 rdataRRSig
*rrsig2
= (rdataRRSig
*)(((RDataBody2
*)(r2
->resrec
.rdata
->u
.data
))->data
);
9677 if (swap16(rrsig1
->typeCovered
) != swap16(rrsig2
->typeCovered
))
9679 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9680 DNSTypeName(swap16(rrsig1
->typeCovered
)), DNSTypeName(swap16(rrsig2
->typeCovered
)));
9685 // For Unicast (null InterfaceID) the resolver IDs should also match
9686 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
9687 (r1
->resrec
.InterfaceID
|| (id1
== id2
)) &&
9688 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
9689 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
)
9691 if (r1
->resrec
.mortality
== Mortality_Mortal
&& r2
->resrec
.mortality
!= Mortality_Mortal
)
9693 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1
, r2
);
9694 r1
->resrec
.mortality
= Mortality_Immortal
; // Immortalize the replacement record
9697 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9698 // else, if record is old, mark it to be flushed
9699 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9701 // If we find mismatched TTLs in an RRSet, correct them.
9702 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9703 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9704 // which we treat as a goodbye followed by an addition) and in that case it would be
9705 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9707 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9708 // because certain early Bonjour devices are known to have this specific mismatch, and
9709 // there's no point filling syslog with messages about something we already know about.
9710 // We also don't log this for uDNS responses, since a caching name server is obliged
9711 // to give us an aged TTL to correct for how long it has held the record,
9712 // so our received TTLs are expected to vary in that case
9714 // We also suppress log message in the case of SRV records that are received
9715 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9716 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9718 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
9720 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
9721 !(r2
->resrec
.rroriginalttl
== 120 && r1
->resrec
.rroriginalttl
== 4500 && r2
->resrec
.rrtype
== kDNSType_SRV
) &&
9722 mDNSOpaque16IsZero(response
->h
.id
))
9723 LogInfo("Correcting TTL from %4d to %4d for %s",
9724 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
9725 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
9727 r2
->TimeRcvd
= m
->timenow
;
9728 SetNextCacheCheckTimeForRecord(m
, r2
);
9730 else if (r2
->resrec
.InterfaceID
) // else, if record is old, mark it to be flushed
9732 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
9733 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
9734 // We set stale records to expire in one second.
9735 // This gives the owner a chance to rescue it if necessary.
9736 // This is important in the case of multi-homing and bridged networks:
9737 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9738 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9739 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9740 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9741 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9742 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9744 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9745 // final expiration queries for this record.
9747 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9748 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9749 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9750 // <rdar://problem/5636422> Updating TXT records is too slow
9751 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9752 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9753 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
9755 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
9756 r2
->resrec
.rroriginalttl
= 0;
9758 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9760 // We only set a record to expire in one second if it currently has *more* than a second to live
9761 // If it's already due to expire in a second or less, we just leave it alone
9762 r2
->resrec
.rroriginalttl
= 1;
9763 r2
->UnansweredQueries
= MaxUnansweredQueries
;
9764 r2
->TimeRcvd
= m
->timenow
- 1;
9765 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9766 // that we marked for deletion via an explicit DE record
9768 SetNextCacheCheckTimeForRecord(m
, r2
);
9772 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9773 if (r2
->resrec
.mortality
== Mortality_Ghost
)
9776 for (q
= m
->Questions
; q
; q
=q
->next
)
9778 if (!q
->LongLived
&& ActiveQuestion(q
) &&
9779 CacheRecordAnswersQuestion(r2
, q
) &&
9780 q
->metrics
.expiredAnswerState
== ExpiredAnswer_AnsweredWithExpired
)
9782 q
->metrics
.expiredAnswerState
= ExpiredAnswer_ExpiredAnswerChanged
;
9787 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9788 r2
->resrec
.mortality
= Mortality_Mortal
; // We want it purged, so remove any immortality
9789 mDNS_PurgeCacheResourceRecord(m
, r2
);
9790 purgedRecords
= mDNStrue
;
9795 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
9797 // If we had a unicast question for this response with at least one positive answer and we
9798 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9799 // signatures along with the cache record which will be used for validation later. If
9800 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9801 // use that instead.
9802 if (response
->h
.numAnswers
&& unicastQuestion
&& NSECRecords
)
9806 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9807 "[R%d->Q%d] mDNSCoreReceiveResponse: Updating NSECCachePtr to " PRI_S
,
9808 unicastQuestion
->request_id
, mDNSVal16(unicastQuestion
->TargetQID
), CRDisplayString(m
, r1
));
9811 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9812 // might start the verification process which needs these NSEC records
9813 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
9815 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
9816 FreeNSECRecords(m
, NSECRecords
);
9818 NSECRecords
= mDNSNULL
;
9819 NSECCachePtr
= mDNSNULL
;
9821 if (r1
->resrec
.InterfaceID
)
9823 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
);
9827 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9828 // them to be deleted before any ADD events for this record.
9829 r1
->DelayDelivery
= purgedRecords
? NonZeroTime(m
->timenow
) : 0;
9831 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9832 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
9833 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
9837 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9838 // update them now for future validations.
9839 if (NSECRecords
&& NSECCachePtr
)
9841 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m
, NSECCachePtr
));
9842 if (!AddNSECSForCacheRecord(m
, NSECRecords
, NSECCachePtr
, rcode
))
9844 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m
, NSECCachePtr
));
9845 FreeNSECRecords(m
, NSECRecords
);
9847 NSECRecords
= mDNSNULL
;
9848 NSECCachePtr
= mDNSNULL
;
9851 // If there is at least one answer and we did not create RRSIGs and there was a
9852 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9853 // were created. We don't need to give a hint:
9855 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9856 // generate a negative response
9858 // - if we have NSECRecords, it means we might have a potential proof for
9859 // non-existence of name that we are looking for
9861 if (response
->h
.numAnswers
&& !rrsigsCreated
&& DNSSECQuestion
&& !NSECRecords
)
9862 mDNSCoreReceiveNoDNSSECAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
);
9864 // See if we need to generate negative cache entries for unanswered unicast questions
9865 mDNSCoreReceiveNoUnicastAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
, LLQType
, rcode
, NSECRecords
);
9867 if (McastNSEC3Records
)
9869 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9870 FreeNSECRecords(m
, McastNSEC3Records
);
9874 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9875 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9876 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9877 // that warrants waking the sleeping host.
9878 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9880 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
9882 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9883 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9884 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9885 // simple, we use the same mechanism for both lists.
9888 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9891 m
->CurrentRecord
= thelist
;
9892 while (m
->CurrentRecord
)
9894 AuthRecord
*const rr
= m
->CurrentRecord
;
9895 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
9897 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m
, rr
));
9898 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
9900 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
9901 m
->CurrentRecord
= rr
->next
;
9905 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
9907 if (!e
->l
[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9908 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
9909 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
9912 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
9914 if (result
&& result
!= mStatus_MemFree
)
9915 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
9917 if (result
== mStatus_NameConflict
)
9920 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
9921 if (ar
->WakeUp
.HMAC
.l
[0])
9923 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
, mDNSfalse
); // Send one wakeup magic packet
9924 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
); // Schedule all other records with the same owner to be woken
9929 if (result
== mStatus_NameConflict
|| result
== mStatus_MemFree
)
9932 mDNSPlatformMemFree(ar
);
9933 mDNS_UpdateAllowSleep(m
);
9937 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
)
9944 for (i
= 0; ptr
< limit
&& *ptr
!= ' ' && i
< 17; i
++, ptr
++)
9946 hval
= HexVal(*ptr
);
9952 else if (*ptr
== ':')
9956 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons
, val
);
9959 eth
->b
[colons
] = val
;
9966 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons
);
9969 eth
->b
[colons
] = val
;
9973 mDNSlocal mDNSu8
*GetValueForIPv6Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv6Addr
*v6
)
9978 int digitsProcessed
;
9983 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9984 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9986 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9987 // the result in "v6"
9989 numColons
= numBytes
= value
= digitsProcessed
= zeroFillStart
= 0;
9990 while (ptr
< limit
&& *ptr
!= ' ')
9992 hval
= HexVal(*ptr
);
9997 digitsProcessed
= 1;
9999 else if (*ptr
== ':')
10001 if (!digitsProcessed
)
10003 // If we have already seen a "::", we should not see one more. Handle the special
10007 // if we never filled any bytes and the next character is space (we have reached the end)
10009 if (!numBytes
&& (ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
10011 mDNSPlatformMemZero(v6
->b
, 16);
10014 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart
);
10018 // We processed "::". We need to fill zeroes later. For now, mark the
10019 // point where we will start filling zeroes from.
10020 zeroFillStart
= numBytes
;
10023 else if ((ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
10025 // We have a trailing ":" i.e., no more characters after ":"
10026 LogMsg("GetValueForIPv6Addr: Trailing colon");
10031 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
10032 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
10033 // filled here is 12 and 13.
10034 if (numBytes
> 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes
); return mDNSNULL
; }
10036 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
10037 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
10038 digitsProcessed
= value
= 0;
10040 // Make sure that we did not fill the 13th and 14th byte above
10041 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes
); return mDNSNULL
; }
10047 // We should be processing the last set of bytes following the last ":" here
10048 if (!digitsProcessed
)
10050 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes
);
10054 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes
); return mDNSNULL
; }
10055 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
10056 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
10061 for (i
= 0; i
< zeroFillStart
; i
++)
10062 v6
->b
[i
] = v6addr
[i
];
10063 for (j
= i
, n
= 0; n
< 16 - numBytes
; j
++, n
++)
10065 for (; j
< 16; i
++, j
++)
10066 v6
->b
[j
] = v6addr
[i
];
10068 else if (numBytes
== 16)
10069 mDNSPlatformMemCopy(v6
->b
, v6addr
, 16);
10072 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes
);
10078 mDNSlocal mDNSu8
*GetValueForIPv4Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv4Addr
*v4
)
10084 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
10086 if (*ptr
>= '0' && *ptr
<= '9')
10087 val
= val
* 10 + *ptr
- '0';
10088 else if (*ptr
== '.')
10090 if (val
> 255 || dots
>= 3)
10092 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
);
10095 v4
->b
[dots
++] = val
;
10100 // We have a zero at the end and if we reached that, then we are done.
10101 if (*ptr
== 0 && ptr
== limit
- 1 && dots
== 3)
10106 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
); return mDNSNULL
; }
10109 if (dots
!= 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots
); return mDNSNULL
; }
10114 mDNSlocal mDNSu8
*GetValueForKeepalive(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSu32
*value
)
10119 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
10121 if (*ptr
< '0' || *ptr
> '9')
10123 // We have a zero at the end and if we reached that, then we are done.
10124 if (*ptr
== 0 && ptr
== limit
- 1)
10129 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr
, ptr
, limit
, *(ptr
+ 1)); return mDNSNULL
; }
10131 val
= val
* 10 + *ptr
- '0';
10137 mDNSexport mDNSBool
mDNSValidKeepAliveRecord(AuthRecord
*rr
)
10139 mDNSAddr laddr
, raddr
;
10141 mDNSIPPort lport
, rport
;
10142 mDNSu32 timeout
, seq
, ack
;
10145 if (!mDNS_KeepaliveRecord(&rr
->resrec
))
10150 timeout
= seq
= ack
= 0;
10152 laddr
= raddr
= zeroAddr
;
10153 lport
= rport
= zeroIPPort
;
10156 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10158 if (mDNSAddressIsZero(&laddr
) || mDNSIPPortIsZero(lport
) ||
10159 mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(rport
) ||
10160 mDNSEthAddressIsZero(eth
))
10169 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
, mDNSu32
*seq
,
10170 mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
)
10172 if (ar
->resrec
.rrtype
!= kDNSType_NULL
)
10175 if (mDNS_KeepaliveRecord(&ar
->resrec
))
10177 int len
= ar
->resrec
.rdlength
;
10178 mDNSu8
*ptr
= &ar
->resrec
.rdata
->u
.txt
.c
[1];
10179 mDNSu8
*limit
= ptr
+ len
- 1; // Exclude the first byte that is the length
10182 while (ptr
< limit
)
10184 mDNSu8 param
= *ptr
;
10185 ptr
+= 2; // Skip the letter and the "="
10188 laddr
->type
= mDNSAddrType_IPv4
;
10189 ptr
= GetValueForIPv4Addr(ptr
, limit
, &laddr
->ip
.v4
);
10191 else if (param
== 'd')
10193 raddr
->type
= mDNSAddrType_IPv4
;
10194 ptr
= GetValueForIPv4Addr(ptr
, limit
, &raddr
->ip
.v4
);
10196 else if (param
== 'H')
10198 laddr
->type
= mDNSAddrType_IPv6
;
10199 ptr
= GetValueForIPv6Addr(ptr
, limit
, &laddr
->ip
.v6
);
10201 else if (param
== 'D')
10203 raddr
->type
= mDNSAddrType_IPv6
;
10204 ptr
= GetValueForIPv6Addr(ptr
, limit
, &raddr
->ip
.v6
);
10206 else if (param
== 'm')
10208 ptr
= GetValueForMACAddr(ptr
, limit
, eth
);
10212 ptr
= GetValueForKeepalive(ptr
, limit
, &value
);
10214 if (!ptr
) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10216 // Extract everything in network order so that it is easy for sending a keepalive and also
10217 // for matching incoming TCP packets
10222 //if (*timeout < 120) *timeout = 120;
10233 lport
->NotAnInteger
= swap16((mDNSu16
)value
);
10236 rport
->NotAnInteger
= swap16((mDNSu16
)value
);
10239 *seq
= swap32(value
);
10242 *ack
= swap32(value
);
10245 *win
= swap16((mDNSu16
)value
);
10248 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param
);
10252 ptr
++; // skip the space
10257 // 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
10258 // the clients need not retrieve this information from the auth record again.
10259 mDNSlocal AuthRecord
* mDNS_MatchKeepaliveInfo(mDNS
*const m
, const mDNSAddr
* pladdr
, const mDNSAddr
* praddr
, const mDNSIPPort plport
,
10260 const mDNSIPPort prport
, mDNSu32
*rseq
, mDNSu32
*rack
)
10263 mDNSAddr laddr
, raddr
;
10265 mDNSIPPort lport
, rport
;
10266 mDNSu32 timeout
, seq
, ack
;
10269 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10271 timeout
= seq
= ack
= 0;
10273 laddr
= raddr
= zeroAddr
;
10274 lport
= rport
= zeroIPPort
;
10276 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10278 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10280 // Did we parse correctly ?
10281 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10283 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10287 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10288 &laddr
, pladdr
, &raddr
, praddr
, mDNSVal16(lport
), mDNSVal16(plport
), mDNSVal16(rport
), mDNSVal16(prport
));
10290 // Does it match the incoming TCP packet ?
10291 if (mDNSSameAddress(&laddr
, pladdr
) && mDNSSameAddress(&raddr
, praddr
) && mDNSSameIPPort(lport
, plport
) && mDNSSameIPPort(rport
, prport
))
10293 // returning in network order
10302 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
)
10306 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10308 mDNSu32 timeout
, seq
, ack
;
10310 mDNSAddr laddr
, raddr
;
10312 mDNSIPPort lport
, rport
;
10314 timeout
= seq
= ack
= 0;
10317 laddr
= raddr
= zeroAddr
;
10318 lport
= rport
= zeroIPPort
;
10320 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10322 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10324 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10326 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10329 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10331 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10332 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10333 if (!ar
->KATimeExpire
|| (m
->timenow
- ar
->KATimeExpire
>= 0))
10335 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10336 ar
->KATimeExpire
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
10338 if (m
->NextScheduledKA
- ar
->KATimeExpire
> 0)
10339 m
->NextScheduledKA
= ar
->KATimeExpire
;
10343 mDNSlocal
void mDNS_SendKeepaliveACK(mDNS
*const m
, AuthRecord
*ar
)
10345 mDNSu32 timeout
, seq
, ack
, seqInc
;
10347 mDNSAddr laddr
, raddr
;
10349 mDNSIPPort lport
, rport
;
10352 if (ar
== mDNSNULL
)
10354 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10358 timeout
= seq
= ack
= 0;
10361 laddr
= raddr
= zeroAddr
;
10362 lport
= rport
= zeroIPPort
;
10364 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10366 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10368 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10372 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10373 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10374 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10375 // it's converted to host byte order before incrementing it by one.
10376 ptr
= (mDNSu8
*)&seq
;
10377 seqInc
= (mDNSu32
)((ptr
[0] << 24) | (ptr
[1] << 16) | (ptr
[2] << 8) | ptr
[3]) + 1;
10378 ptr
[0] = (mDNSu8
)((seqInc
>> 24) & 0xFF);
10379 ptr
[1] = (mDNSu8
)((seqInc
>> 16) & 0xFF);
10380 ptr
[2] = (mDNSu8
)((seqInc
>> 8) & 0xFF);
10381 ptr
[3] = (mDNSu8
)((seqInc
) & 0xFF);
10382 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10383 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10386 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
10387 const DNSMessage
*const msg
, const mDNSu8
*end
,
10388 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
10389 const mDNSInterfaceID InterfaceID
)
10393 mDNSu8
*p
= m
->omsg
.data
;
10394 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10395 mDNSu32 updatelease
= 0;
10398 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10399 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10400 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
10401 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
10402 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
10403 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
10404 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
10406 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
10408 if (mDNS_PacketLoggingEnabled
)
10409 DumpPacket(mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
, InterfaceID
);
10411 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
10414 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
10415 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
10418 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
10419 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
10421 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
10422 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
10425 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10428 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
10430 if (!updatelease
|| !owner
.HMAC
.l
[0])
10432 static int msgs
= 0;
10436 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
10437 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
10439 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
10441 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
10443 static int msgs
= 0;
10447 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
10448 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
10450 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10454 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
10456 if (updatelease
> 24 * 60 * 60)
10457 updatelease
= 24 * 60 * 60;
10459 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
10460 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
10462 ptr
= LocateAuthorities(msg
, end
);
10464 // Clear any stale TCP keepalive records that may exist
10465 ClearKeepaliveProxyRecords(m
, &owner
, m
->DuplicateRecords
, InterfaceID
);
10466 ClearKeepaliveProxyRecords(m
, &owner
, m
->ResourceRecords
, InterfaceID
);
10468 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
10470 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
10471 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
10473 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
10474 AuthRecord
*ar
= (AuthRecord
*) mDNSPlatformMemAllocateClear(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
10477 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10482 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
10483 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
10484 // All stale keepalive records have been flushed prior to this loop.
10485 if (!mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
10487 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
10488 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
10490 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, AuthRecordAny
, SPSRecordCallback
, ar
);
10491 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
10492 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
10493 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
10494 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
10495 ar
->ForceMCast
= mDNStrue
;
10496 ar
->WakeUp
= owner
;
10497 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
10499 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
10500 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10501 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10502 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
10503 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
10505 ar
->TimeRcvd
= m
->timenow
;
10506 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
10507 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
10508 m
->NextScheduledSPS
= ar
->TimeExpire
;
10509 ar
->KATimeExpire
= 0;
10510 mDNS_Register_internal(m
, ar
);
10513 mDNS_UpdateAllowSleep(m
);
10514 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
10517 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10520 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
10522 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
10523 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
10524 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
10528 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10529 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10530 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
10531 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10532 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
10533 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
10534 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
10538 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, mDNSNULL
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
10539 mDNS_SendKeepalives(m
);
10542 mDNSlocal mDNSu32
mDNSGenerateOwnerOptForInterface(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, DNSMessage
*msg
)
10544 mDNSu8
*ptr
= msg
->data
;
10545 mDNSu8
*end
= mDNSNULL
;
10546 mDNSu32 length
= 0;
10548 NetworkInterfaceInfo
*intf
;
10550 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10551 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10552 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
10553 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10555 intf
= FirstInterfaceForID(m
, InterfaceID
);
10556 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
10558 LogSPS("Generated OPT record : %s", ARDisplayString(m
, &opt
));
10559 end
= PutResourceRecord(msg
, ptr
, &msg
->h
.numAdditionals
, &opt
.resrec
);
10560 if (end
!= mDNSNULL
)
10562 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10563 SwapDNSHeaderBytes(msg
);
10564 length
= (end
- msg
->data
);
10567 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10572 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10573 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10574 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10575 // Really, both should be unified and handled in one place.
10576 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
)
10580 mDNSu32 pktlease
= 0, spsupdates
= 0;
10581 const mDNSBool gotlease
= GetPktLease(m
, msg
, end
, &pktlease
);
10582 const mDNSu32 updatelease
= gotlease
? pktlease
: 60 * 60; // If SPS fails to indicate lease time, assume one hour
10583 if (gotlease
) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease
, mDNSVal16(msg
->h
.id
), InterfaceID
);
10585 if (m
->CurrentRecord
)
10586 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
10587 m
->CurrentRecord
= m
->ResourceRecords
;
10588 while (m
->CurrentRecord
)
10590 AuthRecord
*const rr
= m
->CurrentRecord
;
10591 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
10592 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
10594 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10595 // Clear the updateid when we are done sending on all interfaces.
10596 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, InterfaceID
, mDNStrue
);
10597 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
10598 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
10599 if (mDNSOpaque64IsZero(&rr
->updateIntID
))
10600 rr
->updateid
= zeroID
;
10601 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
10603 LogSPS("Sleep Proxy %s record %2d %5d 0x%x 0x%x (%d) %s", rr
->WakeUp
.HMAC
.l
[0] ? "transferred" : "registered", spsupdates
, updatelease
, rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
,rr
));
10604 if (rr
->WakeUp
.HMAC
.l
[0])
10606 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10607 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
10608 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
10611 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10612 // new records could have been added to the end of the list as a result of that call.
10613 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
10614 m
->CurrentRecord
= rr
->next
;
10616 if (spsupdates
) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10622 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10623 ifname
= InterfaceNameForID(m
, InterfaceID
);
10624 mDNSPlatformMemCopy(&spsaddr
, srcaddr
, sizeof (mDNSAddr
));
10625 mDNSPlatformStoreSPSMACAddr(&spsaddr
, ifname
);
10627 // Store the Owner OPT record for this interface.
10628 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10629 InitializeDNSMessage(&optMsg
.h
, zeroID
, ResponseFlags
);
10630 length
= mDNSGenerateOwnerOptForInterface(m
, InterfaceID
, &optMsg
);
10633 length
+= sizeof(DNSMessageHeader
);
10634 mDNSPlatformStoreOwnerOptRecord(ifname
, &optMsg
, length
);
10638 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10639 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10640 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
10643 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
10644 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
, DNSServer
*dnsserver
)
10646 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
10647 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
10649 // Create empty resource record
10650 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
10651 cr
->resrec
.InterfaceID
= InterfaceID
;
10652 cr
->resrec
.rDNSServer
= dnsserver
;
10653 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10654 cr
->resrec
.rrtype
= rrtype
;
10655 cr
->resrec
.rrclass
= rrclass
;
10656 cr
->resrec
.rroriginalttl
= ttl_seconds
;
10657 cr
->resrec
.rdlength
= 0;
10658 cr
->resrec
.rdestimate
= 0;
10659 cr
->resrec
.namehash
= namehash
;
10660 cr
->resrec
.rdatahash
= 0;
10661 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
10662 cr
->resrec
.rdata
->MaxRDLength
= 0;
10664 cr
->NextInKAList
= mDNSNULL
;
10665 cr
->TimeRcvd
= m
->timenow
;
10666 cr
->DelayDelivery
= 0;
10667 cr
->NextRequiredQuery
= m
->timenow
;
10668 cr
->CRActiveQuestion
= mDNSNULL
;
10669 cr
->UnansweredQueries
= 0;
10670 cr
->LastUnansweredTime
= 0;
10671 cr
->NextInCFList
= mDNSNULL
;
10672 cr
->nsec
= mDNSNULL
;
10673 cr
->soa
= mDNSNULL
;
10674 cr
->CRDNSSECQuestion
= 0;
10675 // Initialize to the basic one and the caller can set it to more
10676 // specific based on the response if any
10677 cr
->responseFlags
= ResponseFlags
;
10680 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
10681 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
10682 const mDNSInterfaceID InterfaceID
)
10684 mDNSInterfaceID ifid
= InterfaceID
;
10685 const mDNSu8
*const pkt
= (mDNSu8
*)msg
;
10686 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
10687 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
10688 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
10689 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
10691 mDNSu8
*ptr
= mDNSNULL
;
10692 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10693 if (TLS
) dstaddr
= mDNSNULL
;
10695 #ifndef UNICAST_DISABLED
10696 if (mDNSSameAddress(srcaddr
, &m
->Router
))
10698 #ifdef _LEGACY_NAT_TRAVERSAL_
10699 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
10702 LNT_ConfigureRouterInfo(m
, InterfaceID
, (mDNSu8
*)msg
, (mDNSu16
)(end
- pkt
));
10707 if (mDNSSameIPPort(srcport
, NATPMPPort
))
10710 uDNS_ReceiveNATPacket(m
, InterfaceID
, (mDNSu8
*)msg
, (mDNSu16
)(end
- pkt
));
10715 #ifdef _LEGACY_NAT_TRAVERSAL_
10716 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
10720 if ((unsigned)(end
- pkt
) < sizeof(DNSMessageHeader
))
10722 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), (int)(end
- pkt
));
10725 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
10726 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10727 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
10728 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
10729 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
10730 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
10731 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
10733 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10735 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10736 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10737 if (!mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
10741 if (mDNSOpaque16IsZero(msg
->h
.id
))
10744 #if APPLE_OSX_mDNSResponder
10745 // Track the number of multicast packets received from a source outside our subnet.
10746 // Check the destination address to avoid accounting for spurious packets that
10747 // comes in with message id zero.
10748 if (!mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
) && dstaddr
&&
10749 mDNSAddressIsAllDNSLinkGroup(dstaddr
))
10753 #endif // #if APPLE_OSX_mDNSResponder
10756 #ifndef UNICAST_DISABLED
10757 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
10758 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10760 ifid
= mDNSInterface_Any
;
10761 if (mDNS_PacketLoggingEnabled
)
10762 DumpPacket(mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
, InterfaceID
);
10763 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
10764 // Note: mDNSCore also needs to get access to received unicast responses
10767 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10768 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10769 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
10770 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, srcaddr
, InterfaceID
);
10773 if (mDNS_LoggingEnabled
)
10775 static int msgCount
= 0;
10776 if (msgCount
< 1000) {
10779 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10780 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), (int)(end
- pkt
), InterfaceID
);
10781 while (i
< (int)(end
- pkt
))
10784 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
10785 do if (i
< (int)(end
- pkt
)) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", pkt
[i
]);while (++i
& 15);
10786 LogInfo("%s", buffer
);
10791 // Packet reception often causes a change to the task list:
10792 // 1. Inbound queries can cause us to need to send responses
10793 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10794 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10795 // 4. Response packets that answer questions may cause our client to issue new questions
10799 // ***************************************************************************
10800 #if COMPILER_LIKES_PRAGMA_MARK
10802 #pragma mark - Searcher Functions
10805 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10806 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10807 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10808 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10809 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10811 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10812 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10813 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10814 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10815 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10816 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10817 // breaks this design principle.
10820 // If IsLLQ(Q) is true, it means the question is both:
10821 // (a) long-lived and
10822 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10823 // for multicast questions, we don't want to treat LongLived as anything special
10824 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10825 #define AWDLIsIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10826 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10828 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
10831 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10832 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10833 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10834 // further in the list.
10835 for (q
= m
->Questions
; q
&& (q
!= question
); q
= q
->next
)
10837 if (!SameQuestionKind(q
, question
)) continue;
10838 if (q
->qnamehash
!= question
->qnamehash
) continue;
10839 if (q
->InterfaceID
!= question
->InterfaceID
) continue;
10840 if (q
->qtype
!= question
->qtype
) continue;
10841 if (q
->qclass
!= question
->qclass
) continue;
10842 if (IsLLQ(q
) != IsLLQ(question
)) continue;
10843 if (q
->AuthInfo
&& !question
->AuthInfo
) continue;
10844 if (q
->ValidationRequired
!= question
->ValidationRequired
) continue;
10845 if (q
->ValidatingResponse
!= question
->ValidatingResponse
) continue;
10846 if (!q
->Suppressed
!= !question
->Suppressed
) continue;
10847 if (q
->BrowseThreshold
!= question
->BrowseThreshold
) continue;
10848 if (AWDLIsIncluded(q
) != AWDLIsIncluded(question
)) continue;
10849 if (!SameDomainName(&q
->qname
, &question
->qname
)) continue;
10855 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10856 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
10859 DNSQuestion
*first
= mDNSNULL
;
10861 // This is referring to some other question as duplicate. No other question can refer to this
10862 // question as a duplicate.
10863 if (question
->DuplicateOf
)
10865 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
10866 "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME
" (" PUB_S
") duplicate of %p " PRI_DM_NAME
" (" PUB_S
")",
10867 question
->request_id
, mDNSVal16(question
->DuplicateOf
->TargetQID
), mDNSVal16(question
->TargetQID
),
10868 question
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
), question
->DuplicateOf
,
10869 DM_NAME_PARAM(question
->DuplicateOf
->qname
.c
), DNSTypeName(question
->DuplicateOf
->qtype
));
10873 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
10874 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
10876 q
->DuplicateOf
= first
;
10880 // If q used to be a duplicate, but now is not,
10881 // then inherit the state from the question that's going away
10882 q
->LastQTime
= question
->LastQTime
;
10883 q
->ThisQInterval
= question
->ThisQInterval
;
10884 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
10885 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
10886 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
10887 q
->RequestUnicast
= question
->RequestUnicast
;
10888 q
->LastQTxTime
= question
->LastQTxTime
;
10889 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
10890 q
->nta
= question
->nta
;
10891 q
->servAddr
= question
->servAddr
;
10892 q
->servPort
= question
->servPort
;
10893 q
->qDNSServer
= question
->qDNSServer
;
10894 q
->validDNSServers
= question
->validDNSServers
;
10895 q
->unansweredQueries
= question
->unansweredQueries
;
10896 q
->noServerResponse
= question
->noServerResponse
;
10897 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
10899 q
->TargetQID
= question
->TargetQID
;
10900 q
->LocalSocket
= question
->LocalSocket
;
10901 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10903 q
->state
= question
->state
;
10904 // q->tcp = question->tcp;
10905 q
->ReqLease
= question
->ReqLease
;
10906 q
->expire
= question
->expire
;
10907 q
->ntries
= question
->ntries
;
10908 q
->id
= question
->id
;
10910 question
->LocalSocket
= mDNSNULL
;
10911 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
10912 // question->tcp = mDNSNULL;
10914 if (q
->LocalSocket
)
10915 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10919 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10920 q
->nta
->ZoneDataContext
= q
;
10923 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10924 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10926 if (question
->state
== LLQ_Established
)
10928 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10929 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10932 SetNextQueryTime(m
,q
);
10937 mDNSexport McastResolver
*mDNS_AddMcastResolver(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, mDNSu32 timeout
)
10939 McastResolver
**p
= &m
->McastResolvers
;
10940 McastResolver
*tmp
= mDNSNULL
;
10942 if (!d
) d
= (const domainname
*)"";
10944 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
10945 "mDNS_AddMcastResolver: Adding " PUB_DM_NAME
", InterfaceID %p, timeout %u", DM_NAME_PARAM(d
), interface
, timeout
);
10949 while (*p
) // Check if we already have this {interface, domain} tuple registered
10951 if ((*p
)->interface
== interface
&& SameDomainName(&(*p
)->domain
, d
))
10953 if (!((*p
)->flags
& McastResolver_FlagDelete
)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d
->c
, interface
);
10954 (*p
)->flags
&= ~McastResolver_FlagDelete
;
10957 tmp
->next
= mDNSNULL
;
10963 if (tmp
) *p
= tmp
; // move to end of list, to ensure ordering from platform layer
10966 // allocate, add to list
10967 *p
= (McastResolver
*) mDNSPlatformMemAllocateClear(sizeof(**p
));
10968 if (!*p
) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10971 (*p
)->interface
= interface
;
10972 (*p
)->flags
= McastResolver_FlagNew
;
10973 (*p
)->timeout
= timeout
;
10974 AssignDomainName(&(*p
)->domain
, d
);
10975 (*p
)->next
= mDNSNULL
;
10981 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
10984 if (server
->penaltyTime
!= 0)
10986 ptime
= server
->penaltyTime
- m
->timenow
;
10989 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10990 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10992 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10993 ptime
, server
->penaltyTime
, m
->timenow
);
10994 server
->penaltyTime
= 0;
11001 //Checks to see whether the newname is a better match for the name, given the best one we have
11002 //seen so far (given in bestcount).
11003 //Returns -1 if the newname is not a better match
11004 //Returns 0 if the newname is the same as the old match
11005 //Returns 1 if the newname is a better match
11006 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
11009 // If the name contains fewer labels than the new server's domain or the new name
11010 // contains fewer labels than the current best, then it can't possibly be a better match
11011 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
11013 // If there is no match, return -1 and the caller will skip this newname for
11016 // If we find a match and the number of labels is the same as bestcount, then
11017 // we return 0 so that the caller can do additional logic to pick one of
11018 // the best based on some other factors e.g., penaltyTime
11020 // If we find a match and the number of labels is more than bestcount, then we
11021 // return 1 so that the caller can pick this over the old one.
11023 // Note: newcount can either be equal or greater than bestcount beause of the
11026 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
11027 return bestcount
== newcount
? 0 : 1;
11032 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
11033 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
11034 // names. In that case, we give a default timeout of 5 seconds
11035 #define DEFAULT_MCAST_TIMEOUT 5
11036 mDNSlocal mDNSu32
GetTimeoutForMcastQuestion(mDNS
*m
, DNSQuestion
*question
)
11038 McastResolver
*curmatch
= mDNSNULL
;
11039 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
11040 McastResolver
*curr
;
11041 int bettermatch
, currcount
;
11042 for (curr
= m
->McastResolvers
; curr
; curr
= curr
->next
)
11044 currcount
= CountLabels(&curr
->domain
);
11045 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11046 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
11047 // the timeout value from the first one
11048 if (bettermatch
== 1)
11051 bestmatchlen
= currcount
;
11054 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question
->qname
.c
, curmatch
,
11055 curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
11056 return ( curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
11059 // Returns true if it is a Domain Enumeration Query
11060 mDNSexport mDNSBool
DomainEnumQuery(const domainname
*qname
)
11062 const mDNSu8
*mDNS_DEQLabels
[] = { (const mDNSu8
*)"\001b", (const mDNSu8
*)"\002db", (const mDNSu8
*)"\002lb",
11063 (const mDNSu8
*)"\001r", (const mDNSu8
*)"\002dr", (const mDNSu8
*)mDNSNULL
, };
11064 const domainname
*d
= qname
;
11065 const mDNSu8
*label
;
11068 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
11069 if (CountLabels(qname
) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname
->c
); return mDNSfalse
; }
11071 label
= (const mDNSu8
*)d
;
11072 while (mDNS_DEQLabels
[i
] != (const mDNSu8
*)mDNSNULL
)
11074 if (SameDomainLabel(mDNS_DEQLabels
[i
], label
)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
); break;}
11077 if (mDNS_DEQLabels
[i
] == (const mDNSu8
*)mDNSNULL
)
11079 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname
->c
);
11082 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
);
11084 // CountLabels already verified the number of labels
11085 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Second Label
11086 label
= (const mDNSu8
*)d
;
11087 if (!SameDomainLabel(label
, (const mDNSu8
*)"\007_dns-sd"))
11089 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname
->c
);
11092 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname
->c
);
11094 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Third Label
11095 label
= (const mDNSu8
*)d
;
11096 if (!SameDomainLabel(label
, (const mDNSu8
*)"\004_udp"))
11098 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname
->c
);
11101 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname
->c
);
11103 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname
->c
);
11108 // Note: InterfaceID is the InterfaceID of the question
11109 mDNSlocal mDNSBool
DNSServerMatch(DNSServer
*d
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11111 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11112 // with scopeType set to kScopeNone)
11114 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11115 // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11117 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11118 // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11120 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11121 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11123 // If the first condition fails, following are the possible cases (the notes below are using
11124 // InterfaceID for discussion and the same holds good for ServiceID):
11126 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11127 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11129 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11130 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11131 // would fail in this case.
11133 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11134 // should match (Refer to (2) above).
11136 if (((d
->scopeType
== kScopeNone
) && (!InterfaceID
&& ServiceID
== -1)) ||
11137 ((d
->scopeType
== kScopeInterfaceID
) && d
->interface
== InterfaceID
) ||
11138 ((d
->scopeType
== kScopeServiceID
) && d
->serviceID
== ServiceID
))
11145 // Sets all the Valid DNS servers for a question
11146 mDNSexport mDNSu32
SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
11148 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
11150 int bettermatch
, currcount
;
11152 mDNSu32 timeout
= 0;
11155 question
->validDNSServers
= zeroOpaque128
;
11156 DEQuery
= DomainEnumQuery(&question
->qname
);
11157 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11159 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11160 // skip servers that will soon be deleted
11161 if (curr
->flags
& DNSServerFlag_Delete
)
11163 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11167 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11168 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11169 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11170 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11171 // match the scoped entries by mistake.
11173 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11175 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11176 if (((curr
->scopeType
== kScopeInterfaceID
) && (curr
->interface
== mDNSInterface_Any
)) ||
11177 ((curr
->scopeType
== kScopeServiceID
) && (curr
->serviceID
<= 0)))
11179 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11180 (int)curr
->scopeType
, &curr
->addr
, curr
->domain
.c
, curr
->interface
, curr
->serviceID
);
11184 currcount
= CountLabels(&curr
->domain
);
11185 if ((!DEQuery
|| !curr
->isCell
) && DNSServerMatch(curr
, question
->InterfaceID
, question
->ServiceID
))
11187 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11189 // If we found a better match (bettermatch == 1) then clear all the bits
11190 // corresponding to the old DNSServers that we have may set before and start fresh.
11191 // If we find an equal match, then include that DNSServer also by setting the corresponding
11193 if ((bettermatch
== 1) || (bettermatch
== 0))
11195 bestmatchlen
= currcount
;
11198 debugf("SetValidDNSServers: Resetting all the bits");
11199 question
->validDNSServers
= zeroOpaque128
;
11202 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11203 " Timeout %d, interface %p", question
->qname
.c
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
, index
, curr
->timeout
,
11205 timeout
+= curr
->timeout
;
11207 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question
->qname
.c
, &curr
->addr
, curr
->isCell
);
11208 bit_set_opaque128(question
->validDNSServers
, index
);
11213 question
->noServerResponse
= 0;
11215 debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11216 question
->validDNSServers
.l
[3], question
->validDNSServers
.l
[2], question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11217 // If there are no matching resolvers, then use the default timeout value.
11218 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
11219 return ((question
->ProxyQuestion
|| question
->ValidatingResponse
) ? DEFAULT_UDNSSEC_TIMEOUT
: timeout
? timeout
: DEFAULT_UDNS_TIMEOUT
);
11222 // Get the Best server that matches a name. If you find penalized servers, look for the one
11223 // that will come out of the penalty box soon
11224 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
, mDNSOpaque128 validBits
,
11225 int *selected
, mDNSBool nameMatch
)
11227 DNSServer
*curmatch
= mDNSNULL
;
11228 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
11230 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
11231 int bettermatch
, currcount
;
11233 int currindex
= -1;
11235 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
11236 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
11237 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11239 // skip servers that will soon be deleted
11240 if (curr
->flags
& DNSServerFlag_Delete
)
11242 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11246 // Check if this is a valid DNSServer
11247 if (!bit_get_opaque64(validBits
, index
))
11249 debugf("GetBestServer: continuing for index %d", index
);
11254 currcount
= CountLabels(&curr
->domain
);
11255 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
11257 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11258 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
11260 // If there are multiple best servers for a given question, we will pick the first one
11261 // if none of them are penalized. If some of them are penalized in that list, we pick
11262 // the least penalized one. BetterMatchForName walks through all best matches and
11263 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11264 // in the list when there are no penalized servers and least one among them
11265 // when there are some penalized servers.
11267 if (DNSServerMatch(curr
, InterfaceID
, ServiceID
))
11270 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11271 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11272 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11273 // part and still do some redundant steps e.g., InterfaceID match
11276 bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11280 // If we found a better match (bettermatch == 1) then we don't need to
11281 // compare penalty times. But if we found an equal match, then we compare
11282 // the penalty times to pick a better match
11284 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
11288 bestmatchlen
= currcount
;
11289 bestPenaltyTime
= currPenaltyTime
;
11294 if (selected
) *selected
= currindex
;
11298 // Look up a DNS Server, matching by name and InterfaceID
11299 mDNSlocal DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11301 DNSServer
*curmatch
= mDNSNULL
;
11302 char *ifname
= mDNSNULL
; // for logging purposes only
11303 mDNSOpaque128 allValid
;
11305 if (InterfaceID
== mDNSInterface_LocalOnly
)
11306 InterfaceID
= mDNSNULL
;
11308 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
11310 // By passing in all ones, we make sure that every DNS server is considered
11311 allValid
.l
[0] = allValid
.l
[1] = allValid
.l
[2] = allValid
.l
[3] = 0xFFFFFFFF;
11313 curmatch
= GetBestServer(m
, name
, InterfaceID
, ServiceID
, allValid
, mDNSNULL
, mDNStrue
);
11315 if (curmatch
!= mDNSNULL
)
11316 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch
->addr
,
11317 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
11318 InterfaceID
, name
);
11320 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname
? ifname
: "None", InterfaceID
, name
);
11325 // Look up a DNS Server for a question within its valid DNSServer bits
11326 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
11328 DNSServer
*curmatch
= mDNSNULL
;
11329 char *ifname
= mDNSNULL
; // for logging purposes only
11330 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
11331 const domainname
*name
= &question
->qname
;
11334 if (InterfaceID
== mDNSInterface_LocalOnly
)
11335 InterfaceID
= mDNSNULL
;
11338 ifname
= InterfaceNameForID(m
, InterfaceID
);
11340 if (!mDNSOpaque128IsZero(&question
->validDNSServers
))
11342 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->ServiceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
11343 if (currindex
!= -1)
11344 bit_clr_opaque128(question
->validDNSServers
, currindex
);
11347 if (curmatch
!= mDNSNULL
)
11349 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11350 "[R%d->Q%d] GetServerForQuestion: %p DNS server (%p) " PRI_IP_ADDR
":%d (Penalty Time Left %d) (Scope " PUB_S
":%p:%d) for " PRI_DM_NAME
" (" PUB_S
")",
11351 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, curmatch
, &curmatch
->addr
,
11352 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0),
11353 ifname
? ifname
: "None", InterfaceID
, question
->ServiceID
, DM_NAME_PARAM(name
), DNSTypeName(question
->qtype
));
11357 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11358 "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S
":%p:%d) for " PRI_DM_NAME
" (" PUB_S
")",
11359 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, ifname
? ifname
: "None", InterfaceID
,
11360 question
->ServiceID
, DM_NAME_PARAM(name
), DNSTypeName(question
->qtype
));
11366 // Called in normal client context (lock not held)
11367 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
11371 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
11372 n
->clientContext
= mDNSNULL
; // we received at least one callback since starting this NAT-T
11373 for (q
= m
->Questions
; q
; q
=q
->next
)
11374 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
11375 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
11379 // This function takes the DNSServer as a separate argument because sometimes the
11380 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11381 // status before switching to it.
11382 mDNSlocal mDNSBool
ShouldSuppressUnicastQuery(const DNSQuestion
*const q
, const DNSServer
*const server
)
11384 mDNSBool suppress
= mDNSfalse
;
11385 const char *reason
= NULL
;
11387 if (q
->BlockedByPolicy
)
11389 suppress
= mDNStrue
;
11390 reason
= " (blocked by policy)";
11394 if (!q
->IsUnicastDotLocal
)
11396 suppress
= mDNStrue
;
11397 reason
= " (no DNS server)";
11400 else if (server
->isCell
&& (q
->flags
& kDNSServiceFlagsDenyCellular
))
11402 suppress
= mDNStrue
;
11403 reason
= " (interface is cellular)";
11405 else if (server
->isExpensive
&& (q
->flags
& kDNSServiceFlagsDenyExpensive
))
11407 suppress
= mDNStrue
;
11408 reason
= " (interface is expensive)";
11410 else if (server
->isConstrained
&& (q
->flags
& kDNSServiceFlagsDenyConstrained
))
11412 suppress
= mDNStrue
;
11413 reason
= " (interface is constrained)";
11415 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11416 else if (q
->SuppressUnusable
&& !DNS64IsQueryingARecord(q
->dns64
.state
))
11418 else if (q
->SuppressUnusable
)
11421 if (q
->qtype
== kDNSType_A
)
11423 if (!server
->usableA
)
11425 suppress
= mDNStrue
;
11426 reason
= " (A records are unusable)";
11428 // If the server's configuration allows A record queries, suppress this query if
11429 // 1. the interface associated with the server is CLAT46; and
11430 // 2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11431 // See <rdar://problem/42672030> for more info.
11432 else if (server
->isCLAT46
&& (q
->flags
& kDNSServiceFlagsPathEvaluationDone
))
11434 suppress
= mDNStrue
;
11435 reason
= " (CLAT46 A records are unusable)";
11438 else if (q
->qtype
== kDNSType_AAAA
)
11440 if (!server
->usableAAAA
)
11442 suppress
= mDNStrue
;
11443 reason
= " (AAAA records are unusable)";
11449 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11450 "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME
" " PUB_S PUB_S
,
11451 mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), reason
? reason
: "");
11456 mDNSlocal mDNSBool
ShouldSuppressQuery(DNSQuestion
*q
)
11458 if (q
->InterfaceID
== mDNSInterface_LocalOnly
)
11462 if (!q
->IsUnicastDotLocal
&& IsLocalDomain(&q
->qname
))
11466 return (ShouldSuppressUnicastQuery(q
, q
->qDNSServer
));
11469 mDNSlocal
void CacheRecordRmvEventsForCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
11474 cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
11475 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
11477 // Don't deliver RMV events for negative records
11478 if (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
11480 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11481 "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S
" Suppressing RMV events for question %p " PRI_DM_NAME
" (" PUB_S
"), CRActiveQuestion %p, CurrentAnswers %d",
11482 q
->request_id
, mDNSVal16(q
->TargetQID
), CRDisplayString(m
, cr
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
), cr
->CRActiveQuestion
, q
->CurrentAnswers
);
11486 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
11488 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11489 q
->qname
.c
, CRDisplayString(m
, cr
), q
->LOAddressAnswers
);
11491 q
->CurrentAnswers
--;
11492 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
11493 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
11494 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_rmv
);
11495 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
11500 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
11503 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
11504 if (q
== question
) return mDNStrue
;
11508 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11513 if (m
->CurrentQuestion
)
11514 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11515 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11517 if (IsQuestionNew(m
, q
))
11519 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11522 m
->CurrentQuestion
= q
;
11523 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
11526 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
11527 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11528 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
11530 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11531 ARDisplayString(m
, rr
));
11532 if (q
->CurrentAnswers
<= 0 || q
->LOAddressAnswers
<= 0)
11534 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11535 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
11536 q
->CurrentAnswers
, q
->LOAddressAnswers
);
11539 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_rmv
); // MUST NOT dereference q again
11540 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11543 m
->CurrentQuestion
= mDNSNULL
;
11547 // Returns false if the question got deleted while delivering the RMV events
11548 // The caller should handle the case
11549 mDNSexport mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11551 if (m
->CurrentQuestion
)
11552 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11553 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11555 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11556 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11557 if (!IsQuestionNew(m
, q
) && !q
->LOAddressAnswers
)
11559 m
->CurrentQuestion
= q
;
11560 CacheRecordRmvEventsForCurrentQuestion(m
, q
);
11561 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11562 m
->CurrentQuestion
= mDNSNULL
;
11564 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
11568 mDNSlocal
void SuppressStatusChanged(mDNS
*const m
, DNSQuestion
*q
, DNSQuestion
**restart
)
11570 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11571 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11572 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11575 q
->Suppressed
= mDNSfalse
;
11576 if (!CacheRecordRmvEventsForQuestion(m
, q
))
11578 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11579 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11580 q
->request_id
, mDNSVal16(q
->TargetQID
));
11583 q
->Suppressed
= mDNStrue
;
11586 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11587 // and Suppressed status does not mean anything for these questions. As we are going to stop the
11588 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11589 // the restart will not be a duplicate ADD
11590 if (!LocalRecordRmvEventsForQuestion(m
, q
))
11592 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11593 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11594 q
->request_id
, mDNSVal16(q
->TargetQID
));
11598 // There are two cases here.
11600 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11601 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11602 // because when we get the response, if we had entries in the cache already, it will not answer
11603 // this question if the cache entry did not change. Hence, we need to restart
11604 // the query so that it can be answered from the cache.
11606 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11607 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11608 // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11609 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11610 // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11611 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11612 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11613 // This affects both efficiency and also the current design where there is only one active question
11614 // pointed to from a cache entry.
11616 // We restart queries in a two step process by first calling stop and build a temporary list which we
11617 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11618 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11619 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11620 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11621 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11623 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11625 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11626 "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME
" (" PUB_S
")",
11627 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
11628 mDNS_StopQuery_internal(m
, q
);
11629 q
->next
= *restart
;
11633 // The caller should hold the lock
11634 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
11637 DNSQuestion
*restart
= mDNSNULL
;
11639 // We look through all questions including new questions. During network change events,
11640 // we potentially restart questions here in this function that ends up as new questions,
11641 // which may be suppressed at this instance. Before it is handled we get another network
11642 // event that changes the status e.g., address becomes available. If we did not process
11643 // new questions, we would never change its Suppressed status.
11645 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11646 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11647 // *any* other question which could be the next one that we may process here. RestartQuestion
11648 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11649 // if the "next" question is stopped while the CurrentQuestion is stopped
11650 if (m
->RestartQuestion
)
11651 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11652 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11653 m
->RestartQuestion
= m
->Questions
;
11654 while (m
->RestartQuestion
)
11656 q
= m
->RestartQuestion
;
11657 m
->RestartQuestion
= q
->next
;
11658 if (q
->SuppressUnusable
)
11660 const mDNSBool old
= q
->Suppressed
;
11661 q
->Suppressed
= ShouldSuppressQuery(q
);
11662 if (q
->Suppressed
!= old
)
11664 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11665 // followed by a negative cache response. Temporarily turn off suppression so that
11666 // AnswerCurrentQuestionWithResourceRecord can answer the question
11667 SuppressStatusChanged(m
, q
, &restart
);
11674 restart
= restart
->next
;
11675 q
->next
= mDNSNULL
;
11676 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
11677 mDNS_StartQuery_internal(m
, q
);
11681 mDNSlocal
void RestartUnicastQuestions(mDNS
*const m
)
11684 DNSQuestion
*restartList
= mDNSNULL
;
11686 if (m
->RestartQuestion
)
11687 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11688 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11689 m
->RestartQuestion
= m
->Questions
;
11690 while (m
->RestartQuestion
)
11692 q
= m
->RestartQuestion
;
11693 m
->RestartQuestion
= q
->next
;
11696 if (mDNSOpaque16IsZero(q
->TargetQID
))
11697 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11699 q
->Restart
= mDNSfalse
;
11700 SuppressStatusChanged(m
, q
, &restartList
);
11703 while ((q
= restartList
) != mDNSNULL
)
11705 restartList
= q
->next
;
11706 q
->next
= mDNSNULL
;
11707 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11708 "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME
" (" PUB_S
")",
11709 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
));
11710 mDNS_StartQuery_internal(m
, q
);
11714 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11715 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11716 mDNSlocal mStatus
ValidateParameters(mDNS
*const m
, DNSQuestion
*const question
)
11718 if (!ValidateDomainName(&question
->qname
))
11720 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
11721 return(mStatus_Invalid
);
11724 // If this question is referencing a specific interface, verify it exists
11725 if (question
->InterfaceID
&& !LocalOnlyOrP2PInterface(question
->InterfaceID
))
11727 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
11729 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11730 IIDPrintable(question
->InterfaceID
), question
->qname
.c
, DNSTypeName(question
->qtype
));
11733 return(mStatus_NoError
);
11736 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11737 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11738 mDNSlocal
void InitDNSConfig(mDNS
*const m
, DNSQuestion
*const question
)
11740 // First reset all DNS Configuration
11741 question
->qDNSServer
= mDNSNULL
;
11742 question
->validDNSServers
= zeroOpaque128
;
11743 question
->triedAllServersOnce
= mDNSfalse
;
11744 question
->noServerResponse
= mDNSfalse
;
11745 question
->StopTime
= (question
->TimeoutQuestion
) ? question
->StopTime
: 0;
11746 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11747 mDNSPlatformMemZero(&question
->metrics
, sizeof(question
->metrics
));
11748 question
->metrics
.expiredAnswerState
= (question
->allowExpired
!= AllowExpired_None
) ? ExpiredAnswer_Allowed
: ExpiredAnswer_None
;
11751 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11752 if (LocalOnlyOrP2PInterface(question
->InterfaceID
) && !question
->TimeoutQuestion
)
11754 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11755 if (!mDNSOpaque16IsZero(question
->TargetQID
))
11757 mDNSu32 timeout
= SetValidDNSServers(m
, question
);
11758 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11759 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11760 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11761 // it gets a full timeout value even if the original question times out earlier.
11762 if (question
->TimeoutQuestion
&& !question
->StopTime
)
11764 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11765 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11766 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME
" (" PUB_S
")",
11767 mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
));
11770 question
->qDNSServer
= GetServerForQuestion(m
, question
);
11771 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
11772 "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME
" " PUB_S
" Timeout %d, DNS Server " PRI_IP_ADDR
":%d",
11773 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(question
->qname
.c
),
11774 DNSTypeName(question
->qtype
), timeout
, question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11775 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11777 else if (question
->TimeoutQuestion
&& !question
->StopTime
)
11779 // If the question is to be timed out and its a multicast, local-only or P2P case,
11780 // then set it's stop time.
11781 mDNSu32 timeout
= LocalOnlyOrP2PInterface(question
->InterfaceID
) ?
11782 DEFAULT_LO_OR_P2P_TIMEOUT
: GetTimeoutForMcastQuestion(m
, question
);
11783 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11784 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11785 "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME
" (" PUB_S
")",
11786 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
));
11788 // Set StopTime here since it is a part of DNS Configuration
11789 if (question
->StopTime
)
11790 SetNextQueryStopTime(m
, question
);
11791 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11792 // will never be transmitted on the wire.
11793 if (!(LocalOnlyOrP2PInterface(question
->InterfaceID
)))
11794 SetNextQueryTime(m
,question
);
11797 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11798 // state fields of the DNS Question. These are independent of the Client layer.
11799 mDNSlocal
void InitCommonState(mDNS
*const m
, DNSQuestion
*const question
)
11802 mDNSBool isBlocked
= mDNSfalse
;
11804 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11805 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11806 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11807 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11808 // that to go out immediately.
11809 question
->next
= mDNSNULL
;
11810 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11811 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11812 // the question list to check if ThisQInterval is negative which means the question has been
11813 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11814 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11815 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11816 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11817 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
11818 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
11819 question
->DelayAnswering
= mDNSOpaque16IsZero(question
->TargetQID
) ? CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
) : 0;
11820 question
->LastQTime
= m
->timenow
;
11821 question
->ExpectUnicastResp
= 0;
11822 question
->LastAnswerPktNum
= m
->PktNum
;
11823 question
->RecentAnswerPkts
= 0;
11824 question
->CurrentAnswers
= 0;
11826 #if APPLE_OSX_mDNSResponder
11828 // Initial browse threshold used by Finder.
11829 #define mDNSFinderBrowseThreshold 20
11831 // Set the threshold at which we move to a passive browse state,
11832 // not actively sending queries.
11833 if (question
->flags
& kDNSServiceFlagsThresholdOne
)
11834 question
->BrowseThreshold
= 1;
11835 else if (question
->flags
& kDNSServiceFlagsThresholdFinder
)
11836 question
->BrowseThreshold
= mDNSFinderBrowseThreshold
;
11838 question
->BrowseThreshold
= 0;
11840 #else // APPLE_OSX_mDNSResponder
11841 question
->BrowseThreshold
= 0;
11842 #endif // APPLE_OSX_mDNSResponder
11843 question
->CachedAnswerNeedsUpdate
= mDNSfalse
;
11845 question
->LargeAnswers
= 0;
11846 question
->UniqueAnswers
= 0;
11847 question
->LOAddressAnswers
= 0;
11848 question
->FlappingInterface1
= mDNSNULL
;
11849 question
->FlappingInterface2
= mDNSNULL
;
11851 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11852 // since we would already have the question->ServiceID in that case.
11853 if (!(question
->flags
& kDNSServiceFlagsServiceIndex
))
11855 #if APPLE_OSX_mDNSResponder
11856 mDNSPlatformGetDNSRoutePolicy(question
, &isBlocked
);
11858 question
->ServiceID
= -1;
11862 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question
->qname
.c
,
11863 DNSTypeName(question
->qtype
), question
->pid
, question
->euid
, question
->ServiceID
);
11865 InitDNSConfig(m
, question
);
11867 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
11869 // The question's BlockedByPolicy value must be set before calling ShouldSuppressQuery().
11870 question
->BlockedByPolicy
= isBlocked
? mDNStrue
: mDNSfalse
;
11871 question
->Suppressed
= ShouldSuppressQuery(question
);
11872 question
->NextInDQList
= mDNSNULL
;
11873 question
->SendQNow
= mDNSNULL
;
11874 question
->SendOnAll
= mDNSfalse
;
11875 question
->RequestUnicast
= kDefaultRequestUnicastCount
;
11877 #if APPLE_OSX_mDNSResponder
11878 // Set the QU bit in the first query for the following options.
11879 if ((question
->flags
& kDNSServiceFlagsUnicastResponse
) || (question
->flags
& kDNSServiceFlagsThresholdFinder
))
11881 question
->RequestUnicast
= SET_QU_IN_FIRST_QUERY
;
11882 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question
->RequestUnicast
, question
->qname
.c
,
11883 DNSTypeName(question
->qtype
));
11885 #endif // APPLE_OSX_mDNSResponder
11887 question
->LastQTxTime
= m
->timenow
;
11888 question
->CNAMEReferrals
= 0;
11890 question
->WakeOnResolveCount
= 0;
11891 if (question
->WakeOnResolve
)
11893 question
->WakeOnResolveCount
= InitialWakeOnResolveCount
;
11896 for (i
=0; i
<DupSuppressInfoSize
; i
++)
11897 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
11899 question
->Restart
= mDNSfalse
;
11901 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11902 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
11903 NextQSendTime(question
) - m
->timenow
,
11904 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
11905 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
11907 if (question
->DelayAnswering
)
11908 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11909 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11912 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11913 mDNSlocal
void InitWABState(DNSQuestion
*const question
)
11915 // We'll create our question->LocalSocket on demand, if needed.
11916 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11917 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11918 // NAT mapping for receiving inbound add/remove events.
11919 question
->LocalSocket
= mDNSNULL
;
11920 question
->unansweredQueries
= 0;
11921 question
->nta
= mDNSNULL
;
11922 question
->servAddr
= zeroAddr
;
11923 question
->servPort
= zeroIPPort
;
11924 question
->tcp
= mDNSNULL
;
11925 question
->NoAnswer
= NoAnswer_Normal
;
11928 mDNSlocal
void InitLLQNATState(mDNS
*const m
)
11930 // If we don't have our NAT mapping active, start it now
11931 if (!m
->LLQNAT
.clientCallback
)
11933 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
11934 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
11935 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
11936 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
11937 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal just started
11938 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
11942 mDNSlocal
void InitLLQState(DNSQuestion
*const question
)
11944 question
->state
= LLQ_Init
;
11945 question
->ReqLease
= 0;
11946 question
->expire
= 0;
11947 question
->ntries
= 0;
11948 question
->id
= zeroOpaque64
;
11951 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11952 // DNSSEC & DNS Proxy fields of the DNS Question.
11953 mDNSlocal
void InitDNSSECProxyState(mDNS
*const m
, DNSQuestion
*const question
)
11957 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11958 // or the request is going over cellular interface.
11960 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11961 // at ValidationRequired setting also.
11962 if (question
->qDNSServer
)
11964 if (question
->qDNSServer
->isCell
)
11966 debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question
->qname
.c
, DNSTypeName(question
->qtype
));
11967 question
->ValidationRequired
= mDNSfalse
;
11969 if (DNSSECOptionalQuestion(question
) && !(question
->qDNSServer
->req_DO
))
11971 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11972 question
->qname
.c
, DNSTypeName(question
->qtype
));
11973 question
->ValidationRequired
= DNSSEC_VALIDATION_NONE
;
11976 question
->ValidationState
= (question
->ValidationRequired
? DNSSECValRequired
: DNSSECValNotRequired
);
11977 question
->ValidationStatus
= 0;
11978 question
->responseFlags
= zeroID
;
11981 // Once the question is completely initialized including the duplicate logic, this function
11982 // is called to finalize the unicast question which requires flushing the cache if needed,
11983 // activating the query etc.
11984 mDNSlocal
void FinalizeUnicastQuestion(mDNS
*const m
, DNSQuestion
*question
)
11986 // Ensure DNS related info of duplicate question is same as the orig question
11987 if (question
->DuplicateOf
)
11989 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
11990 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11991 // then we log a line as it could indicate an issue
11992 if (question
->DuplicateOf
->qDNSServer
== mDNSNULL
)
11994 if (question
->qDNSServer
) {
11995 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11996 "[R%d->Q%d] FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(" PRI_IP_ADDR
":%d) but original question(%p) has no DNS Server! " PRI_DM_NAME
" (" PUB_S
")",
11997 question
->request_id
, mDNSVal16(question
->TargetQID
), question
,
11998 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11999 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
), question
->DuplicateOf
,
12000 DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
));
12004 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
12005 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12006 "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME
" (" PUB_S
"), DNS Server " PRI_IP_ADDR
":%d",
12007 question
->request_id
, mDNSVal16(question
->DuplicateOf
->TargetQID
), mDNSVal16(question
->TargetQID
),
12008 question
, question
->DuplicateOf
, DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
),
12009 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
12010 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
12013 ActivateUnicastQuery(m
, question
, mDNSfalse
);
12015 if (!question
->DuplicateOf
&& DNSSECQuestion(question
))
12017 // For DNSSEC questions, we need to have the RRSIGs also for verification.
12018 CheckForDNSSECRecords(m
, question
);
12020 if (question
->LongLived
)
12022 // Unlike other initializations, InitLLQNATState should be done after
12023 // we determine that it is a unicast question. LongLived is set for
12024 // both multicast and unicast browse questions but we should initialize
12025 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
12026 // start the NAT traversal that is not needed.
12027 InitLLQNATState(m
);
12031 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
12036 // First check for cache space (can't do queries if there is no cache space allocated)
12037 if (m
->rrcache_size
== 0)
12038 return(mStatus_NoCache
);
12040 vStatus
= ValidateParameters(m
, question
);
12045 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12046 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12047 // This applies to the top label (TLD) only
12048 // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12049 if (IsHighASCIILabel(LastLabel(&question
->qname
)))
12051 domainname newname
;
12052 if (PerformNextPunycodeConversion(question
, &newname
))
12053 AssignDomainName(&question
->qname
, &newname
);
12055 #endif // USE_LIBIDN
12057 #ifndef UNICAST_DISABLED
12058 question
->TargetQID
= Question_uDNS(question
) ? mDNS_NewMessageID(m
) : zeroID
;
12059 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
12060 question
->LastTargetQID
= zeroID
;
12063 question
->TargetQID
= zeroID
;
12065 debugf("mDNS_StartQuery_internal: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12067 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12069 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12070 q
= &m
->LocalOnlyQuestions
;
12071 while (*q
&& *q
!= question
)
12076 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12077 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
12078 return(mStatus_AlreadyRegistered
);
12082 // Intialize the question. The only ordering constraint we have today is that
12083 // InitDNSSECProxyState should be called after the DNS server is selected (in
12084 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12087 InitCommonState(m
, question
);
12088 InitWABState(question
);
12089 InitLLQState(question
);
12090 InitDNSSECProxyState(m
, question
);
12092 // FindDuplicateQuestion should be called last after all the intialization
12093 // as the duplicate logic could be potentially based on any field in the
12095 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
12096 if (question
->DuplicateOf
)
12097 question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
12099 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12101 if (!m
->NewLocalOnlyQuestions
)
12102 m
->NewLocalOnlyQuestions
= question
;
12106 if (!m
->NewQuestions
)
12107 m
->NewQuestions
= question
;
12109 // If the question's id is non-zero, then it's Wide Area
12110 // MUST NOT do this Wide Area setup until near the end of
12111 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12112 // NS, etc.) and if we haven't finished setting up our own question and setting
12113 // m->NewQuestions if necessary then we could end up recursively re-entering
12114 // this routine with the question list data structures in an inconsistent state.
12115 if (!mDNSOpaque16IsZero(question
->TargetQID
))
12117 FinalizeUnicastQuestion(m
, question
);
12121 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12122 m
->NumAllInterfaceQuestions
++;
12123 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12124 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME
" (" PUB_S
")",
12125 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
12126 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12128 m
->NextBonjourDisableTime
= 0;
12129 if (m
->BonjourEnabled
== 0)
12131 // Enable Bonjour immediately by scheduling network changed processing where
12132 // we will join the multicast group on each active interface.
12133 m
->BonjourEnabled
= 1;
12134 m
->NetworkChanged
= m
->timenow
;
12138 if (question
->WakeOnResolve
)
12140 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question
->qname
.c
);
12141 mDNS_PurgeBeforeResolve(m
, question
);
12146 return(mStatus_NoError
);
12149 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12150 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
12152 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
12153 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12154 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12156 if (nta
->question
.ThisQInterval
!= -1)
12158 mDNS_StopQuery_internal(m
, &nta
->question
);
12159 if (nta
->question
.ThisQInterval
!= -1)
12160 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
12162 mDNSPlatformMemFree(nta
);
12165 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
12167 CacheGroup
*cg
= CacheGroupForName(m
, question
->qnamehash
, &question
->qname
);
12169 DNSQuestion
**qp
= &m
->Questions
;
12171 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12173 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12174 qp
= &m
->LocalOnlyQuestions
;
12175 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
12176 if (*qp
) *qp
= (*qp
)->next
;
12180 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
12182 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question
->qname
.c
, DNSTypeName(question
->qtype
));
12183 return(mStatus_BadReferenceErr
);
12186 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12187 if (!LocalOnlyOrP2PInterface(question
->InterfaceID
) && mDNSOpaque16IsZero(question
->TargetQID
))
12189 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12190 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
12191 m
->NumAllInterfaceQuestions
--;
12192 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12193 "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME
" (" PUB_S
")",
12194 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
12198 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12199 if (Question_uDNS(question
) && !question
->metrics
.answered
&& (question
->metrics
.querySendCount
> 0))
12201 const domainname
* queryName
;
12202 mDNSBool isForCell
;
12203 mDNSu32 durationMs
;
12205 queryName
= question
->metrics
.originalQName
? question
->metrics
.originalQName
: &question
->qname
;
12206 isForCell
= (question
->qDNSServer
&& question
->qDNSServer
->isCell
);
12207 durationMs
= ((m
->timenow
- question
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
12208 MetricsUpdateDNSQueryStats(queryName
, question
->qtype
, mDNSNULL
, question
->metrics
.querySendCount
, question
->metrics
.expiredAnswerState
, question
->metrics
.dnsOverTCPState
, durationMs
, isForCell
);
12211 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12212 UpdateQuestionDuplicates(m
, question
);
12213 // But don't trash ThisQInterval until afterwards.
12214 question
->ThisQInterval
= -1;
12216 // If there are any cache records referencing this as their active question, then see if there is any
12217 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12218 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
12220 if (cr
->CRActiveQuestion
== question
)
12223 DNSQuestion
*replacement
= mDNSNULL
;
12224 // If we find an active question that is answered by this cached record, use it as the cache record's
12225 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12226 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12227 // via CacheRecordRmv() when the cache record expires.
12228 for (q
= m
->Questions
; q
&& (q
!= m
->NewQuestions
); q
= q
->next
)
12230 if (!q
->DuplicateOf
&& !q
->Suppressed
&& CacheRecordAnswersQuestion(cr
, q
))
12232 if (q
->ThisQInterval
> 0)
12237 else if (!replacement
)
12244 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12245 "CurrentAnswers %d, Suppressed %d", replacement
, CRDisplayString(m
,cr
), question
->CurrentAnswers
, replacement
->CurrentAnswers
, replacement
->Suppressed
);
12246 cr
->CRActiveQuestion
= replacement
; // Question used to be active; new value may or may not be null
12247 if (!replacement
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
12251 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12252 // bump its pointer forward one question.
12253 if (m
->CurrentQuestion
== question
)
12255 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12256 question
->qname
.c
, DNSTypeName(question
->qtype
));
12257 m
->CurrentQuestion
= question
->next
;
12260 if (m
->NewQuestions
== question
)
12262 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12263 question
->qname
.c
, DNSTypeName(question
->qtype
));
12264 m
->NewQuestions
= question
->next
;
12267 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
12269 if (m
->RestartQuestion
== question
)
12271 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12272 question
->qname
.c
, DNSTypeName(question
->qtype
));
12273 m
->RestartQuestion
= question
->next
;
12276 if (m
->ValidationQuestion
== question
)
12278 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
12279 question
->qname
.c
, DNSTypeName(question
->qtype
));
12280 m
->ValidationQuestion
= question
->next
;
12283 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12284 question
->next
= mDNSNULL
;
12286 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12288 // And finally, cancel any associated GetZoneData operation that's still running.
12289 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12290 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12291 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12292 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12293 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
12294 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
12295 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
12297 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12299 for (q
= m
->Questions
; q
; q
=q
->next
)
12300 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
12303 if (!m
->LLQNAT
.clientCallback
) // Should never happen, but just in case...
12305 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12309 LogInfo("Stopping LLQNAT");
12310 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
12311 m
->LLQNAT
.clientCallback
= mDNSNULL
; // Means LLQ NAT Traversal not running
12315 // If necessary, tell server it can delete this LLQ state
12316 if (question
->state
== LLQ_Established
)
12318 question
->ReqLease
= 0;
12319 sendLLQRefresh(m
, question
);
12320 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12321 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12322 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12323 // we let that run out its natural course and complete asynchronously.
12326 question
->tcp
->question
= mDNSNULL
;
12327 question
->tcp
= mDNSNULL
;
12330 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12331 else if (question
->dnsPushServer
!= mDNSNULL
)
12333 UnSubscribeToDNSPushNotificationServer(m
, question
);
12337 // wait until we send the refresh above which needs the nta
12338 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
12340 if (question
->ValidationRequired
&& question
->DNSSECAuthInfo
)
12342 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question
->qname
.c
);
12343 question
->DAIFreeCallback(m
, question
->DNSSECAuthInfo
);
12344 question
->DNSSECAuthInfo
= mDNSNULL
;
12346 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12347 if (question
->metrics
.originalQName
)
12349 mDNSPlatformMemFree(question
->metrics
.originalQName
);
12350 question
->metrics
.originalQName
= mDNSNULL
;
12354 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12355 DNS64ResetState(question
);
12358 return(mStatus_NoError
);
12361 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
12365 status
= mDNS_StartQuery_internal(m
, question
);
12370 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
12374 status
= mDNS_StopQuery_internal(m
, question
);
12379 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12380 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12381 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12382 // specifically to catch and report if the client callback does try to make API calls
12383 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
12389 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12390 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
12392 status
= mDNS_StopQuery_internal(m
, question
);
12393 if (status
== mStatus_NoError
&& !qq
)
12395 const CacheRecord
*cr
;
12396 CacheGroup
*const cg
= CacheGroupForName(m
, question
->qnamehash
, &question
->qname
);
12397 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12398 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
12400 if (cr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameCacheRecordAnswersQuestion(cr
, question
))
12402 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12403 if (question
->QuestionCallback
)
12404 question
->QuestionCallback(m
, question
, &cr
->resrec
, mDNSfalse
);
12412 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
12416 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12417 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, cr
->resrec
.InterfaceID
, 0);
12422 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
12424 mStatus status
= mStatus_BadReferenceErr
;
12427 cr
= FindIdenticalRecordInCache(m
, rr
);
12428 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
12429 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12430 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, cr
->resrec
.InterfaceID
, 0);
12435 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
12436 const domainname
*const srv
, const domainname
*const domain
,
12437 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12438 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12439 mDNSQuestionCallback
*Callback
, void *Context
)
12441 question
->InterfaceID
= InterfaceID
;
12442 question
->flags
= flags
;
12443 question
->qtype
= kDNSType_PTR
;
12444 question
->qclass
= kDNSClass_IN
;
12445 question
->LongLived
= mDNStrue
;
12446 question
->ExpectUnique
= mDNSfalse
;
12447 question
->ForceMCast
= ForceMCast
;
12448 question
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
12449 question
->SuppressUnusable
= mDNSfalse
;
12450 question
->AppendSearchDomains
= mDNSfalse
;
12451 question
->TimeoutQuestion
= 0;
12452 question
->WakeOnResolve
= 0;
12453 question
->UseBackgroundTraffic
= useBackgroundTrafficClass
;
12454 question
->ValidationRequired
= 0;
12455 question
->ValidatingResponse
= 0;
12456 question
->ProxyQuestion
= 0;
12457 question
->QuestionCallback
= Callback
;
12458 question
->QuestionContext
= Context
;
12460 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
))
12461 return(mStatus_BadParamErr
);
12463 return(mDNS_StartQuery_internal(m
, question
));
12466 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
12467 const domainname
*const srv
, const domainname
*const domain
,
12468 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12469 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12470 mDNSQuestionCallback
*Callback
, void *Context
)
12474 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, InterfaceID
, flags
, ForceMCast
, useBackgroundTrafficClass
, Callback
, Context
);
12480 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
12481 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
12483 question
->InterfaceID
= InterfaceID
;
12484 question
->flags
= 0;
12485 question
->qtype
= kDNSType_PTR
;
12486 question
->qclass
= kDNSClass_IN
;
12487 question
->LongLived
= mDNSfalse
;
12488 question
->ExpectUnique
= mDNSfalse
;
12489 question
->ForceMCast
= mDNSfalse
;
12490 question
->ReturnIntermed
= mDNSfalse
;
12491 question
->SuppressUnusable
= mDNSfalse
;
12492 question
->AppendSearchDomains
= mDNSfalse
;
12493 question
->TimeoutQuestion
= 0;
12494 question
->WakeOnResolve
= 0;
12495 question
->UseBackgroundTraffic
= mDNSfalse
;
12496 question
->ValidationRequired
= 0;
12497 question
->ValidatingResponse
= 0;
12498 question
->ProxyQuestion
= 0;
12499 question
->pid
= mDNSPlatformGetPID();
12500 question
->euid
= 0;
12501 question
->QuestionCallback
= Callback
;
12502 question
->QuestionContext
= Context
;
12503 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
12504 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
12505 if (!dom
) dom
= &localdomain
;
12506 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
12507 return(mDNS_StartQuery(m
, question
));
12510 // ***************************************************************************
12511 #if COMPILER_LIKES_PRAGMA_MARK
12513 #pragma mark - Responder Functions
12516 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
12520 status
= mDNS_Register_internal(m
, rr
);
12525 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
12526 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
12528 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
12530 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
12531 return(mStatus_Invalid
);
12536 // If TTL is unspecified, leave TTL unchanged
12537 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
12539 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12542 RData
*n
= rr
->NewRData
;
12543 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
12544 if (rr
->UpdateCallback
)
12545 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
12548 rr
->NewRData
= newrdata
;
12549 rr
->newrdlength
= newrdlength
;
12550 rr
->UpdateCallback
= Callback
;
12552 #ifndef UNICAST_DISABLED
12553 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
&& !IsLocalDomain(rr
->resrec
.name
))
12555 mStatus status
= uDNS_UpdateRecord(m
, rr
);
12556 // The caller frees the memory on error, don't retain stale pointers
12557 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
12563 if (RRLocalOnly(rr
) || (rr
->resrec
.rroriginalttl
== newttl
&&
12564 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
)))
12565 CompleteRDataUpdate(m
, rr
);
12568 rr
->AnnounceCount
= InitialAnnounceCount
;
12569 InitializeLastAPTime(m
, rr
);
12570 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
12571 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
12572 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
12573 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
12574 if (rr
->UpdateCredits
<= 5)
12576 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12577 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
12578 rr
->ThisAPInterval
*= 4;
12579 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
12580 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12581 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
12583 rr
->resrec
.rroriginalttl
= newttl
;
12587 return(mStatus_NoError
);
12590 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12591 // the record list and/or question list.
12592 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12593 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
12597 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
12602 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12603 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
12604 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12605 mDNSlocal
void mDNS_RandomizedHostNameCallback(mDNS
*m
, AuthRecord
*rr
, mStatus result
);
12608 mDNSlocal AuthRecord
*GetInterfaceAddressRecord(NetworkInterfaceInfo
*intf
, mDNSBool forRandHostname
)
12610 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12611 return(forRandHostname
? &intf
->RR_AddrRand
: &intf
->RR_A
);
12613 (void)forRandHostname
; // Unused.
12614 return(&intf
->RR_A
);
12618 mDNSlocal AuthRecord
*GetFirstAddressRecordEx(const mDNS
*const m
, const mDNSBool forRandHostname
)
12620 NetworkInterfaceInfo
*intf
;
12621 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12623 if (!intf
->Advertise
) continue;
12624 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12625 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
)) continue;
12627 return(GetInterfaceAddressRecord(intf
, forRandHostname
));
12631 #define GetFirstAddressRecord(M) GetFirstAddressRecordEx(M, mDNSfalse)
12633 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12634 // (It's a set of records, not a set of interfaces.)
12635 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12636 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool useRandomizedHostname
)
12638 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12641 const domainname
*hostname
;
12642 mDNSRecordCallback
*hostnameCallback
;
12643 AuthRecord
*addrAR
;
12645 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12646 const mDNSBool interfaceIsAWDL
= mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
);
12648 mDNSu8 addrRecordType
;
12649 char buffer
[MAX_REVERSE_MAPPING_NAME
];
12651 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12652 if (interfaceIsAWDL
|| useRandomizedHostname
)
12654 hostname
= &m
->RandomizedHostname
;
12655 hostnameCallback
= mDNS_RandomizedHostNameCallback
;
12660 hostname
= &m
->MulticastHostname
;
12661 hostnameCallback
= mDNS_HostNameCallback
;
12664 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12665 if (!interfaceIsAWDL
&& useRandomizedHostname
)
12667 addrAR
= &set
->RR_AddrRand
;
12673 addrAR
= &set
->RR_A
;
12674 ptrAR
= &set
->RR_PTR
;
12676 if (addrAR
->resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
12678 addrRecordType
= set
->DirectLink
? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
12679 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12680 if (hostname
== &m
->RandomizedHostname
) addrRecordType
= kDNSRecordTypeKnownUnique
;
12681 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12682 "AdvertiseInterface: Advertising " PUB_S
" hostname on interface " PUB_S
,
12683 (hostname
== &m
->RandomizedHostname
) ? "randomized" : "normal", set
->ifname
);
12685 LogInfo("AdvertiseInterface: Advertising for ifname %s", set
->ifname
);
12688 // Send dynamic update for non-linklocal IPv4 Addresses
12689 mDNS_SetupResourceRecord(addrAR
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, addrRecordType
, AuthRecordAny
, hostnameCallback
, set
);
12690 if (ptrAR
) mDNS_SetupResourceRecord(ptrAR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
12692 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12693 addrAR
->AllowRemoteQuery
= mDNStrue
;
12694 if (ptrAR
) ptrAR
->AllowRemoteQuery
= mDNStrue
;
12696 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12697 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12698 AssignDomainName(&addrAR
->namestorage
, hostname
);
12699 if (set
->ip
.type
== mDNSAddrType_IPv4
)
12701 addrAR
->resrec
.rrtype
= kDNSType_A
;
12702 addrAR
->resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
12703 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12704 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
12705 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
12707 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
12710 addrAR
->resrec
.rrtype
= kDNSType_AAAA
;
12711 addrAR
->resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
12712 for (i
= 0; i
< 16; i
++)
12714 static const char hexValues
[] = "0123456789ABCDEF";
12715 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
12716 buffer
[i
* 4 + 1] = '.';
12717 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
12718 buffer
[i
* 4 + 3] = '.';
12720 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
12725 MakeDomainNameFromDNSNameString(&ptrAR
->namestorage
, buffer
);
12726 ptrAR
->AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12727 ptrAR
->ForceMCast
= mDNStrue
; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12730 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12731 addrAR
->RRSet
= interfaceIsAWDL
? addrAR
: GetFirstAddressRecordEx(m
, useRandomizedHostname
);
12733 addrAR
->RRSet
= GetFirstAddressRecord(m
);
12735 if (!addrAR
->RRSet
) addrAR
->RRSet
= addrAR
;
12736 mDNS_Register_internal(m
, addrAR
);
12737 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "Initialized RRSet for " PRI_S
, ARDisplayString(m
, addrAR
));
12738 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "RRSet: " PRI_S
, ARDisplayString(m
, addrAR
->RRSet
));
12739 if (ptrAR
) mDNS_Register_internal(m
, ptrAR
);
12741 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12742 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12743 D2D_start_advertising_interface(set
);
12747 mDNSlocal
void AdvertiseInterfaceIfNeeded(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12749 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12750 if (mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
))
12752 if ((m
->AutoTargetAWDLIncludedCount
> 0) || (m
->AutoTargetAWDLOnlyCount
> 0))
12754 AdvertiseInterface(m
, set
, mDNSfalse
);
12759 if (m
->AutoTargetServices
> 0) AdvertiseInterface(m
, set
, mDNSfalse
);
12760 if (m
->AutoTargetAWDLIncludedCount
> 0) AdvertiseInterface(m
, set
, mDNStrue
);
12763 if (m
->AutoTargetServices
> 0) AdvertiseInterface(m
, set
);
12767 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, DeadvertiseFlags flags
)
12769 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12770 const mDNSBool interfaceIsAWDL
= mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
);
12773 // Unregister these records.
12774 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12775 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12776 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12777 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12778 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12779 if ((!interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_NormalHostname
)) ||
12780 ( interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_RandHostname
)))
12782 if (flags
& kDeadvertiseFlag_NormalHostname
)
12785 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12786 "DeadvertiseInterface: Deadvertising " PUB_S
" hostname on interface " PUB_S
,
12787 (flags
& kDeadvertiseFlag_RandHostname
) ? "randomized" : "normal", set
->ifname
);
12788 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12789 D2D_stop_advertising_interface(set
);
12791 if (set
->RR_A
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
12792 if (set
->RR_PTR
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
12794 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12795 if (!interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_RandHostname
))
12797 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12798 "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S
, set
->ifname
);
12799 AuthRecord
*const ar
= &set
->RR_AddrRand
;
12800 if (ar
->resrec
.RecordType
) mDNS_Deregister_internal(m
, ar
, mDNS_Dereg_normal
);
12805 // Change target host name for record.
12806 mDNSlocal
void UpdateTargetHostName(mDNS
*const m
, AuthRecord
*const rr
)
12808 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12809 // If this record was also registered with any D2D plugins, stop advertising
12810 // the version with the old host name.
12811 D2D_stop_advertising_record(rr
);
12814 SetTargetToHostName(m
, rr
);
12816 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12817 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12818 D2D_start_advertising_record(rr
);
12822 mDNSlocal
void DeadvertiseAllInterfaceRecords(mDNS
*const m
, DeadvertiseFlags flags
)
12824 NetworkInterfaceInfo
*intf
;
12825 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12827 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
, flags
);
12831 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
12833 domainname newmname
;
12837 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12838 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12842 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
12845 AssignDomainName(&m
->MulticastHostname
, &newmname
);
12846 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_NormalHostname
);
12847 AdvertiseNecessaryInterfaceRecords(m
);
12850 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12851 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12852 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12857 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
12859 (void)rr
; // Unused parameter
12863 char *msg
= "Unknown result";
12864 if (result
== mStatus_NoError
) msg
= "Name registered";
12865 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
12866 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
12870 if (result
== mStatus_NoError
)
12872 // Notify the client that the host name is successfully registered
12873 if (m
->MainCallback
)
12874 m
->MainCallback(m
, mStatus_NoError
);
12876 else if (result
== mStatus_NameConflict
)
12878 domainlabel oldlabel
= m
->hostlabel
;
12880 // 1. First give the client callback a chance to pick a new name
12881 if (m
->MainCallback
)
12882 m
->MainCallback(m
, mStatus_NameConflict
);
12884 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12885 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12886 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12887 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
12888 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
12890 // 3. Generate the FQDNs from the hostlabel,
12891 // and make sure all SRV records, etc., are updated to reference our new hostname
12893 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
12895 else if (result
== mStatus_MemFree
)
12897 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12898 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12899 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12902 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
12905 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12906 mDNSlocal
void mDNS_RandomizedHostNameCallback(mDNS
*const m
, AuthRecord
*const addrRecord
, const mStatus result
)
12908 (void)addrRecord
; // Unused parameter
12910 if (result
== mStatus_NameConflict
)
12913 domainlabel newUUIDLabel
;
12915 GetRandomUUIDLabel(&newUUIDLabel
);
12916 if (SameDomainLabel(newUUIDLabel
.c
, m
->RandomizedHostname
.c
))
12918 IncrementLabelSuffix(&newUUIDLabel
, mDNSfalse
);
12923 m
->RandomizedHostname
.c
[0] = 0;
12924 AppendDomainLabel(&m
->RandomizedHostname
, &newUUIDLabel
);
12925 AppendLiteralLabelString(&m
->RandomizedHostname
, "local");
12927 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_RandHostname
);
12928 AdvertiseNecessaryInterfaceRecords(m
);
12929 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
12931 if (rr
->AutoTarget
&& AuthRecordIncludesOrIsAWDL(rr
)) UpdateTargetHostName(m
, rr
);
12933 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
12935 if (rr
->AutoTarget
&& AuthRecordIncludesOrIsAWDL(rr
)) UpdateTargetHostName(m
, rr
);
12943 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
12945 NetworkInterfaceInfo
*intf
;
12946 active
->IPv4Available
= mDNSfalse
;
12947 active
->IPv6Available
= mDNSfalse
;
12948 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12949 if (intf
->InterfaceID
== active
->InterfaceID
)
12951 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
12952 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
12956 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
12959 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12960 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
12961 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
12963 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
12964 // Zero out the updateid so that if we have a pending response from the server, it won't
12965 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12966 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
12967 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
12971 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12974 // We initialize ThisQInterval to -1 indicating that the question has not been started
12975 // yet. If the question (browse) is started later during interface registration, it will
12976 // be stopped during interface deregistration. We can't sanity check to see if the
12977 // question has been stopped or not before initializing it to -1 because we need to
12978 // initialize it to -1 the very first time.
12980 set
->NetWakeBrowse
.ThisQInterval
= -1;
12981 for (i
=0; i
<3; i
++)
12983 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
12984 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
12986 set
->NextSPSAttempt
= -1;
12987 set
->NextSPSAttemptTime
= m
->timenow
;
12990 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12992 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12993 while (p
&& p
!= set
) p
=p
->next
;
12994 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12996 if (set
->InterfaceActive
)
12998 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12999 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, set
->InterfaceID
, 0, mDNSfalse
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
13003 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
13005 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
13006 while (p
&& p
!= set
) p
=p
->next
;
13007 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
13009 // Note: We start the browse only if the interface is NetWake capable and we use this to
13010 // stop the resolves also. Hence, the resolves should not be started without the browse
13011 // being started i.e, resolves should not happen unless NetWake capable which is
13012 // guaranteed by BeginSleepProcessing.
13013 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
13016 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
13018 // Stop our browse and resolve operations
13019 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
13020 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
13022 // Make special call to the browse callback to let it know it can to remove all records for this interface
13023 if (m
->SPSBrowseCallback
)
13025 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
13026 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
13027 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
13030 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
13031 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
13032 InitializeNetWakeState(m
, set
);
13036 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, InterfaceActivationSpeed activationSpeed
)
13039 mDNSBool FirstOfType
= mDNStrue
;
13040 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
13042 if (!set
->InterfaceID
)
13043 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set
->ip
); return(mStatus_Invalid
); }
13045 if (!mDNSAddressIsValidNonZero(&set
->mask
))
13046 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set
->ip
, &set
->mask
); return(mStatus_Invalid
); }
13050 // Assume this interface will be active now, unless we find a duplicate already in the list
13051 set
->InterfaceActive
= mDNStrue
;
13052 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
13053 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
13055 InitializeNetWakeState(m
, set
);
13057 // Scan list to see if this InterfaceID is already represented
13062 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
13064 return(mStatus_AlreadyRegistered
);
13067 if ((*p
)->InterfaceID
== set
->InterfaceID
)
13069 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13070 set
->InterfaceActive
= mDNSfalse
;
13071 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
13072 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
13073 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
13079 set
->next
= mDNSNULL
;
13082 if (set
->Advertise
) AdvertiseInterfaceIfNeeded(m
, set
);
13084 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
13085 "mDNS_RegisterInterface: InterfaceID %u " PUB_S
" (" PRI_IP_ADDR
") " PUB_S
,
13086 IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
, set
->InterfaceActive
?
13087 "not represented in list; marking active and retriggering queries" :
13088 "already represented in list; marking inactive for now");
13090 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
13092 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13093 // giving the false impression that there's an active representative of this interface when there really isn't.
13094 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13095 // even if we believe that we previously had an active representative of this interface.
13096 if (set
->McastTxRx
&& (FirstOfType
|| set
->InterfaceActive
))
13099 // Normally, after an interface comes up, we pause half a second before beginning probing.
13100 // This is to guard against cases where there's rapid interface changes, where we could be confused by
13101 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13102 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13103 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13104 // and think it's a conflicting answer to our probe.
13105 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13106 mDNSs32 probedelay
;
13107 mDNSu8 numannounce
;
13108 switch (activationSpeed
)
13110 case FastActivation
:
13111 probedelay
= (mDNSs32
)0;
13112 numannounce
= InitialAnnounceCount
;
13113 LogMsg("mDNS_RegisterInterface: Using fast activation for DirectLink interface %s (%#a)", set
->ifname
, &set
->ip
);
13116 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13117 case SlowActivation
:
13118 probedelay
= mDNSPlatformOneSecond
* 5;
13119 numannounce
= (mDNSu8
)1;
13120 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a), doing slow activation", set
->ifname
, &set
->ip
);
13121 m
->mDNSStats
.InterfaceUpFlap
++;
13125 case NormalActivation
:
13127 probedelay
= mDNSPlatformOneSecond
/ 2;
13128 numannounce
= InitialAnnounceCount
;
13132 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set
->ifname
, &set
->ip
, probedelay
);
13134 // No probe or sending suppression on DirectLink type interfaces.
13135 if (activationSpeed
== FastActivation
)
13137 m
->SuppressSending
= 0;
13138 m
->SuppressProbes
= 0;
13142 // Use a small amount of randomness:
13143 // In the case of a network administrator turning on an Ethernet hub so that all the
13144 // connected machines establish link at exactly the same time, we don't want them all
13145 // to go and hit the network with identical queries at exactly the same moment.
13146 // We set a random delay of up to InitialQuestionInterval (1/3 second).
13147 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13148 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13149 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13150 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13151 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13152 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
13154 if (m
->SuppressProbes
== 0 ||
13155 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
13156 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
13159 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13160 // it here also handles the wake up case as the network link comes UP after waking causing
13161 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13162 // that the network link comes UP after 60 seconds and we never set the OWNER option
13163 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
13164 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "mDNS_RegisterInterface: Setting AnnounceOwner");
13166 m
->mDNSStats
.InterfaceUp
++;
13167 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
13169 if (mDNSOpaque16IsZero(q
->TargetQID
))
13171 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
13172 { // then reactivate this question
13173 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13174 // If flapping, delay between first and second queries is nine seconds instead of one second
13175 mDNSBool dodelay
= (activationSpeed
== SlowActivation
) && (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
13176 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
13177 mDNSs32 qdelay
= dodelay
? kDefaultQueryDelayTimeForFlappingInterface
: 0;
13178 if (dodelay
) LogInfo("No cache records expired for %##s (%s); delaying questions by %d seconds", q
->qname
.c
, DNSTypeName(q
->qtype
), qdelay
);
13180 mDNSs32 initial
= InitialQuestionInterval
;
13181 mDNSs32 qdelay
= 0;
13184 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
13186 q
->ThisQInterval
= initial
;
13187 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
13189 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
13190 q
->RecentAnswerPkts
= 0;
13191 SetNextQueryTime(m
,q
);
13196 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13197 // we now need them to re-probe if necessary, and then re-announce.
13198 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13200 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13202 mDNSCoreRestartRegistration(m
, rr
, numannounce
);
13205 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
13210 RestartRecordGetZoneData(m
);
13212 mDNS_UpdateAllowSleep(m
);
13215 return(mStatus_NoError
);
13218 mDNSlocal
void AdjustAddressRecordSetsEx(mDNS
*const m
, NetworkInterfaceInfo
*removedIntf
, mDNSBool forRandHostname
)
13220 NetworkInterfaceInfo
*intf
;
13221 const AuthRecord
*oldAR
;
13223 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13224 if (mDNSPlatformInterfaceIsAWDL(removedIntf
->InterfaceID
)) return;
13226 oldAR
= GetInterfaceAddressRecord(removedIntf
, forRandHostname
);
13227 newAR
= GetFirstAddressRecordEx(m
, forRandHostname
);
13228 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13231 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13232 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
)) continue;
13234 ar
= GetInterfaceAddressRecord(intf
, forRandHostname
);
13235 if (ar
->RRSet
== oldAR
)
13237 ar
->RRSet
= newAR
? newAR
: ar
;
13238 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "Changed RRSet for " PRI_S
, ARDisplayString(m
, ar
));
13239 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "New RRSet: " PRI_S
, ARDisplayString(m
, ar
->RRSet
));
13243 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13244 #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue)
13246 #define AdjustAddressRecordSets(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse)
13248 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13249 // the record list and/or question list.
13250 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13251 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, InterfaceActivationSpeed activationSpeed
)
13253 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13254 (void)activationSpeed
; // Unused parameter
13256 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
13257 mDNSBool revalidate
= mDNSfalse
;
13258 NetworkInterfaceInfo
*intf
;
13262 // Find this record in our list
13263 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
13264 if (!*p
) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m
); return; }
13266 mDNS_DeactivateNetWake_internal(m
, set
);
13268 // Unlink this record from our list
13270 set
->next
= mDNSNULL
;
13272 if (!set
->InterfaceActive
)
13274 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13275 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13276 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
13277 UpdateInterfaceProtocols(m
, intf
);
13281 intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
13284 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13285 " making it active", IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13286 if (intf
->InterfaceActive
)
13287 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set
->ifname
, &set
->ip
);
13288 intf
->InterfaceActive
= mDNStrue
;
13289 UpdateInterfaceProtocols(m
, intf
);
13291 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
13293 // See if another representative *of the same type* exists. If not, we mave have gone from
13294 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13295 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13296 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
13298 if (!intf
) revalidate
= mDNStrue
;
13307 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13308 " marking questions etc. dormant", IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13310 m
->mDNSStats
.InterfaceDown
++;
13312 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13313 if (set
->McastTxRx
&& (activationSpeed
== SlowActivation
))
13315 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set
->ifname
, &set
->ip
);
13316 m
->mDNSStats
.InterfaceDownFlap
++;
13320 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13321 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13322 for (q
= m
->Questions
; q
; q
=q
->next
)
13324 if (mDNSOpaque16IsZero(q
->TargetQID
)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13326 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
13327 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
13329 q
->FlappingInterface2
= q
->FlappingInterface1
;
13330 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
13335 // 2. Flush any cache records received on this interface
13336 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
13337 FORALL_CACHERECORDS(slot
, cg
, rr
)
13339 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13341 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13342 // If this interface is deemed flapping,
13343 // postpone deleting the cache records in case the interface comes back again
13344 if (set
->McastTxRx
&& (activationSpeed
== SlowActivation
))
13346 // For a flapping interface we want these records to go away after
13347 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13348 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13349 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13350 // if the interface does come back, any relevant questions will be reactivated anyway
13351 rr
->UnansweredQueries
= MaxUnansweredQueries
;
13356 rr
->resrec
.mortality
= Mortality_Mortal
;
13357 mDNS_PurgeCacheResourceRecord(m
, rr
);
13364 // If we still have address records referring to this one, update them.
13365 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13366 // so the call to AdjustAddressRecordSets*() won’t accidentally find it.
13367 AdjustAddressRecordSets(m
, set
);
13368 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13369 AdjustAddressRecordSetsForRandHostname(m
, set
);
13372 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13373 if (set
->Advertise
) DeadvertiseInterface(m
, set
, kDeadvertiseFlag_All
);
13375 // If we have any cache records received on this interface that went away, then re-verify them.
13376 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13377 // giving the false impression that there's an active representative of this interface when there really isn't.
13378 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13379 if (revalidate
&& !m
->ShutdownTime
)
13384 FORALL_CACHERECORDS(slot
, cg
, rr
)
13385 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13386 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13389 mDNS_UpdateAllowSleep(m
);
13394 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13396 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13397 (void)m
; // Unused parameter
13401 char *msg
= "Unknown result";
13402 if (result
== mStatus_NoError
) msg
= "Name Registered";
13403 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
13404 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
13405 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
13409 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13410 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
13412 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13413 if (result
== mStatus_NameConflict
)
13415 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
13416 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
13420 if (result
== mStatus_MemFree
)
13422 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13423 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13424 // every record is finished cleaning up.
13426 ExtraResourceRecord
*e
= sr
->Extras
;
13428 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13429 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13430 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13431 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13432 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13436 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13440 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13441 // then we can now report the NameConflict to the client
13442 if (sr
->Conflict
) result
= mStatus_NameConflict
;
13446 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered" : "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
13447 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13448 // function is allowed to do anything, including deregistering this service and freeing its memory.
13449 if (sr
->ServiceCallback
)
13450 sr
->ServiceCallback(m
, sr
, result
);
13453 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13455 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13456 if (sr
->ServiceCallback
)
13457 sr
->ServiceCallback(m
, sr
, result
);
13461 // Derive AuthRecType from the kDNSServiceFlags* values.
13462 mDNSlocal AuthRecType
setAuthRecType(mDNSInterfaceID InterfaceID
, mDNSu32 flags
)
13464 AuthRecType artype
;
13466 if (InterfaceID
== mDNSInterface_LocalOnly
)
13467 artype
= AuthRecordLocalOnly
;
13468 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13469 artype
= AuthRecordP2P
;
13470 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
)
13471 && (flags
& kDNSServiceFlagsIncludeAWDL
))
13472 artype
= AuthRecordAnyIncludeAWDLandP2P
;
13473 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
))
13474 artype
= AuthRecordAnyIncludeP2P
;
13475 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeAWDL
))
13476 artype
= AuthRecordAnyIncludeAWDL
;
13478 artype
= AuthRecordAny
;
13484 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13485 // Type is service type (e.g. "_ipp._tcp.")
13486 // Domain is fully qualified domain name (i.e. ending with a null label)
13487 // We always register a TXT, even if it is empty (so that clients are not
13488 // left waiting forever looking for a nonexistent record.)
13489 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13490 // then the default host name (m->MulticastHostname) is automatically used
13491 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13492 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
13493 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13494 const domainname
*const host
, mDNSIPPort port
, RData
*const txtrdata
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
13495 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
13496 mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
, mDNSu32 flags
)
13500 AuthRecType artype
;
13501 mDNSu8 recordType
= (flags
& kDNSServiceFlagsKnownUnique
) ? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
13503 sr
->ServiceCallback
= Callback
;
13504 sr
->ServiceContext
= Context
;
13505 sr
->Conflict
= mDNSfalse
;
13507 sr
->Extras
= mDNSNULL
;
13508 sr
->NumSubTypes
= NumSubTypes
;
13509 sr
->SubTypes
= SubTypes
;
13512 artype
= setAuthRecType(InterfaceID
, flags
);
13514 // Initialize the AuthRecord objects to sane values
13515 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13516 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, artype
, ServiceCallback
, sr
);
13517 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13519 if (flags
& kDNSServiceFlagsWakeOnlyService
)
13521 sr
->RR_PTR
.AuthFlags
= AuthFlagsWakeOnly
;
13524 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, recordType
, artype
, ServiceCallback
, sr
);
13525 mDNS_SetupResourceRecord(&sr
->RR_TXT
, txtrdata
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, recordType
, artype
, ServiceCallback
, sr
);
13527 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13528 if (mDNSIPPortIsZero(port
))
13529 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, InterfaceID
, NSSCallback
, sr
, flags
));
13531 // If the caller is registering an oversized TXT record,
13532 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13533 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
13534 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
13536 // Set up the record names
13537 // For now we only create an advisory record for the main type, not for subtypes
13538 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13539 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
13540 return(mStatus_BadParamErr
);
13541 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13542 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13543 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13545 // 1. Set up the ADV record rdata to advertise our service type
13546 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
13548 // 2. Set up the PTR record rdata to point to our service name
13549 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13550 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13551 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
13552 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
13553 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
13555 // 2a. Set up any subtype PTRs to point to our service name
13556 // If the client is using subtypes, it is the client's responsibility to have
13557 // already set the first label of the record name to the subtype being registered
13558 for (i
=0; i
<NumSubTypes
; i
++)
13561 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
13562 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13563 AppendDomainName(&st
, type
);
13564 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13565 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13566 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
13567 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
13568 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
13571 // 3. Set up the SRV record rdata.
13572 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
13573 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
13574 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
13576 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13577 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
13578 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
13580 // 4. Set up the TXT record rdata,
13581 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13582 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13583 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
13584 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
13586 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
13587 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
13588 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
13590 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
13593 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13594 // that if the SRV cannot find a target, rest of the records that belong to this service
13595 // will not be activated.
13596 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
13597 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13598 // any list and hence no need to deregister. We could probably do similar checks for other
13599 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13605 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
13606 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13607 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13608 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13609 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13610 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13611 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
13612 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
13613 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
13617 if (err
) mDNS_DeregisterService(m
, sr
);
13621 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
13622 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
, mDNSu32 flags
)
13624 ExtraResourceRecord
**e
;
13626 AuthRecType artype
;
13627 mDNSInterfaceID InterfaceID
= sr
->RR_PTR
.resrec
.InterfaceID
;
13628 ResourceRecord
*rr
;
13630 artype
= setAuthRecType(InterfaceID
, flags
);
13632 extra
->next
= mDNSNULL
;
13633 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
13634 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
13635 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13639 if (extra
->r
.resrec
.rrtype
== kDNSType_TXT
)
13641 if (sr
->RR_TXT
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_TXT
.resrec
;
13643 else if (extra
->r
.resrec
.rrtype
== kDNSType_SRV
)
13645 if (sr
->RR_SRV
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_SRV
.resrec
;
13650 ExtraResourceRecord
*srExtra
;
13652 for (srExtra
= sr
->Extras
; srExtra
; srExtra
= srExtra
->next
)
13654 if ((srExtra
->r
.resrec
.rrtype
== extra
->r
.resrec
.rrtype
) && (srExtra
->r
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
13656 rr
= &srExtra
->r
.resrec
;
13662 if (rr
&& (extra
->r
.resrec
.rroriginalttl
!= rr
->rroriginalttl
))
13664 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13665 extra
->r
.resrec
.rroriginalttl
, rr
->rroriginalttl
, RRDisplayString(m
, &extra
->r
.resrec
));
13666 extra
->r
.resrec
.rroriginalttl
= rr
->rroriginalttl
;
13670 while (*e
) e
= &(*e
)->next
;
13672 extra
->r
.DependentOn
= &sr
->RR_SRV
;
13674 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13675 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
13677 status
= mDNS_Register_internal(m
, &extra
->r
);
13678 if (status
== mStatus_NoError
) *e
= extra
;
13684 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
13685 mDNSRecordCallback MemFreeCallback
, void *Context
)
13687 ExtraResourceRecord
**e
;
13692 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
13695 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
13696 status
= mStatus_BadReferenceErr
;
13700 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
13701 extra
->r
.RecordCallback
= MemFreeCallback
;
13702 extra
->r
.RecordContext
= Context
;
13704 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
13710 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
13712 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13713 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13714 domainlabel name1
, name2
;
13715 domainname type
, domain
;
13716 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
13717 ExtraResourceRecord
*extras
= sr
->Extras
;
13720 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
13724 IncrementLabelSuffix(&name2
, mDNStrue
);
13728 if (SameDomainName(&domain
, &localdomain
))
13729 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
13730 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
13732 // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13733 // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13734 if (sr
->RR_TXT
.NewRData
) CompleteRDataUpdate(m
, &sr
->RR_TXT
);
13735 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
13736 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
,
13737 (sr
->RR_TXT
.resrec
.rdata
!= &sr
->RR_TXT
.rdatastorage
) ? sr
->RR_TXT
.resrec
.rdata
: mDNSNULL
,
13738 sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
13739 sr
->SubTypes
, sr
->NumSubTypes
,
13740 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
, sr
->flags
);
13742 // mDNS_RegisterService() just reset sr->Extras to NULL.
13743 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13744 // through the old list of extra records, and re-add them to our freshly created service registration
13745 while (!err
&& extras
)
13747 ExtraResourceRecord
*e
= extras
;
13748 extras
= extras
->next
;
13749 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
, 0);
13755 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13756 // which may change the record list and/or question list.
13757 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13758 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
13760 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13761 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
13763 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
13765 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
13766 return(mStatus_BadReferenceErr
);
13768 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
13770 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
13771 // Avoid race condition:
13772 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13773 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13774 // If the client happens to deregister the service in the middle of that process, then
13775 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13776 // instead of incorrectly promoting it to mStatus_NameConflict.
13777 // This race condition is exposed particularly when the conformance test generates
13778 // a whole batch of simultaneous conflicts across a range of services all advertised
13779 // using the same system default name, and if we don't take this precaution then
13780 // we end up incrementing m->nicelabel multiple times instead of just once.
13781 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13782 sr
->Conflict
= mDNSfalse
;
13783 return(mStatus_NoError
);
13789 ExtraResourceRecord
*e
;
13793 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13794 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13795 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
13796 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
13797 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
13799 // We deregister all of the extra records, but we leave the sr->Extras list intact
13800 // in case the client wants to do a RenameAndReregister and reinstate the registration
13803 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
13807 for (i
=0; i
<sr
->NumSubTypes
; i
++)
13808 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
13810 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
13816 // Create a registration that asserts that no such service exists with this name.
13817 // This can be useful where there is a given function is available through several protocols.
13818 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13819 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13820 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13821 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13822 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
13823 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13824 const domainname
*const host
,
13825 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
, mDNSu32 flags
)
13827 AuthRecType artype
;
13829 artype
= setAuthRecType(InterfaceID
, flags
);
13831 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, artype
, Callback
, Context
);
13832 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13833 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
13834 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
13835 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
13836 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
13837 else rr
->AutoTarget
= Target_AutoHost
;
13838 return(mDNS_Register(m
, rr
));
13841 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
13842 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
13844 AuthRecType artype
;
13846 if (InterfaceID
== mDNSInterface_LocalOnly
)
13847 artype
= AuthRecordLocalOnly
;
13848 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13849 artype
= AuthRecordP2P
;
13851 artype
= AuthRecordAny
;
13852 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, mDNSNULL
, mDNSNULL
);
13853 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
13854 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
13855 return(mDNS_Register(m
, rr
));
13858 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
13861 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
13865 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
13868 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
13872 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
13877 for (i
=0; i
<10; i
++)
13879 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
13880 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
13883 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
13888 // ***************************************************************************
13889 #if COMPILER_LIKES_PRAGMA_MARK
13891 #pragma mark - Sleep Proxy Server
13894 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
13896 // If we see an ARP from a machine we think is sleeping, then either
13897 // (i) the machine has woken, or
13898 // (ii) it's just a stray old packet from before the machine slept
13899 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13900 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13901 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13902 // 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*
13903 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13904 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13906 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
13907 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
13908 rr
->ProbeRestartCount
++;
13910 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13911 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13912 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13913 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13914 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13915 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13916 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
13917 InitializeLastAPTime(m
, rr
);
13920 rr
->AnnounceCount
= InitialAnnounceCount
;
13921 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
13922 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13923 SetNextAnnounceProbeTime(m
, rr
);
13927 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
13929 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
13931 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
13937 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13938 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13939 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13940 // The times we might need to react to an ARP Announcement are:
13941 // (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
13942 // (ii) if it's a conflicting Announcement from another host
13943 // -- and we check for these in Pass 2 below.
13944 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
13946 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13947 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13948 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
13950 static const char msg1
[] = "ARP Req from owner -- re-probing";
13951 static const char msg2
[] = "Ignoring ARP Request from ";
13952 static const char msg3
[] = "Creating Local ARP Cache entry ";
13953 static const char msg4
[] = "Answering ARP Request from ";
13954 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
13955 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
13956 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
13957 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13958 intf
->ifname
, msg
, arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
,
13959 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13962 if ( rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
13963 RestartARPProbing(m
, rr
);
13965 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
13967 else if (msg
== msg3
)
13969 mDNSPlatformSetLocalAddressCacheEntry(&rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
13971 else if (msg
== msg4
)
13973 SendARP(m
, 2, rr
, (mDNSv4Addr
*)arp
->tpa
.b
, &arp
->sha
, (mDNSv4Addr
*)arp
->spa
.b
, &arp
->sha
);
13979 // 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.
13980 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13981 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13982 // 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.
13983 // If we see an apparently conflicting ARP, we check the sender hardware address:
13984 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13985 // 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.
13986 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
13987 debugf("ARP from self for %.4a", arp
->tpa
.b
);
13990 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
13991 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13992 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13993 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
13995 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
13997 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
13998 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14002 RestartARPProbing(m
, rr
);
14003 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
14005 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
14006 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
14007 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, ARDisplayString(m
, rr
));
14011 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14012 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14013 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14023 // Option 1 is Source Link Layer Address Option
14024 // Option 2 is Target Link Layer Address Option
14025 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14027 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14028 while (options < end)
14030 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14031 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14032 options += options[1] * 8;
14038 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
14039 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
14042 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
14047 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14048 if (ndp
->type
== NDP_Sol
)
14050 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14052 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14053 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14054 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
14056 static const char msg1
[] = "NDP Req from owner -- re-probing";
14057 static const char msg2
[] = "Ignoring NDP Request from ";
14058 static const char msg3
[] = "Creating Local NDP Cache entry ";
14059 static const char msg4
[] = "Answering NDP Request from ";
14060 static const char msg5
[] = "Answering NDP Probe from ";
14061 const char *const msg
= mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
14062 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
14063 mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
14064 mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
14065 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14066 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14069 if (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
14070 RestartARPProbing(m
, rr
);
14072 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
14074 else if (msg
== msg3
)
14075 mDNSPlatformSetLocalAddressCacheEntry(&rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
14076 else if (msg
== msg4
)
14077 SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
14078 else if (msg
== msg5
)
14079 SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
14083 // 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.
14084 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
14085 debugf("NDP from self for %.16a", &ndp
->target
);
14088 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14089 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14090 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14091 // Hence it is the NDP target address we care about, not the actual packet source address.
14092 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
14093 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
14094 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14095 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14096 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
14098 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
14100 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14101 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14105 RestartARPProbing(m
, rr
);
14106 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
14108 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
14109 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
14113 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14114 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14115 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14124 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
14125 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
14127 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
14128 mDNSBool wake
= mDNSfalse
;
14129 mDNSBool kaWake
= mDNSfalse
;
14133 #define XX wake ? "Received" : "Ignoring", end-p
14134 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
14140 #define TH_FIN 0x01
14141 #define TH_SYN 0x02
14142 #define TH_RST 0x04
14143 #define TH_ACK 0x10
14145 kr
= mDNS_MatchKeepaliveInfo(m
, dst
, src
, port
, t
->tcp
.src
, &seq
, &ack
);
14148 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
));
14150 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14151 // (b) packet that contains new data and acks a sequence number higher than the one
14152 // we have been sending in the keepalive
14154 wake
= ((t
->tcp
.flags
& TH_RST
) || (t
->tcp
.flags
& TH_FIN
)) ;
14158 mDNSu32 pseq
, pack
;
14159 mDNSBool data
= mDNSfalse
;
14162 // Convert to host order
14163 ptr
= (mDNSu8
*)&seq
;
14164 seq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14166 ptr
= (mDNSu8
*)&ack
;
14167 ack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14170 ptr
= (mDNSu8
*)&pseq
;
14171 pseq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14174 ptr
= (mDNSu8
*)&pack
;
14175 pack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14177 // If the other side is acking one more than our sequence number (keepalive is one
14178 // less than the last valid sequence sent) and it's sequence is more than what we
14180 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14181 tcphlen
= ((t
->tcp
.offset
>> 4) * 4);
14182 if (end
- ((mDNSu8
*)t
+ tcphlen
) > 0) data
= mDNStrue
;
14183 wake
= ((int)(pack
- seq
) > 0) && ((int)(pseq
- ack
) >= 0) && data
;
14185 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14186 if ((t
->tcp
.flags
& TH_ACK
) && (data
== mDNSfalse
) &&
14187 ((int)(ack
- pseq
) == 1))
14190 mDNS_SendKeepaliveACK(m
, kr
);
14192 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14193 end
, tcphlen
, end
- ((mDNSu8
*)t
+ tcphlen
), pack
, seq
, pseq
, ack
, wake
);
14195 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t
->tcp
.flags
); }
14201 // (a) RST is not set, AND
14202 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14203 wake
= (!(t
->tcp
.flags
& TH_RST
) && (t
->tcp
.flags
& (TH_FIN
|TH_SYN
)) != TH_FIN
);
14205 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14206 // except for ssh connections, where we'll wake for plain data packets too
14207 if (!mDNSSameIPPort(port
, SSHPort
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
14209 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
14210 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
14211 (t
->tcp
.flags
& 2) ? " SYN" : "",
14212 (t
->tcp
.flags
& 1) ? " FIN" : "",
14213 (t
->tcp
.flags
& 4) ? " RST" : "");
14219 #define ARD_AsNumber 3283
14220 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
14221 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
14222 if (udplen
>= sizeof(UDPHeader
))
14224 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
14227 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14228 if (mDNSSameIPPort(port
, IPSECPort
))
14230 // Specifically ignore NAT keepalive packets
14231 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
14234 // Skip over the Non-ESP Marker if present
14235 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
14236 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
14237 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
14238 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
14239 if ((ike
->Version
& 0x10) == 0x10)
14241 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14242 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14243 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
14244 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
14249 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14250 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14251 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14252 // UDP header (8 bytes)
14253 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14254 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
14256 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
14261 case 0x3A: if (&t
->bytes
[len
] <= end
)
14263 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
14264 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
14265 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
14269 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
14275 AuthRecord
*rr
, *r2
;
14278 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14279 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
14280 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14281 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
14283 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
14284 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
14285 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
14286 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14287 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
14288 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
14290 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14291 if (!r2
&& kaWake
) r2
= rr
; // So that we wake for keepalive packets, even without a matching SRV record
14294 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14295 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
14296 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14299 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14300 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
14306 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
14308 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14309 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14310 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14311 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14312 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14314 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14315 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14316 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14317 // since it points to a an address 14 bytes before pkt.
14318 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
14319 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
14321 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14323 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14324 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
14325 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
14326 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14327 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
14329 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
14330 const mDNSu8
* transEnd
= p
+ 14 + mDNSVal16(pkt
->v4
.totlen
);
14331 if (transEnd
> end
) transEnd
= end
;
14332 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
.b
, &pkt
->v4
.dst
.b
);
14333 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
14334 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
14335 if (transEnd
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
14336 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, transEnd
, InterfaceID
, 0);
14338 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14339 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
14341 const mDNSu8
*const trans
= p
+ 54;
14342 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
.b
, &pkt
->v6
.dst
.b
);
14343 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
14344 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
14345 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
14346 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
14347 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
14351 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
14353 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d.%d %#s",
14354 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
, &m
->nicelabel
);
14357 #ifndef SPC_DISABLED
14358 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
14360 if (result
== mStatus_NameConflict
)
14361 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
14362 else if (result
== mStatus_MemFree
)
14368 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
14372 ConstructSleepProxyServerName(m
, &name
);
14373 mDNS_RegisterService(m
, srs
,
14374 &name
, &SleepProxyServiceType
, &localdomain
,
14375 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
14377 (mDNSu8
*)"", 1, // TXT data, length
14378 mDNSNULL
, 0, // Subtypes (none)
14379 mDNSInterface_Any
, // Interface ID
14380 SleepProxyServerCallback
, mDNSNULL
, 0); // Callback, context, flags
14382 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
14388 // Called with lock held
14389 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
, mDNSu8 features
)
14391 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14392 mDNS_DropLockBeforeCallback();
14394 // If turning off SPS, close our socket
14395 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14396 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
14398 // If turning off, or changing type, deregister old name
14399 #ifndef SPC_DISABLED
14400 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
14401 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
14402 #endif // SPC_DISABLED
14404 // Record our new SPS parameters
14406 m
->SPSPortability
= port
;
14407 m
->SPSMarginalPower
= marginalpower
;
14408 m
->SPSTotalPower
= totpower
;
14409 m
->SPSFeatureFlags
= features
;
14410 // If turning on, open socket and advertise service
14415 m
->SPSSocket
= mDNSPlatformUDPSocket(zeroIPPort
);
14416 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
14418 #ifndef SPC_DISABLED
14419 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
14420 #endif // SPC_DISABLED
14422 else if (m
->SPSState
)
14424 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
14425 m
->NextScheduledSPS
= m
->timenow
;
14428 mDNS_ReclaimLockAfterCallback();
14431 // ***************************************************************************
14432 #if COMPILER_LIKES_PRAGMA_MARK
14434 #pragma mark - Startup and Shutdown
14437 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14439 if (storage
&& numrecords
)
14442 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
14443 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
14444 storage
[numrecords
-1].next
= m
->rrcache_free
;
14445 m
->rrcache_free
= storage
;
14446 m
->rrcache_size
+= numrecords
;
14450 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14453 mDNS_GrowCache_internal(m
, storage
, numrecords
);
14457 mDNSlocal mStatus
mDNS_InitStorage(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14458 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14459 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14465 if (!rrcachestorage
) rrcachesize
= 0;
14467 m
->next_request_id
= 1;
14469 m
->NetworkChanged
= 0;
14470 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14471 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
14472 m
->DivertMulticastAdvertisements
= mDNSfalse
;
14473 m
->mDNSPlatformStatus
= mStatus_Waiting
;
14474 m
->UnicastPort4
= zeroIPPort
;
14475 m
->UnicastPort6
= zeroIPPort
;
14476 m
->PrimaryMAC
= zeroEthAddr
;
14477 m
->MainCallback
= Callback
;
14478 m
->MainContext
= Context
;
14479 m
->rec
.r
.resrec
.RecordType
= 0;
14481 // For debugging: To catch and report locking failures
14483 m
->mDNS_reentrancy
= 0;
14484 m
->ShutdownTime
= 0;
14485 m
->lock_rrcache
= 0;
14486 m
->lock_Questions
= 0;
14487 m
->lock_Records
= 0;
14489 // Task Scheduling variables
14490 result
= mDNSPlatformTimeInit();
14491 if (result
!= mStatus_NoError
) return(result
);
14492 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
14493 timenow
= mDNS_TimeNow_NoLock(m
);
14495 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14496 m
->timenow_last
= timenow
;
14497 m
->NextScheduledEvent
= timenow
;
14498 m
->SuppressSending
= timenow
;
14499 m
->NextCacheCheck
= timenow
+ FutureTime
;
14500 m
->NextScheduledQuery
= timenow
+ FutureTime
;
14501 m
->NextScheduledProbe
= timenow
+ FutureTime
;
14502 m
->NextScheduledResponse
= timenow
+ FutureTime
;
14503 m
->NextScheduledNATOp
= timenow
+ FutureTime
;
14504 m
->NextScheduledSPS
= timenow
+ FutureTime
;
14505 m
->NextScheduledKA
= timenow
+ FutureTime
;
14506 m
->NextScheduledStopTime
= timenow
+ FutureTime
;
14507 m
->NextBLEServiceTime
= 0; // zero indicates inactive
14509 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14510 m
->NextBonjourDisableTime
= 0; // Timer active when non zero.
14511 m
->BonjourEnabled
= 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14513 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
14514 m
->NextSuspiciousTimeout
= 0;
14517 m
->RandomQueryDelay
= 0;
14518 m
->RandomReconfirmDelay
= 0;
14521 m
->LocalRemoveEvents
= mDNSfalse
;
14522 m
->SleepState
= SleepState_Awake
;
14523 m
->SleepSeqNum
= 0;
14524 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
14525 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
14529 #if APPLE_OSX_mDNSResponder
14530 m
->UnicastPacketsSent
= 0;
14531 m
->MulticastPacketsSent
= 0;
14532 m
->RemoteSubnet
= 0;
14533 #endif // APPLE_OSX_mDNSResponder
14535 // These fields only required for mDNS Searcher...
14536 m
->Questions
= mDNSNULL
;
14537 m
->NewQuestions
= mDNSNULL
;
14538 m
->CurrentQuestion
= mDNSNULL
;
14539 m
->LocalOnlyQuestions
= mDNSNULL
;
14540 m
->NewLocalOnlyQuestions
= mDNSNULL
;
14541 m
->RestartQuestion
= mDNSNULL
;
14542 m
->ValidationQuestion
= mDNSNULL
;
14543 m
->rrcache_size
= 0;
14544 m
->rrcache_totalused
= 0;
14545 m
->rrcache_active
= 0;
14546 m
->rrcache_report
= 10;
14547 m
->rrcache_free
= mDNSNULL
;
14549 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
14551 m
->rrcache_hash
[slot
] = mDNSNULL
;
14552 m
->rrcache_nextcheck
[slot
] = timenow
+ FutureTime
;;
14555 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
14556 m
->rrauth
.rrauth_free
= mDNSNULL
;
14558 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
14559 m
->rrauth
.rrauth_hash
[slot
] = mDNSNULL
;
14561 // Fields below only required for mDNS Responder...
14562 m
->hostlabel
.c
[0] = 0;
14563 m
->nicelabel
.c
[0] = 0;
14564 m
->MulticastHostname
.c
[0] = 0;
14565 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14566 m
->RandomizedHostname
.c
[0] = 0;
14568 m
->HIHardware
.c
[0] = 0;
14569 m
->HISoftware
.c
[0] = 0;
14570 m
->ResourceRecords
= mDNSNULL
;
14571 m
->DuplicateRecords
= mDNSNULL
;
14572 m
->NewLocalRecords
= mDNSNULL
;
14573 m
->NewLocalOnlyRecords
= mDNSfalse
;
14574 m
->CurrentRecord
= mDNSNULL
;
14575 m
->HostInterfaces
= mDNSNULL
;
14576 m
->ProbeFailTime
= 0;
14577 m
->NumFailedProbes
= 0;
14578 m
->SuppressProbes
= 0;
14580 #ifndef UNICAST_DISABLED
14581 m
->NextuDNSEvent
= timenow
+ FutureTime
;
14582 m
->NextSRVUpdate
= timenow
+ FutureTime
;
14584 m
->DNSServers
= mDNSNULL
;
14586 m
->Router
= zeroAddr
;
14587 m
->AdvertisedV4
= zeroAddr
;
14588 m
->AdvertisedV6
= zeroAddr
;
14590 m
->AuthInfoList
= mDNSNULL
;
14592 m
->ReverseMap
.ThisQInterval
= -1;
14593 m
->StaticHostname
.c
[0] = 0;
14595 m
->Hostnames
= mDNSNULL
;
14597 m
->WABBrowseQueriesCount
= 0;
14598 m
->WABLBrowseQueriesCount
= 0;
14599 m
->WABRegQueriesCount
= 0;
14600 m
->AutoTargetServices
= 0;
14602 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14603 m
->NumAllInterfaceRecords
= 0;
14604 m
->NumAllInterfaceQuestions
= 0;
14606 // NAT traversal fields
14607 m
->LLQNAT
.clientCallback
= mDNSNULL
;
14608 m
->LLQNAT
.clientContext
= mDNSNULL
;
14609 m
->NATTraversals
= mDNSNULL
;
14610 m
->CurrentNATTraversal
= mDNSNULL
;
14611 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
14612 m
->retryGetAddr
= timenow
+ FutureTime
; // absolute time when we retry
14613 m
->ExtAddress
= zerov4Addr
;
14614 m
->PCPNonce
[0] = mDNSRandom(-1);
14615 m
->PCPNonce
[1] = mDNSRandom(-1);
14616 m
->PCPNonce
[2] = mDNSRandom(-1);
14618 m
->NATMcastRecvskt
= mDNSNULL
;
14619 m
->LastNATupseconds
= 0;
14620 m
->LastNATReplyLocalTime
= timenow
;
14621 m
->LastNATMapResultCode
= NATErr_None
;
14623 m
->UPnPInterfaceID
= 0;
14624 m
->SSDPSocket
= mDNSNULL
;
14625 m
->SSDPWANPPPConnection
= mDNSfalse
;
14626 m
->UPnPRouterPort
= zeroIPPort
;
14627 m
->UPnPSOAPPort
= zeroIPPort
;
14628 m
->UPnPRouterURL
= mDNSNULL
;
14629 m
->UPnPWANPPPConnection
= mDNSfalse
;
14630 m
->UPnPSOAPURL
= mDNSNULL
;
14631 m
->UPnPRouterAddressString
= mDNSNULL
;
14632 m
->UPnPSOAPAddressString
= mDNSNULL
;
14634 m
->SPSPortability
= 0;
14635 m
->SPSMarginalPower
= 0;
14636 m
->SPSTotalPower
= 0;
14637 m
->SPSFeatureFlags
= 0;
14639 m
->SPSProxyListChanged
= mDNSNULL
;
14640 m
->SPSSocket
= mDNSNULL
;
14641 m
->SPSBrowseCallback
= mDNSNULL
;
14642 m
->ProxyRecords
= 0;
14644 m
->DNSPushServers
= mDNSNULL
;
14645 m
->DNSPushZones
= mDNSNULL
;
14648 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14649 if (WCFConnectionNew
)
14651 m
->WCF
= WCFConnectionNew();
14652 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
14659 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14660 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14661 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14663 mStatus result
= mDNS_InitStorage(m
, p
, rrcachestorage
, rrcachesize
, AdvertiseLocalAddresses
, Callback
, Context
);
14664 if (result
!= mStatus_NoError
)
14667 #if MDNS_MALLOC_DEBUGGING
14668 static mDNSListValidator lv
;
14669 mDNSPlatformAddListValidator(&lv
, mDNS_ValidateLists
, "mDNS_ValidateLists", m
);
14671 result
= mDNSPlatformInit(m
);
14673 #ifndef UNICAST_DISABLED
14674 // It's better to do this *after* the platform layer has set up the
14675 // interface list and security credentials
14676 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
14682 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
14684 if (m
->SPSState
== 1)
14686 domainlabel name
, newname
;
14687 #ifndef SPC_DISABLED
14688 domainname type
, domain
;
14689 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
14690 #endif // SPC_DISABLED
14691 ConstructSleepProxyServerName(m
, &newname
);
14692 if (!SameDomainLabelCS(name
.c
, newname
.c
))
14694 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
14695 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14696 // it will reregister the service under the new name
14698 #ifndef SPC_DISABLED
14699 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
14700 #endif // SPC_DISABLED
14704 if (m
->MainCallback
)
14705 m
->MainCallback(m
, mStatus_ConfigChanged
);
14708 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
14711 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
14712 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
14715 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
)
14717 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
14718 cr
->resrec
.rrtype
== kDNSType_A
||
14719 cr
->resrec
.rrtype
== kDNSType_AAAA
||
14720 cr
->resrec
.rrtype
== kDNSType_SRV
||
14721 cr
->resrec
.rrtype
== kDNSType_CNAME
;
14723 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14724 purge
? "purging" : "reconfirming",
14725 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
,
14726 cr
->resrec
.rDNSServer
? mDNSVal16(cr
->resrec
.rDNSServer
->port
) : -1,
14727 cr
->resrec
.rDNSServer
? cr
->resrec
.rDNSServer
->domain
.c
: mDNSNULL
, CRDisplayString(m
, cr
));
14731 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14732 cr
->resrec
.mortality
= Mortality_Mortal
;
14733 mDNS_PurgeCacheResourceRecord(m
, cr
);
14737 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14738 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
14742 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
)
14744 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
14746 mDNSu8 validatingResponse
= 0;
14748 // For DNSSEC questions, purge the corresponding RRSIGs also.
14749 if (DNSSECQuestion(q
))
14751 validatingResponse
= q
->ValidatingResponse
;
14752 q
->ValidatingResponse
= mDNStrue
;
14754 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14756 if (SameNameCacheRecordAnswersQuestion(rp
, q
))
14758 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m
, rp
));
14759 mDNS_PurgeCacheResourceRecord(m
, rp
);
14762 if (DNSSECQuestion(q
))
14764 q
->ValidatingResponse
= validatingResponse
;
14768 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14769 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14770 // Just re-issuing the question for RRSIGs does not work in practice as the response
14771 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14773 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14774 // have the cached NSECs, purge them. For positive responses, if we don't have the
14775 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14777 mDNSlocal
void CheckForDNSSECRecords(mDNS
*const m
, DNSQuestion
*q
)
14779 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
14782 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14784 if (SameNameCacheRecordAnswersQuestion(rp
, q
))
14786 if (rp
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| !rp
->nsec
)
14788 if (!rp
->CRDNSSECQuestion
)
14790 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m
, rp
));
14791 mDNS_PurgeCacheResourceRecord(m
, rp
);
14798 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
14804 if (q
->DuplicateOf
)
14805 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
14807 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14808 // of events for all of them are consistent. Duplicates for a question are always inserted
14809 // after in the list.
14810 q
->qDNSServer
= new;
14811 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14813 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
14817 mDNSlocal
void SetConfigState(mDNS
*const m
, mDNSBool
delete)
14824 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14826 ptr
->penaltyTime
= 0;
14827 ptr
->flags
|= DNSServerFlag_Delete
;
14828 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14829 if (ptr
->flags
& DNSServerFlag_Unreachable
)
14830 NumUnreachableDNSServers
--;
14833 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14834 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14836 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14837 mr
->flags
|= McastResolver_FlagDelete
;
14841 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14843 ptr
->penaltyTime
= 0;
14844 ptr
->flags
&= ~DNSServerFlag_Delete
;
14845 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14846 if (ptr
->flags
& DNSServerFlag_Unreachable
)
14847 NumUnreachableDNSServers
++;
14850 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14851 mr
->flags
&= ~McastResolver_FlagDelete
;
14855 mDNSlocal
void SetDynDNSHostNameIfChanged(mDNS
*const m
, domainname
*const fqdn
)
14857 // Did our FQDN change?
14858 if (!SameDomainName(fqdn
, &m
->FQDN
))
14860 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
14862 AssignDomainName(&m
->FQDN
, fqdn
);
14866 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
14867 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
14872 // Even though this is called “Setup” it is not called just once at startup.
14873 // It’s actually called multiple times, every time there’s a configuration change.
14874 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
14879 mDNSAddr v4
, v6
, r
;
14881 DNSServer
*ptr
, **p
= &m
->DNSServers
;
14882 const DNSServer
*oldServers
= m
->DNSServers
;
14884 McastResolver
*mr
, **mres
= &m
->McastResolvers
;
14885 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14886 DNSPushNotificationServer
**psp
;
14889 debugf("uDNS_SetupDNSConfig: entry");
14891 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14892 uDNS_SetupWABQueries(m
);
14896 // We need to first mark all the entries to be deleted. If the configuration changed, then
14897 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14899 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14900 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14901 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14902 // for the dns configuration change notification.
14903 SetConfigState(m
, mDNStrue
);
14904 if (!mDNSPlatformSetDNSConfig(mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
, mDNStrue
))
14906 SetDynDNSHostNameIfChanged(m
, &fqdn
);
14907 SetConfigState(m
, mDNSfalse
);
14909 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14910 return mStatus_NoError
;
14912 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
14913 // Reset suspicious mode on any DNS configuration change
14914 m
->NextSuspiciousTimeout
= 0;
14917 // For now, we just delete the mcast resolvers. We don't deal with cache or
14918 // questions here. Neither question nor cache point to mcast resolvers. Questions
14919 // do inherit the timeout values from mcast resolvers. But we don't bother
14920 // affecting them as they never change.
14923 if (((*mres
)->flags
& McastResolver_FlagDelete
) != 0)
14926 *mres
= (*mres
)->next
;
14927 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr
, mr
->domain
.c
);
14928 mDNSPlatformMemFree(mr
);
14932 (*mres
)->flags
&= ~McastResolver_FlagNew
;
14933 mres
= &(*mres
)->next
;
14937 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14939 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14940 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14941 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14942 // DNSServers and flush the cache.
14944 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14945 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14946 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14947 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14948 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14949 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14950 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14951 // the same resGroupID.
14953 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14954 // of the old followed by ADD of the new records.
14956 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14957 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14958 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14960 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14961 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14962 // non-scoped question and vice versa.
14964 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14965 DNS64RestartQuestions(m
);
14968 // First, restart questions whose suppression status will change. The suppression status of each question in a given
14969 // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14970 // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14971 // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14972 // suppressed (or non-suppressed).
14973 for (q
= m
->Questions
; q
; q
= q
->next
)
14976 const DNSServer
*t
;
14977 mDNSBool oldSuppressed
;
14979 if (mDNSOpaque16IsZero(q
->TargetQID
)) continue;
14981 SetValidDNSServers(m
, q
);
14982 q
->triedAllServersOnce
= mDNSfalse
;
14983 s
= GetServerForQuestion(m
, q
);
14987 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
14988 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR
":%d (" PRI_DM_NAME
") to "
14989 PRI_IP_ADDR
":%d (" PRI_DM_NAME
") for question " PRI_DM_NAME
" (" PUB_S
") (scope:%p)",
14990 q
->request_id
, mDNSVal16(q
->TargetQID
),
14991 t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), DM_NAME_PARAM(t
? t
->domain
.c
: (mDNSu8
*)""),
14992 s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), DM_NAME_PARAM(s
? s
->domain
.c
: (mDNSu8
*)""),
14993 DM_NAME_PARAM(q
->qname
.c
), DNSTypeName(q
->qtype
), q
->InterfaceID
);
14994 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14995 // If this question had a DNS Push server associated with it, substitute the new server for the
14996 // old one. If there is no new server, then we'll clean up the push server later.
14997 if (!q
->DuplicateOf
&& (q
->dnsPushServer
!= mDNSNULL
))
14999 if (q
->dnsPushServer
->qDNSServer
== t
)
15001 q
->dnsPushServer
->qDNSServer
= s
; // which might be null
15003 // If it is null, do the accounting and drop the push server.
15004 if (q
->dnsPushServer
->qDNSServer
== mDNSNULL
)
15006 DNSPushReconcileConnection(m
, q
);
15011 oldSuppressed
= q
->Suppressed
;
15012 q
->Suppressed
= ShouldSuppressUnicastQuery(q
, s
);
15013 if (!q
->Suppressed
!= !oldSuppressed
) q
->Restart
= mDNStrue
;
15015 RestartUnicastQuestions(m
);
15017 // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
15018 // have already had their server changed by being restarted.
15019 for (q
= m
->Questions
; q
; q
= q
->next
)
15022 const DNSServer
*t
;
15024 if (mDNSOpaque16IsZero(q
->TargetQID
) || q
->DuplicateOf
) continue;
15026 SetValidDNSServers(m
, q
);
15027 q
->triedAllServersOnce
= mDNSfalse
;
15028 s
= GetServerForQuestion(m
, q
);
15030 DNSServerChangeForQuestion(m
, q
, s
);
15031 if (s
== t
) continue;
15033 q
->Suppressed
= ShouldSuppressUnicastQuery(q
, s
);
15034 q
->unansweredQueries
= 0;
15035 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
15036 q
->LastTargetQID
= q
->TargetQID
;
15038 q
->TargetQID
= mDNS_NewMessageID(m
);
15039 if (!q
->Suppressed
) ActivateUnicastQuery(m
, q
, mDNStrue
);
15042 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15043 // The above code may have found some DNS Push servers that are no longer valid. Now that we
15044 // are done running through the code, we need to drop our connections to those servers.
15045 // When we get here, any such servers should have zero questions associated with them.
15046 for (psp
= &m
->DNSPushServers
; *psp
!= mDNSNULL
; )
15048 DNSPushNotificationServer
*server
= *psp
;
15050 // It's possible that a push server whose DNS server has been deleted could be still connected but
15051 // not referenced by any questions. In this case, we just delete the push server rather than trying
15052 // to figure out with which DNS server (if any) to associate it.
15053 if (server
->qDNSServer
!= mDNSNULL
&& server
->qDNSServer
->flags
& DNSServerFlag_Delete
)
15055 server
->qDNSServer
= mDNSNULL
;
15058 if (server
->qDNSServer
== mDNSNULL
)
15060 // This would be a programming error, so should never happen.
15061 if (server
->numberOfQuestions
!= 0)
15063 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server
->serverName
);
15065 DNSPushServerDrop(server
);
15066 *psp
= server
->next
;
15067 mDNSPlatformMemFree(server
);
15071 psp
= &(*psp
)->next
;
15076 FORALL_CACHERECORDS(slot
, cg
, cr
)
15078 if (cr
->resrec
.InterfaceID
) continue;
15080 // We already walked the questions and restarted/reactivated them if the dns server
15081 // change affected the question. That should take care of updating the cache. But
15082 // what if there is no active question at this point when the DNS server change
15083 // happened ? There could be old cache entries lying around and if we don't flush
15084 // them, a new question after the DNS server change could pick up these stale
15085 // entries and get a wrong answer.
15087 // For cache entries that have active questions we might have skipped rescheduling
15088 // the questions if they were suppressed (see above). To keep it simple, we walk
15089 // all the cache entries to make sure that there are no stale entries. We use the
15090 // active question's InterfaceID/ServiceID for looking up the right DNS server.
15092 // Note: If GetServerForName returns NULL, it could either mean that there are no
15093 // DNS servers or no matching DNS servers for this question. In either case,
15094 // the cache should get purged below when we process deleted DNS servers.
15096 // If it is a DNSSEC question, purge the cache as the DNSSEC capabilities of the
15097 // DNS server may have changed.
15099 if (cr
->CRActiveQuestion
&& !DNSSECQuestion(cr
->CRActiveQuestion
))
15101 // Purge or Reconfirm if this cache entry would use the new DNS server
15102 ptr
= GetServerForName(m
, cr
->resrec
.name
, cr
->CRActiveQuestion
->InterfaceID
, cr
->CRActiveQuestion
->ServiceID
);
15103 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
15105 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15106 CRDisplayString(m
, cr
), &ptr
->addr
,
15107 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
);
15108 PurgeOrReconfirmCacheRecord(m
, cr
);
15110 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15111 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15112 if (!cr
->resrec
.rDNSServer
&& cr
->CRActiveQuestion
->qDNSServer
)
15114 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr
->CRActiveQuestion
->qDNSServer
->addr
, CRDisplayString(m
, cr
));
15115 cr
->resrec
.rDNSServer
= cr
->CRActiveQuestion
->qDNSServer
;
15119 if (cr
->resrec
.rDNSServer
&& cr
->resrec
.rDNSServer
->flags
& DNSServerFlag_Delete
)
15121 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
15122 if (qptr
->qDNSServer
== cr
->resrec
.rDNSServer
)
15124 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15125 " to be freed", CRDisplayString(m
, cr
),
15126 qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
,
15127 &cr
->resrec
.rDNSServer
->addr
);
15128 qptr
->validDNSServers
= zeroOpaque128
;
15129 qptr
->qDNSServer
= mDNSNULL
;
15130 cr
->resrec
.rDNSServer
= mDNSNULL
;
15134 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15135 " resetting to question's DNSServer Address %#a", CRDisplayString(m
, cr
),
15136 qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
,
15137 &cr
->resrec
.rDNSServer
->addr
,
15138 qptr
->qDNSServer
? &qptr
->qDNSServer
->addr
: mDNSNULL
);
15139 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
15141 PurgeOrReconfirmCacheRecord(m
, cr
);
15144 else if (!cr
->resrec
.rDNSServer
|| cr
->resrec
.rDNSServer
->flags
& DNSServerFlag_Delete
)
15146 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
15147 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S
", DNS server " PUB_S
" " PRI_IP_ADDR
" " PUB_S
,
15148 CRDisplayString(m
, cr
), !cr
->resrec
.rDNSServer
? "(to be deleted)" : "",
15149 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
,
15150 cr
->resrec
.rDNSServer
? DNSScopeToString(cr
->resrec
.rDNSServer
->scopeType
) : "" );
15151 cr
->resrec
.rDNSServer
= mDNSNULL
;
15152 cr
->resrec
.mortality
= Mortality_Mortal
;
15153 mDNS_PurgeCacheResourceRecord(m
, cr
);
15157 // Delete all the DNS servers that are flagged for deletion
15160 if (((*p
)->flags
& DNSServerFlag_Delete
) != 0)
15164 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
);
15165 mDNSPlatformMemFree(ptr
);
15172 LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m
));
15174 // 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).
15175 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15176 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15177 // 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.
15178 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
15181 FORALL_CACHERECORDS(slot
, cg
, cr
)
15183 if (!cr
->resrec
.InterfaceID
)
15185 mDNS_PurgeCacheResourceRecord(m
, cr
);
15189 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15190 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
15192 // Force anything that needs to get zone data to get that information again
15193 RestartRecordGetZoneData(m
);
15196 SetDynDNSHostNameIfChanged(m
, &fqdn
);
15200 // handle router and primary interface changes
15201 v4
= v6
= r
= zeroAddr
;
15202 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
15204 if (mDNSPlatformGetPrimaryInterface(&v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
15206 mDNS_SetPrimaryInterfaceInfo(m
,
15207 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
15208 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
15209 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
15213 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
15214 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
15217 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m
));
15218 return mStatus_NoError
;
15221 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
15223 m
->mDNSPlatformStatus
= result
;
15224 if (m
->MainCallback
)
15227 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15228 m
->MainCallback(m
, mStatus_NoError
);
15229 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15234 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
15236 m
->CurrentRecord
= start
;
15237 while (m
->CurrentRecord
)
15239 AuthRecord
*rr
= m
->CurrentRecord
;
15240 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15241 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
15242 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15243 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
15244 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
15245 else if (rr
->AnnounceCount
> 1)
15247 rr
->AnnounceCount
= 1;
15248 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
15250 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15251 // new records could have been added to the end of the list as a result of that call.
15252 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
15253 m
->CurrentRecord
= rr
->next
;
15257 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
15263 LogInfo("mDNS_StartExit");
15264 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
15266 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0, 0);
15268 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15269 if (WCFConnectionDealloc
)
15271 if (m
->WCF
) WCFConnectionDealloc(m
->WCF
);
15275 #ifndef UNICAST_DISABLED
15279 // Don't need to do SleepRecordRegistrations() here
15280 // because we deregister all records and services later in this routine
15281 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
15283 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15284 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15285 // and we may crash because the list still contains dangling pointers.
15286 for (s
= SearchList
; s
; s
= s
->next
)
15287 while (s
->AuthRecs
)
15289 ARListElem
*dereg
= s
->AuthRecs
;
15290 s
->AuthRecs
= s
->AuthRecs
->next
;
15291 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
15296 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_All
);
15298 // Shut down all our active NAT Traversals
15299 while (m
->NATTraversals
)
15301 NATTraversalInfo
*t
= m
->NATTraversals
;
15302 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15304 // After stopping the NAT Traversal, we zero out the fields.
15305 // This has particularly important implications for our AutoTunnel records --
15306 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15307 // handlers to just turn around and attempt to re-register those same records.
15308 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15310 t
->ExternalAddress
= zerov4Addr
;
15311 t
->NewAddress
= zerov4Addr
;
15312 t
->ExternalPort
= zeroIPPort
;
15313 t
->RequestedPort
= zeroIPPort
;
15315 t
->Result
= mStatus_NoError
;
15318 // Make sure there are nothing but deregistering records remaining in the list
15319 if (m
->CurrentRecord
)
15320 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
15322 // We're in the process of shutting down, so queries, etc. are no longer available.
15323 // Consequently, determining certain information, e.g. the uDNS update server's IP
15324 // address, will not be possible. The records on the main list are more likely to
15325 // already contain such information, so we deregister the duplicate records first.
15326 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15327 DeregLoop(m
, m
->DuplicateRecords
);
15328 LogInfo("mDNS_StartExit: Deregistering resource records");
15329 DeregLoop(m
, m
->ResourceRecords
);
15331 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15332 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15333 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
15335 m
->NextScheduledResponse
= m
->timenow
;
15336 m
->SuppressSending
= 0;
15339 if (m
->ResourceRecords
) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15340 else LogInfo("mDNS_StartExit: No deregistering records remain");
15342 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
15343 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15345 // If any deregistering records remain, send their deregistration announcements before we exit
15346 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
15350 LogInfo("mDNS_StartExit: done");
15353 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
15355 mDNSu32 rrcache_active
= 0;
15356 mDNSu32 rrcache_totalused
= m
->rrcache_totalused
;
15360 LogInfo("mDNS_FinalExit: mDNSPlatformClose");
15361 mDNSPlatformClose(m
);
15363 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
15365 while (m
->rrcache_hash
[slot
])
15367 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
15368 while (cg
->members
)
15370 CacheRecord
*cr
= cg
->members
;
15371 cg
->members
= cg
->members
->next
;
15372 if (cr
->CRActiveQuestion
) rrcache_active
++;
15373 ReleaseCacheRecord(m
, cr
);
15375 cg
->rrcache_tail
= &cg
->members
;
15376 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
15379 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
15380 if (rrcache_active
!= m
->rrcache_active
)
15381 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused
, rrcache_active
, m
->rrcache_active
);
15383 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
15384 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15386 LogInfo("mDNS_FinalExit: done");
15390 #include "../unittests/mdns_ut.c"