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-2020 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
29 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
33 #if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
34 #include <bsm/libbsm.h>
37 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
38 #include "dnssd_analytics.h"
41 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
42 #include "QuerierSupport.h"
45 // Disable certain benign warnings with Microsoft compilers
46 #if (defined(_MSC_VER))
47 // Disable "conditional expression is constant" warning for debug macros.
48 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
49 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
50 #pragma warning(disable:4127)
52 // Disable "assignment within conditional expression".
53 // Other compilers understand the convention that if you place the assignment expression within an extra pair
54 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
55 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
56 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
57 #pragma warning(disable:4706)
60 #include "dns_sd.h" // for kDNSServiceFlags* definitions
61 #include "dns_sd_internal.h"
63 #if APPLE_OSX_mDNSResponder
64 // Delay in seconds before disabling multicast after there are no active queries or registrations.
65 #define BONJOUR_DISABLE_DELAY 60
68 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
69 #include <WebFilterDNS/WebFilterDNS.h>
71 WCFConnection
*WCFConnectionNew(void) __attribute__((weak_import
));
72 void WCFConnectionDealloc(WCFConnection
* c
) __attribute__((weak_import
));
75 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
79 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
83 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
84 #include "dnssec_v2.h"
85 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
87 // Forward declarations
88 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
);
89 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
);
90 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
);
91 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
92 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
);
94 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
);
95 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
);
96 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
,
97 mDNSu32
*seq
, mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
);
99 typedef mDNSu32 DeadvertiseFlags
;
100 #define kDeadvertiseFlag_NormalHostname (1U << 0)
101 #define kDeadvertiseFlag_RandHostname (1U << 1)
102 #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
104 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, DeadvertiseFlags flags
);
105 mDNSlocal
void AdvertiseInterfaceIfNeeded(mDNS
*const m
, NetworkInterfaceInfo
*set
);
106 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
);
108 // ***************************************************************************
109 #if COMPILER_LIKES_PRAGMA_MARK
110 #pragma mark - Program Constants
113 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
114 #define MDNS_TRACER 1
116 // Any records bigger than this are considered 'large' records
117 #define SmallRecordLimit 1024
119 #define kMaxUpdateCredits 10
120 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
122 // define special NR_AnswerTo values
123 #define NR_AnswerMulticast (mDNSu8*)~0
124 #define NR_AnswerUnicast (mDNSu8*)~1
126 // Question default timeout values
127 #define DEFAULT_MCAST_TIMEOUT 5
128 #define DEFAULT_LO_OR_P2P_TIMEOUT 5
130 // The code (see SendQueries() and BuildQuestion()) needs to have the
131 // RequestUnicast value set to a value one greater than the number of times you want the query
132 // sent with the "request unicast response" (QU) bit set.
133 #define SET_QU_IN_FIRST_QUERY 2
134 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
136 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
137 #define DARK_WAKE_DELAY_SLEEP 5
138 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
140 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
141 #define MAX_CONFLICT_PROCESSING_DELAYS 3
143 // RFC 6762 defines Passive Observation Of Failures (POOF)
145 // A host observes the multicast queries issued by the other hosts on
146 // the network. One of the major benefits of also sending responses
147 // using multicast is that it allows all hosts to see the responses
148 // (or lack thereof) to those queries.
150 // If a host sees queries, for which a record in its cache would be
151 // expected to be given as an answer in a multicast response, but no
152 // such answer is seen, then the host may take this as an indication
153 // that the record may no longer be valid.
155 // After seeing two or more of these queries, and seeing no multicast
156 // response containing the expected answer within ten seconds, then even
157 // though its TTL may indicate that it is not yet due to expire, that
158 // record SHOULD be flushed from the cache.
160 // <https://tools.ietf.org/html/rfc6762#section-10.5>
162 #define POOF_ENABLED 1
164 mDNSexport
const char *const mDNS_DomainTypeNames
[] =
166 "b._dns-sd._udp.", // Browse
167 "db._dns-sd._udp.", // Default Browse
168 "lb._dns-sd._udp.", // Automatic Browse
169 "r._dns-sd._udp.", // Registration
170 "dr._dns-sd._udp." // Default Registration
173 #ifdef UNICAST_DISABLED
174 #define uDNS_IsActiveQuery(q, u) mDNSfalse
177 // ***************************************************************************
178 #if COMPILER_LIKES_PRAGMA_MARK
180 #pragma mark - General Utility Functions
183 #if MDNS_MALLOC_DEBUGGING
184 // When doing memory allocation debugging, this function traverses all lists in the mDNS query
185 // structures and caches and checks each entry in the list to make sure it's still good.
186 mDNSlocal
void mDNS_ValidateLists(void *context
)
189 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
190 mDNSu32 NumAllInterfaceRecords
= 0;
191 mDNSu32 NumAllInterfaceQuestions
= 0;
194 // Check core mDNS lists
196 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
198 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
199 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
200 if (rr
->resrec
.name
!= &rr
->namestorage
)
201 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
202 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
203 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
204 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
208 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
210 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
211 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
212 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
213 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
217 rr
= m
->NewLocalRecords
;
219 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
220 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
222 rr
= m
->CurrentRecord
;
224 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
225 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
228 for (q
= m
->Questions
; q
; q
=q
->next
)
230 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
231 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
232 if (q
->DuplicateOf
&& q
->LocalSocket
)
233 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
234 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
235 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
236 NumAllInterfaceQuestions
++;
243 FORALL_CACHERECORDS(slot
, cg
, cr
)
245 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
246 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
247 if (cr
->CRActiveQuestion
)
249 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
250 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
254 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
255 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
256 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
258 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
259 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
260 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
262 #endif // MDNS_MALLOC_DEBUGGING
264 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
265 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
266 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
267 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
268 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
269 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
270 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
271 (rr)->resrec.rrtype == kDNSType_CNAME || \
272 (rr)->resrec.rrtype == kDNSType_PTR))
274 mDNSlocal
void SetNextQueryStopTime(mDNS
*const m
, const DNSQuestion
*const q
)
278 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
279 m
->NextScheduledStopTime
= q
->StopTime
;
282 mDNSexport
void SetNextQueryTime(mDNS
*const m
, const DNSQuestion
*const q
)
286 if (ActiveQuestion(q
))
288 // Depending on whether this is a multicast or unicast question we want to set either:
289 // m->NextScheduledQuery = NextQSendTime(q) or
290 // m->NextuDNSEvent = NextQSendTime(q)
291 mDNSs32
*const timer
= mDNSOpaque16IsZero(q
->TargetQID
) ? &m
->NextScheduledQuery
: &m
->NextuDNSEvent
;
292 if (*timer
- NextQSendTime(q
) > 0)
293 *timer
= NextQSendTime(q
);
297 mDNSlocal
void ReleaseAuthEntity(AuthHash
*r
, AuthEntity
*e
)
299 #if MDNS_MALLOC_DEBUGGING >= 1
301 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
303 e
->next
= r
->rrauth_free
;
305 r
->rrauth_totalused
--;
308 mDNSlocal
void ReleaseAuthGroup(AuthHash
*r
, AuthGroup
**cp
)
310 AuthEntity
*e
= (AuthEntity
*)(*cp
);
311 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp
)->name
->c
);
312 if ((*cp
)->rrauth_tail
!= &(*cp
)->members
)
313 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
314 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
315 (*cp
)->name
= mDNSNULL
;
316 *cp
= (*cp
)->next
; // Cut record from list
317 ReleaseAuthEntity(r
, e
);
320 mDNSlocal AuthEntity
*GetAuthEntity(AuthHash
*r
, const AuthGroup
*const PreserveAG
)
322 AuthEntity
*e
= mDNSNULL
;
324 if (r
->rrauth_lock
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
329 // We allocate just one AuthEntity at a time because we need to be able
330 // free them all individually which normally happens when we parse /etc/hosts into
331 // AuthHash where we add the "new" entries and discard (free) the already added
332 // entries. If we allocate as chunks, we can't free them individually.
333 AuthEntity
*storage
= (AuthEntity
*) mDNSPlatformMemAllocateClear(sizeof(*storage
));
334 storage
->next
= mDNSNULL
;
335 r
->rrauth_free
= storage
;
338 // If we still have no free records, recycle all the records we can.
339 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
342 mDNSu32 oldtotalused
= r
->rrauth_totalused
;
344 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
346 AuthGroup
**cp
= &r
->rrauth_hash
[slot
];
349 if ((*cp
)->members
|| (*cp
)==PreserveAG
) cp
=&(*cp
)->next
;
350 else ReleaseAuthGroup(r
, cp
);
353 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
354 oldtotalused
- r
->rrauth_totalused
, oldtotalused
, r
->rrauth_totalused
);
357 if (r
->rrauth_free
) // If there are records in the free list, take one
360 r
->rrauth_free
= e
->next
;
361 if (++r
->rrauth_totalused
>= r
->rrauth_report
)
363 LogInfo("RR Auth now using %ld objects", r
->rrauth_totalused
);
364 if (r
->rrauth_report
< 100) r
->rrauth_report
+= 10;
365 else if (r
->rrauth_report
< 1000) r
->rrauth_report
+= 100;
366 else r
->rrauth_report
+= 1000;
368 mDNSPlatformMemZero(e
, sizeof(*e
));
376 mDNSexport AuthGroup
*AuthGroupForName(AuthHash
*r
, const mDNSu32 namehash
, const domainname
*const name
)
379 const mDNSu32 slot
= namehash
% AUTH_HASH_SLOTS
;
381 for (ag
= r
->rrauth_hash
[slot
]; ag
; ag
=ag
->next
)
382 if (ag
->namehash
== namehash
&& SameDomainName(ag
->name
, name
))
387 mDNSexport AuthGroup
*AuthGroupForRecord(AuthHash
*r
, const ResourceRecord
*const rr
)
389 return(AuthGroupForName(r
, rr
->namehash
, rr
->name
));
392 mDNSlocal AuthGroup
*GetAuthGroup(AuthHash
*r
, const ResourceRecord
*const rr
)
394 mDNSu16 namelen
= DomainNameLength(rr
->name
);
395 AuthGroup
*ag
= (AuthGroup
*)GetAuthEntity(r
, mDNSNULL
);
396 const mDNSu32 slot
= rr
->namehash
% AUTH_HASH_SLOTS
;
397 if (!ag
) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
398 ag
->next
= r
->rrauth_hash
[slot
];
399 ag
->namehash
= rr
->namehash
;
400 ag
->members
= mDNSNULL
;
401 ag
->rrauth_tail
= &ag
->members
;
402 ag
->NewLocalOnlyRecords
= mDNSNULL
;
403 if (namelen
> sizeof(ag
->namestorage
))
404 ag
->name
= (domainname
*) mDNSPlatformMemAllocate(namelen
);
406 ag
->name
= (domainname
*)ag
->namestorage
;
409 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
410 ReleaseAuthEntity(r
, (AuthEntity
*)ag
);
413 AssignDomainName(ag
->name
, rr
->name
);
415 if (AuthGroupForRecord(r
, rr
)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr
->name
->c
);
416 r
->rrauth_hash
[slot
] = ag
;
417 if (AuthGroupForRecord(r
, rr
) != ag
) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr
->name
->c
);
422 // Returns the AuthGroup in which the AuthRecord was inserted
423 mDNSexport AuthGroup
*InsertAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
428 ag
= AuthGroupForRecord(r
, &rr
->resrec
);
429 if (!ag
) ag
= GetAuthGroup(r
, &rr
->resrec
); // If we don't have a AuthGroup for this name, make one now
432 *(ag
->rrauth_tail
) = rr
; // Append this record to tail of cache slot list
433 ag
->rrauth_tail
= &(rr
->next
); // Advance tail pointer
438 mDNSexport AuthGroup
*RemoveAuthRecord(mDNS
*const m
, AuthHash
*r
, AuthRecord
*rr
)
443 a
= AuthGroupForRecord(r
, &rr
->resrec
);
444 if (!a
) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m
, rr
)); return mDNSNULL
; }
452 // We don't break here, so that we can set the tail below without tracking "prev" pointers
454 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m
, rr
));
455 *rp
= (*rp
)->next
; // Cut record from list
458 // TBD: If there are no more members, release authgroup ?
463 mDNSexport CacheGroup
*CacheGroupForName(const mDNS
*const m
, const mDNSu32 namehash
, const domainname
*const name
)
466 mDNSu32 slot
= HashSlotFromNameHash(namehash
);
467 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
468 if (cg
->namehash
== namehash
&& SameDomainName(cg
->name
, name
))
473 mDNSlocal CacheGroup
*CacheGroupForRecord(const mDNS
*const m
, const ResourceRecord
*const rr
)
475 return(CacheGroupForName(m
, rr
->namehash
, rr
->name
));
478 mDNSexport mDNSBool
mDNS_AddressIsLocalSubnet(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, const mDNSAddr
*addr
)
480 NetworkInterfaceInfo
*intf
;
482 if (addr
->type
== mDNSAddrType_IPv4
)
484 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
485 if (mDNSv4AddressIsLinkLocal(&addr
->ip
.v4
)) return(mDNStrue
);
486 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
487 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
488 if (((intf
->ip
.ip
.v4
.NotAnInteger
^ addr
->ip
.v4
.NotAnInteger
) & intf
->mask
.ip
.v4
.NotAnInteger
) == 0)
492 if (addr
->type
== mDNSAddrType_IPv6
)
494 if (mDNSv6AddressIsLinkLocal(&addr
->ip
.v6
)) return(mDNStrue
);
495 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
496 if (intf
->ip
.type
== addr
->type
&& intf
->InterfaceID
== InterfaceID
&& intf
->McastTxRx
)
497 if ((((intf
->ip
.ip
.v6
.l
[0] ^ addr
->ip
.v6
.l
[0]) & intf
->mask
.ip
.v6
.l
[0]) == 0) &&
498 (((intf
->ip
.ip
.v6
.l
[1] ^ addr
->ip
.v6
.l
[1]) & intf
->mask
.ip
.v6
.l
[1]) == 0) &&
499 (((intf
->ip
.ip
.v6
.l
[2] ^ addr
->ip
.v6
.l
[2]) & intf
->mask
.ip
.v6
.l
[2]) == 0) &&
500 (((intf
->ip
.ip
.v6
.l
[3] ^ addr
->ip
.v6
.l
[3]) & intf
->mask
.ip
.v6
.l
[3]) == 0))
507 mDNSlocal NetworkInterfaceInfo
*FirstInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
509 NetworkInterfaceInfo
*intf
= m
->HostInterfaces
;
510 while (intf
&& intf
->InterfaceID
!= InterfaceID
) intf
= intf
->next
;
514 mDNSlocal NetworkInterfaceInfo
*FirstIPv4LLInterfaceForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
516 NetworkInterfaceInfo
*intf
;
521 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
522 // we still want to find the first IPv4 Link-Local interface
523 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
525 if (intf
->InterfaceID
== InterfaceID
&&
526 intf
->ip
.type
== mDNSAddrType_IPv4
&& mDNSv4AddressIsLinkLocal(&intf
->ip
.ip
.v4
))
528 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf
->ip
.ip
.v4
);
535 mDNSexport
char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
537 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
538 return(intf
? intf
->ifname
: mDNSNULL
);
541 // Caller should hold the lock
542 mDNSlocal
void GenerateNegativeResponseEx(mDNS
*const m
, mDNSInterfaceID InterfaceID
, QC_result qc
, mDNSBool noData
)
545 if (!m
->CurrentQuestion
) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
546 q
= m
->CurrentQuestion
;
547 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
548 "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME
" (" PUB_S
")",
549 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
551 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, InterfaceID
, mDNSNULL
);
552 m
->rec
.r
.resrec
.negativeRecordType
= noData
? kNegativeRecordType_NoData
: kNegativeRecordType_Unspecified
;
554 // We need to force the response through in the following cases
556 // a) SuppressUnusable questions that are suppressed
557 // b) Append search domains and retry the question
559 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
560 // through we use "QC_forceresponse".
561 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, qc
);
562 if (m
->CurrentQuestion
== q
) { q
->ThisQInterval
= 0; } // Deactivate this question
563 // Don't touch the question after this
564 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
566 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
568 mDNSexport
void AnswerQuestionByFollowingCNAME(mDNS
*const m
, DNSQuestion
*q
, ResourceRecord
*rr
)
570 const mDNSBool selfref
= SameDomainName(&q
->qname
, &rr
->rdata
->u
.name
);
571 if (q
->CNAMEReferrals
>= 10 || selfref
)
573 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
574 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME
" (" PUB_S
") NOT following CNAME referral %d" PUB_S
" for " PRI_S
,
575 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
),
576 q
->CNAMEReferrals
, selfref
? " (Self-Referential)" : "", RRDisplayString(m
, rr
));
581 UDPSocket
*sock
= q
->LocalSocket
;
582 mDNSOpaque16 id
= q
->TargetQID
;
583 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
587 q
->LocalSocket
= mDNSNULL
;
589 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
590 // themselves. Without that check we can get into a case where we have two duplicate questions,
591 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
592 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
593 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
594 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
595 // for either of them. This is not a problem for CNAME loops of two or more records because in
596 // those cases the newly re-appended question A has a different target name and therefore cannot be
597 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
599 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
600 // and track CNAMEs coming and going, we should really create a subordinate query here,
601 // which we would subsequently cancel and retract if the CNAME referral record were removed.
602 // In reality this is such a corner case we'll ignore it until someone actually needs it.
604 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
605 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME
" (" PUB_S
") following CNAME referral %d for " PRI_S
,
606 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
),
607 q
->CNAMEReferrals
, RRDisplayString(m
, rr
));
609 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
610 if (!mDNSOpaque16IsZero(q
->TargetQID
))
612 // Must be called before zeroing out q->metrics below.
613 Querier_PrepareQuestionForCNAMERestart(q
);
616 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
617 if ((q
->CNAMEReferrals
== 0) && !q
->metrics
.originalQName
)
622 qNameLen
= DomainNameLength(&q
->qname
);
623 if ((qNameLen
> 0) && (qNameLen
<= MAX_DOMAIN_NAME
))
625 qName
= (domainname
*) mDNSPlatformMemAllocate(qNameLen
);
628 mDNSPlatformMemCopy(qName
->c
, q
->qname
.c
, qNameLen
);
629 q
->metrics
.originalQName
= qName
;
633 metrics
= q
->metrics
;
634 // The metrics will be transplanted to the restarted question, so zero out the old copy instead of using
635 // uDNSMetricsClear(), which will free any pointers to allocated memory.
636 mDNSPlatformMemZero(&q
->metrics
, sizeof(q
->metrics
));
638 mDNS_StopQuery_internal(m
, q
); // Stop old query
639 AssignDomainName(&q
->qname
, &rr
->rdata
->u
.name
); // Update qname
640 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
641 // If a unicast query results in a CNAME that points to a .local, we need to re-try
642 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
643 // to try this as unicast query even though it is a .local name
644 if (!mDNSOpaque16IsZero(q
->TargetQID
) && IsLocalDomain(&q
->qname
))
646 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
647 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME
" (" PUB_S
") Record " PRI_S
,
648 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), RRDisplayString(m
, rr
));
649 q
->IsUnicastDotLocal
= mDNStrue
;
651 q
->CNAMEReferrals
+= 1; // Increment value before calling mDNS_StartQuery_internal
652 const mDNSu32 c
= q
->CNAMEReferrals
; // Stash a copy of the new q->CNAMEReferrals value
653 mDNS_StartQuery_internal(m
, q
); // start new query
654 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
655 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
656 q
->CNAMEReferrals
= c
;
657 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
658 metrics
.expiredAnswerState
= q
->metrics
.expiredAnswerState
; // We want the newly initialized state for this value
659 metrics
.dnsOverTCPState
= q
->metrics
.dnsOverTCPState
; // We want the newly initialized state for this value
660 q
->metrics
= metrics
;
664 // 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.
665 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
668 // Transplant the old socket into the new question, and copy the query ID across too.
669 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
670 q
->LocalSocket
= sock
;
679 #include <unicode/uidna.h>
681 // #define DEBUG_PUNYCODE 1
683 mDNSlocal mDNSu8
*PunycodeConvert(const mDNSu8
*const src
, mDNSu8
*const dst
, const mDNSu8
*const end
)
685 UErrorCode errorCode
= U_ZERO_ERROR
;
686 UIDNAInfo info
= UIDNA_INFO_INITIALIZER
;
687 UIDNA
*uts46
= uidna_openUTS46(UIDNA_USE_STD3_RULES
|UIDNA_NONTRANSITIONAL_TO_UNICODE
, &errorCode
);
688 int32_t len
= uidna_nameToASCII_UTF8(uts46
, (const char *)src
+1, src
[0], (char *)dst
+1, (int32_t)(end
-(dst
+1)), &info
, &errorCode
);
691 if (errorCode
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src
, errorCode
);
692 if (info
.errors
) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src
, info
.errors
);
693 if (len
> MAX_DOMAIN_LABEL
) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src
, len
);
695 if (errorCode
|| info
.errors
|| len
> MAX_DOMAIN_LABEL
) return mDNSNULL
;
697 return(dst
+ 1 + len
);
700 mDNSlocal mDNSBool
IsHighASCIILabel(const mDNSu8
*d
)
703 for (i
=1; i
<=d
[0]; i
++) if (d
[i
] & 0x80) return mDNStrue
;
707 mDNSlocal
const mDNSu8
*FindLastHighASCIILabel(const domainname
*const d
)
709 const mDNSu8
*ptr
= d
->c
;
710 const mDNSu8
*ans
= mDNSNULL
;
713 const mDNSu8
*const next
= ptr
+ 1 + ptr
[0];
714 if (ptr
[0] > MAX_DOMAIN_LABEL
|| next
>= d
->c
+ MAX_DOMAIN_NAME
) return mDNSNULL
;
715 if (IsHighASCIILabel(ptr
)) ans
= ptr
;
721 mDNSlocal mDNSBool
PerformNextPunycodeConversion(const DNSQuestion
*const q
, domainname
*const newname
)
723 const mDNSu8
*h
= FindLastHighASCIILabel(&q
->qname
);
725 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q
->qname
.c
, DNSTypeName(q
->qtype
), h
);
727 if (!h
) return mDNSfalse
; // There are no high-ascii labels to convert
729 mDNSu8
*const dst
= PunycodeConvert(h
, newname
->c
+ (h
- q
->qname
.c
), newname
->c
+ MAX_DOMAIN_NAME
);
731 return mDNSfalse
; // The label was not convertible to Punycode
734 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
735 const mDNSu8
*const src
= h
+ 1 + h
[0];
736 const mDNSu8 remainder
= DomainNameLength((domainname
*)src
);
737 if (dst
+ remainder
> newname
->c
+ MAX_DOMAIN_NAME
) return mDNSfalse
; // Name too long -- cannot be converted to Punycode
739 mDNSPlatformMemCopy(newname
->c
, q
->qname
.c
, (mDNSu32
)(h
- q
->qname
.c
)); // Fill in the leading part
740 mDNSPlatformMemCopy(dst
, src
, remainder
); // Fill in the trailing part
742 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q
->qname
.c
, newname
->c
);
750 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
751 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
752 mDNSlocal
void AnswerLocalQuestionWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*rr
, QC_result AddRecord
)
754 DNSQuestion
*q
= m
->CurrentQuestion
;
755 mDNSBool followcname
;
759 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m
, rr
));
763 followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
765 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
766 if (!(rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
))
768 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
769 AddRecord
? "Add" : "Rmv", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
773 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
774 if (AddRecord
) rr
->AnsweredLocalQ
= mDNStrue
;
775 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
776 if (q
->QuestionCallback
&& !q
->NoAnswer
)
778 q
->CurrentAnswers
+= AddRecord
? 1 : -1;
779 if (UniqueLocalOnlyRecord(rr
))
781 if (!followcname
|| q
->ReturnIntermed
)
783 // Don't send this packet on the wire as we answered from /etc/hosts
784 q
->ThisQInterval
= 0;
785 q
->LOAddressAnswers
+= AddRecord
? 1 : -1;
786 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
788 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
789 // The callback above could have caused the question to stop. Detect that
790 // using m->CurrentQuestion
791 if (followcname
&& m
->CurrentQuestion
== q
)
792 AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
797 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
800 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
803 mDNSlocal
void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*ar
, QC_result AddRecord
)
805 if (m
->CurrentQuestion
)
806 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
807 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
808 m
->CurrentQuestion
= m
->Questions
;
809 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
812 DNSQuestion
*q
= m
->CurrentQuestion
;
814 answered
= AuthRecordAnswersQuestion(ar
, q
);
816 answered
= LocalOnlyRecordAnswersQuestion(ar
, q
);
818 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, AddRecord
); // MUST NOT dereference q again
819 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
820 m
->CurrentQuestion
= q
->next
;
822 m
->CurrentQuestion
= mDNSNULL
;
825 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
826 // delivers the appropriate add/remove events to listening questions:
827 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
828 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
829 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
830 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
831 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
833 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
834 // and by mDNS_Deregister_internal()
836 mDNSlocal
void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS
*const m
, AuthRecord
*ar
, QC_result AddRecord
)
838 if (m
->CurrentQuestion
)
839 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
840 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
842 m
->CurrentQuestion
= m
->LocalOnlyQuestions
;
843 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewLocalOnlyQuestions
)
846 DNSQuestion
*q
= m
->CurrentQuestion
;
847 // We are called with both LocalOnly/P2P record or a regular AuthRecord
849 answered
= AuthRecordAnswersQuestion(ar
, q
);
851 answered
= LocalOnlyRecordAnswersQuestion(ar
, q
);
853 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, AddRecord
); // MUST NOT dereference q again
854 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
855 m
->CurrentQuestion
= q
->next
;
858 m
->CurrentQuestion
= mDNSNULL
;
860 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
861 if (ar
->ARType
== AuthRecordLocalOnly
|| ar
->ARType
== AuthRecordP2P
)
862 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m
, ar
, AddRecord
);
866 // ***************************************************************************
867 #if COMPILER_LIKES_PRAGMA_MARK
869 #pragma mark - Resource Record Utility Functions
872 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
874 mDNSlocal mDNSBool
ResourceRecordIsValidAnswer(const AuthRecord
*const rr
)
876 if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveMask
) &&
877 ((rr
->Additional1
== mDNSNULL
) || (rr
->Additional1
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)) &&
878 ((rr
->Additional2
== mDNSNULL
) || (rr
->Additional2
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)) &&
879 ((rr
->DependentOn
== mDNSNULL
) || (rr
->DependentOn
->resrec
.RecordType
& kDNSRecordTypeActiveMask
)))
889 mDNSlocal mDNSBool
IsInterfaceValidForAuthRecord(const AuthRecord
*const rr
, const mDNSInterfaceID InterfaceID
)
891 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
893 return mDNSPlatformValidRecordForInterface(rr
, InterfaceID
);
897 return ((rr
->resrec
.InterfaceID
== InterfaceID
) ? mDNStrue
: mDNSfalse
);
901 mDNSlocal mDNSBool
ResourceRecordIsValidInterfaceAnswer(const AuthRecord
*const rr
, const mDNSInterfaceID interfaceID
)
903 return ((IsInterfaceValidForAuthRecord(rr
, interfaceID
) && ResourceRecordIsValidAnswer(rr
)) ? mDNStrue
: mDNSfalse
);
906 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
907 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
909 // Parameters for handling probing conflicts
910 #define kMaxAllowedMCastProbingConflicts 1 // Maximum number of conflicts to allow from mcast messages.
911 #define kProbingConflictPauseDuration mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
913 // See RFC 6762: "8.3 Announcing"
914 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
915 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
916 #define InitialAnnounceCount ((mDNSu8)4)
918 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
919 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
920 // and then if the machine fails to wake, 3 goodbye packets).
921 #define GoodbyeCount ((mDNSu8)3)
922 #define WakeupCount ((mDNSu8)18)
923 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
924 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week
926 // Number of wakeups we send if WakeOnResolve is set in the question
927 #define InitialWakeOnResolveCount ((mDNSu8)3)
929 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
930 // This means that because the announce interval is doubled after sending the first packet, the first
931 // observed on-the-wire inter-packet interval between announcements is actually one second.
932 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
933 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
934 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
935 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
937 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
938 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
939 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
941 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
942 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
943 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
945 // Adjustment factor to avoid race condition (used for unicast cache entries) :
946 // 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.
947 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
948 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
949 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
950 // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
951 // the cached copy at our local caching server will already have expired, so the server will be forced
952 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
954 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
955 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
957 #define MaxUnansweredQueries 4
959 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
960 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
961 // TTL and rdata may differ.
962 // This is used for cache flush management:
963 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
964 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
966 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
968 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
970 mDNSlocal mDNSBool
SameResourceRecordNameClassInterface(const AuthRecord
*const r1
, const AuthRecord
*const r2
)
972 if (!r1
) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse
); }
973 if (!r2
) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse
); }
974 if (r1
->resrec
.InterfaceID
&&
975 r2
->resrec
.InterfaceID
&&
976 r1
->resrec
.InterfaceID
!= r2
->resrec
.InterfaceID
) return(mDNSfalse
);
978 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
&&
979 r1
->resrec
.namehash
== r2
->resrec
.namehash
&&
980 SameDomainName(r1
->resrec
.name
, r2
->resrec
.name
));
983 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
984 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
985 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
986 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
987 // so a response of any type should match, even if it is not actually the type the client plans to use.
989 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
990 // and require the rrtypes to match for the rdata to be considered potentially conflicting
991 mDNSlocal mDNSBool
PacketRRMatchesSignature(const CacheRecord
*const pktrr
, const AuthRecord
*const authrr
)
993 if (!pktrr
) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse
); }
994 if (!authrr
) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse
); }
995 if (pktrr
->resrec
.InterfaceID
&&
996 authrr
->resrec
.InterfaceID
&&
997 pktrr
->resrec
.InterfaceID
!= authrr
->resrec
.InterfaceID
) return(mDNSfalse
);
998 if (!(authrr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) || authrr
->WakeUp
.HMAC
.l
[0])
999 if (pktrr
->resrec
.rrtype
!= authrr
->resrec
.rrtype
) return(mDNSfalse
);
1000 if ((authrr
->resrec
.InterfaceID
== mDNSInterface_Any
) &&
1001 !mDNSPlatformValidRecordForInterface(authrr
, pktrr
->resrec
.InterfaceID
)) return(mDNSfalse
);
1003 pktrr
->resrec
.rrclass
== authrr
->resrec
.rrclass
&&
1004 pktrr
->resrec
.namehash
== authrr
->resrec
.namehash
&&
1005 SameDomainName(pktrr
->resrec
.name
, authrr
->resrec
.name
));
1008 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
1009 // This is the information that the requester believes to be correct.
1010 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
1011 // This is the information that we believe to be correct.
1012 // We've already determined that we plan to give this answer on this interface
1013 // (either the record is non-specific, or it is specific to this interface)
1014 // so now we just need to check the name, type, class, rdata and TTL.
1015 mDNSlocal mDNSBool
ShouldSuppressKnownAnswer(const CacheRecord
*const ka
, const AuthRecord
*const rr
)
1017 // If RR signature is different, or data is different, then don't suppress our answer
1018 if (!IdenticalResourceRecord(&ka
->resrec
, &rr
->resrec
)) return(mDNSfalse
);
1020 // If the requester's indicated TTL is less than half the real TTL,
1021 // we need to give our answer before the requester's copy expires.
1022 // If the requester's indicated TTL is at least half the real TTL,
1023 // then we can suppress our answer this time.
1024 // If the requester's indicated TTL is greater than the TTL we believe,
1025 // then that's okay, and we don't need to do anything about it.
1026 // (If two responders on the network are offering the same information,
1027 // that's okay, and if they are offering the information with different TTLs,
1028 // the one offering the lower TTL should defer to the one offering the higher TTL.)
1029 return (mDNSBool
)(ka
->resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/ 2);
1032 mDNSlocal
void SetNextAnnounceProbeTime(mDNS
*const m
, const AuthRecord
*const rr
)
1034 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1036 if ((rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
> mDNSPlatformOneSecond
* 10)
1038 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr
->ProbeCount
, (rr
->LastAPTime
+ rr
->ThisAPInterval
) - m
->timenow
, ARDisplayString(m
, rr
));
1039 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m
->SuppressProbes
, m
->timenow
, m
->SuppressProbes
- m
->timenow
);
1041 if (m
->NextScheduledProbe
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1042 m
->NextScheduledProbe
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1043 // Some defensive code:
1044 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1045 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1046 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1047 if (m
->NextScheduledProbe
- m
->timenow
< 0)
1048 m
->NextScheduledProbe
= m
->timenow
;
1050 else if (rr
->AnnounceCount
&& (ResourceRecordIsValidAnswer(rr
) || rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
))
1052 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1053 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1057 mDNSlocal
void InitializeLastAPTime(mDNS
*const m
, AuthRecord
*const rr
)
1059 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1060 rr
->ThisAPInterval
= rr
->AddressProxy
.type
? mDNSPlatformOneSecond
: DefaultAPIntervalForRecordType(rr
->resrec
.RecordType
);
1062 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1063 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1064 // records that are going to probe, then we delay its first announcement so that it will
1065 // go out synchronized with the first announcement for the other records that *are* probing.
1066 // This is a minor performance tweak that helps keep groups of related records synchronized together.
1067 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1068 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1069 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1070 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
1071 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1075 rr
->ProbingConflictCount
= 0;
1076 // If we have no probe suppression time set, or it is in the past, set it now
1077 if (m
->SuppressProbes
== 0 || m
->SuppressProbes
- m
->timenow
< 0)
1079 // To allow us to aggregate probes when a group of services are registered together,
1080 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1081 // This means the common-case behaviour is:
1082 // randomized wait; probe
1083 // 1/4 second wait; probe
1084 // 1/4 second wait; probe
1085 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1086 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
1088 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1089 if (m
->SuppressProbes
- m
->NextScheduledProbe
>= 0)
1090 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledProbe
);
1091 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
1092 m
->SuppressProbes
= m
->timenow
;
1094 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1095 if (m
->SuppressProbes
- m
->NextScheduledQuery
>= 0)
1096 m
->SuppressProbes
= NonZeroTime(m
->NextScheduledQuery
);
1097 if (m
->SuppressProbes
- m
->timenow
< 0) // Make sure we don't set m->SuppressProbes excessively in the past
1098 m
->SuppressProbes
= m
->timenow
;
1100 // except... don't expect to be able to send before the m->SuppressSending timer fires
1101 if (m
->SuppressSending
&& m
->SuppressProbes
- m
->SuppressSending
< 0)
1102 m
->SuppressProbes
= NonZeroTime(m
->SuppressSending
);
1104 if (m
->SuppressProbes
- m
->timenow
> mDNSPlatformOneSecond
* 8)
1106 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1107 m
->SuppressProbes
- m
->timenow
,
1108 m
->NextScheduledProbe
- m
->timenow
,
1109 m
->NextScheduledQuery
- m
->timenow
,
1111 m
->SuppressSending
- m
->timenow
);
1112 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ DefaultProbeIntervalForTypeUnique
/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique
/2));
1115 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
;
1117 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1118 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1119 else if ((rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
) && (rr
->resrec
.RecordType
!= kDNSRecordTypeShared
) && m
->SuppressProbes
&& (m
->SuppressProbes
- m
->timenow
>= 0))
1120 rr
->LastAPTime
= m
->SuppressProbes
- rr
->ThisAPInterval
+ DefaultProbeIntervalForTypeUnique
* DefaultProbeCountForTypeUnique
+ rr
->ThisAPInterval
/ 2;
1122 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1124 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1125 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1126 // After three probes one second apart with no answer, we conclude the client is now sleeping
1127 // and we can begin broadcasting our announcements to take over ownership of that IP address.
1128 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1129 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1130 if (rr
->AddressProxy
.type
)
1131 rr
->LastAPTime
= m
->timenow
;
1133 // Set LastMCTime to now, to inhibit multicast responses
1134 // (no need to send additional multicast responses when we're announcing anyway)
1135 rr
->LastMCTime
= m
->timenow
;
1136 rr
->LastMCInterface
= mDNSInterfaceMark
;
1138 SetNextAnnounceProbeTime(m
, rr
);
1141 mDNSlocal
const domainname
*SetUnicastTargetToHostName(mDNS
*const m
, AuthRecord
*rr
)
1143 const domainname
*target
;
1146 rr
->AutoTarget
= Target_AutoHostAndNATMAP
;
1149 target
= GetServiceTarget(m
, rr
);
1150 if (!target
|| target
->c
[0] == 0)
1152 // defer registration until we've got a target
1153 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m
, rr
));
1154 rr
->state
= regState_NoTarget
;
1159 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target
->c
, ARDisplayString(m
,rr
));
1164 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1165 mDNSlocal mDNSBool
AuthRecordIncludesOrIsAWDL(const AuthRecord
*const ar
)
1167 return ((AuthRecordIncludesAWDL(ar
) || mDNSPlatformInterfaceIsAWDL(ar
->resrec
.InterfaceID
)) ? mDNStrue
: mDNSfalse
);
1171 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1172 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1173 mDNSlocal
void SetTargetToHostName(mDNS
*const m
, AuthRecord
*const rr
)
1175 domainname
*const target
= GetRRDomainNameTarget(&rr
->resrec
);
1176 const domainname
*newname
;
1178 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1179 if (AuthRecordIncludesOrIsAWDL(rr
))
1181 newname
= &m
->RandomizedHostname
;
1186 newname
= &m
->MulticastHostname
;
1188 if (!target
) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr
->resrec
.rrtype
));
1190 if (!(rr
->ForceMCast
|| rr
->ARType
== AuthRecordLocalOnly
|| rr
->ARType
== AuthRecordP2P
|| IsLocalDomain(&rr
->namestorage
)))
1192 const domainname
*const n
= SetUnicastTargetToHostName(m
, rr
);
1194 else { if (target
) target
->c
[0] = 0; SetNewRData(&rr
->resrec
, mDNSNULL
, 0); return; }
1197 if (target
&& SameDomainName(target
, newname
))
1198 debugf("SetTargetToHostName: Target of %##s is already %##s", rr
->resrec
.name
->c
, target
->c
);
1200 if (target
&& !SameDomainName(target
, newname
))
1202 AssignDomainName(target
, newname
);
1203 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Update rdlength, rdestimate, rdatahash
1205 // If we're in the middle of probing this record, we need to start again,
1206 // because changing its rdata may change the outcome of the tie-breaker.
1207 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1208 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1210 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1211 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1212 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1213 if (rr
->RequireGoodbye
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
)
1214 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1215 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1217 rr
->AnnounceCount
= InitialAnnounceCount
;
1218 rr
->RequireGoodbye
= mDNSfalse
;
1219 rr
->ProbeRestartCount
= 0;
1220 InitializeLastAPTime(m
, rr
);
1224 mDNSlocal
void AcknowledgeRecord(mDNS
*const m
, AuthRecord
*const rr
)
1226 if (rr
->RecordCallback
)
1228 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1229 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1230 rr
->Acknowledged
= mDNStrue
;
1231 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1232 rr
->RecordCallback(m
, rr
, mStatus_NoError
);
1233 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1237 mDNSexport
void ActivateUnicastRegistration(mDNS
*const m
, AuthRecord
*const rr
)
1239 // Make sure that we don't activate the SRV record and associated service records, if it is in
1240 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1241 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1242 // the target becomes available, the records will be reregistered.
1243 if (rr
->resrec
.rrtype
!= kDNSType_SRV
)
1245 AuthRecord
*srvRR
= mDNSNULL
;
1246 if (rr
->resrec
.rrtype
== kDNSType_PTR
)
1247 srvRR
= rr
->Additional1
;
1248 else if (rr
->resrec
.rrtype
== kDNSType_TXT
)
1249 srvRR
= rr
->DependentOn
;
1252 if (srvRR
->resrec
.rrtype
!= kDNSType_SRV
)
1254 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m
, srvRR
));
1258 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1259 ARDisplayString(m
, srvRR
), srvRR
->state
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1260 rr
->state
= srvRR
->state
;
1265 if (rr
->state
== regState_NoTarget
)
1267 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m
, rr
));
1270 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1271 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1272 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1273 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1274 // 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.
1275 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1277 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m
, rr
), rr
->state
);
1278 rr
->state
= regState_DeregPending
;
1282 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m
, rr
), rr
->state
);
1283 rr
->state
= regState_Pending
;
1285 rr
->ProbingConflictCount
= 0;
1286 rr
->LastConflictPktNum
= 0;
1287 rr
->ProbeRestartCount
= 0;
1289 rr
->AnnounceCount
= 0;
1290 rr
->ThisAPInterval
= INIT_RECORD_REG_INTERVAL
;
1291 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
1292 rr
->expire
= 0; // Forget about all the leases, start fresh
1293 rr
->uselease
= mDNStrue
;
1294 rr
->updateid
= zeroID
;
1295 rr
->SRVChanged
= mDNSfalse
;
1296 rr
->updateError
= mStatus_NoError
;
1297 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1298 // The records might already be registered with the server and hence could have NAT state.
1299 if (rr
->NATinfo
.clientContext
)
1301 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
1302 rr
->NATinfo
.clientContext
= mDNSNULL
;
1304 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
1305 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
1306 if (m
->NextuDNSEvent
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
1307 m
->NextuDNSEvent
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
1310 // Two records qualify to be local duplicates if:
1311 // (a) the RecordTypes are the same, or
1312 // (b) one is Unique and the other Verified
1313 // (c) either is in the process of deregistering
1314 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1315 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1316 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1318 #define RecordIsLocalDuplicate(A,B) \
1319 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1321 mDNSlocal AuthRecord
*CheckAuthIdenticalRecord(AuthHash
*r
, AuthRecord
*rr
)
1326 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1327 if (!a
) return mDNSNULL
;
1331 if (!RecordIsLocalDuplicate(rp
, rr
))
1335 if (rp
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
1337 rp
->AnnounceCount
= 0;
1346 mDNSlocal mDNSBool
CheckAuthRecordConflict(AuthHash
*r
, AuthRecord
*rr
)
1349 const AuthRecord
*rp
;
1351 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1352 if (!a
) return mDNSfalse
;
1356 const AuthRecord
*s1
= rr
->RRSet
? rr
->RRSet
: rr
;
1357 const AuthRecord
*s2
= rp
->RRSet
? rp
->RRSet
: rp
;
1358 if (s1
!= s2
&& SameResourceRecordSignature(rp
, rr
) && !IdenticalSameNameRecord(&rp
->resrec
, &rr
->resrec
))
1366 // checks to see if "rr" is already present
1367 mDNSlocal AuthRecord
*CheckAuthSameRecord(AuthHash
*r
, AuthRecord
*rr
)
1372 a
= AuthGroupForRecord(r
, &rr
->resrec
);
1373 if (!a
) return mDNSNULL
;
1387 mDNSlocal
void DecrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1389 if (RRLocalOnly(rr
))
1391 // A sanity check, this should be prevented in calling code.
1392 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1396 if (!AuthRecord_uDNS(rr
) && (rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHost
))
1398 NetworkInterfaceInfo
*intf
;
1399 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1400 DeadvertiseFlags flags
= 0; // DeadvertiseFlags for non-AWDL interfaces.
1401 DeadvertiseFlags flagsAWDL
= 0; // DeadvertiseFlags for AWDL interfaces.
1402 if (AuthRecordIncludesOrIsAWDL(rr
))
1404 if (AuthRecordIncludesAWDL(rr
))
1406 m
->AutoTargetAWDLIncludedCount
--;
1407 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1408 "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S
,
1409 m
->AutoTargetAWDLIncludedCount
, ARDisplayString(m
, rr
));
1410 if (m
->AutoTargetAWDLIncludedCount
== 0)
1412 flags
|= kDeadvertiseFlag_RandHostname
;
1413 if (m
->AutoTargetAWDLOnlyCount
== 0) flagsAWDL
|= kDeadvertiseFlag_RandHostname
;
1418 m
->AutoTargetAWDLOnlyCount
--;
1419 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1420 "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S
,
1421 m
->AutoTargetAWDLOnlyCount
, ARDisplayString(m
, rr
));
1422 if ((m
->AutoTargetAWDLIncludedCount
== 0) && (m
->AutoTargetAWDLOnlyCount
== 0))
1424 flagsAWDL
|= kDeadvertiseFlag_RandHostname
;
1427 if (flags
|| flagsAWDL
)
1429 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1431 if (!intf
->Advertise
) continue;
1432 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
))
1434 if (flagsAWDL
) DeadvertiseInterface(m
, intf
, flagsAWDL
);
1438 if (flags
) DeadvertiseInterface(m
, intf
, flags
);
1442 if ((m
->AutoTargetAWDLIncludedCount
== 0) && (m
->AutoTargetAWDLOnlyCount
== 0))
1444 GetRandomUUIDLocalHostname(&m
->RandomizedHostname
);
1450 m
->AutoTargetServices
--;
1451 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1452 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S
,
1453 m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1454 if (m
->AutoTargetServices
== 0)
1456 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1458 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
, kDeadvertiseFlag_NormalHostname
);
1464 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1465 if (!AuthRecord_uDNS(rr
))
1467 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1468 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
1469 m
->NumAllInterfaceRecords
--;
1470 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1471 "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S
,
1472 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1477 mDNSlocal
void AdvertiseNecessaryInterfaceRecords(mDNS
*const m
)
1479 NetworkInterfaceInfo
*intf
;
1480 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
1482 if (intf
->Advertise
) AdvertiseInterfaceIfNeeded(m
, intf
);
1486 mDNSlocal
void IncrementAutoTargetServices(mDNS
*const m
, AuthRecord
*const rr
)
1488 mDNSBool enablingBonjour
= mDNSfalse
;
1490 if (RRLocalOnly(rr
))
1492 // A sanity check, this should be prevented in calling code.
1493 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m
, rr
));
1497 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1498 if (!AuthRecord_uDNS(rr
))
1500 m
->NumAllInterfaceRecords
++;
1501 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1502 "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S
,
1503 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, ARDisplayString(m
, rr
));
1504 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
1506 m
->NextBonjourDisableTime
= 0;
1507 if (m
->BonjourEnabled
== 0)
1509 // Enable Bonjour immediately by scheduling network changed processing where
1510 // we will join the multicast group on each active interface.
1511 m
->BonjourEnabled
= 1;
1512 enablingBonjour
= mDNStrue
;
1513 m
->NetworkChanged
= m
->timenow
;
1519 if (!AuthRecord_uDNS(rr
) && (rr
->resrec
.rrtype
== kDNSType_SRV
) && (rr
->AutoTarget
== Target_AutoHost
))
1521 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1522 if (AuthRecordIncludesAWDL(rr
))
1524 m
->AutoTargetAWDLIncludedCount
++;
1525 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1526 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S
,
1527 m
->AutoTargetAWDLIncludedCount
, ARDisplayString(m
, rr
));
1529 else if (mDNSPlatformInterfaceIsAWDL(rr
->resrec
.InterfaceID
))
1531 m
->AutoTargetAWDLOnlyCount
++;
1532 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1533 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S
,
1534 m
->AutoTargetAWDLOnlyCount
, ARDisplayString(m
, rr
));
1539 m
->AutoTargetServices
++;
1540 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1541 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S
,
1542 m
->AutoTargetServices
, ARDisplayString(m
, rr
));
1544 // If this is the first advertised service and we did not just enable Bonjour above, then
1545 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1546 // be advertised during the network changed processing scheduled above, so no need
1548 if (!enablingBonjour
) AdvertiseNecessaryInterfaceRecords(m
);
1552 mDNSlocal
void getKeepaliveRaddr(mDNS
*const m
, AuthRecord
*rr
, mDNSAddr
*raddr
)
1554 mDNSAddr laddr
= zeroAddr
;
1555 mDNSEthAddr eth
= zeroEthAddr
;
1556 mDNSIPPort lport
= zeroIPPort
;
1557 mDNSIPPort rport
= zeroIPPort
;
1558 mDNSu32 timeout
= 0;
1563 if (mDNS_KeepaliveRecord(&rr
->resrec
))
1565 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
1566 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
1568 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, raddr
, rport
.NotAnInteger
);
1574 // Exported so uDNS.c can call this
1575 mDNSexport mStatus
mDNS_Register_internal(mDNS
*const m
, AuthRecord
*const rr
)
1577 domainname
*target
= GetRRDomainNameTarget(&rr
->resrec
);
1579 AuthRecord
**p
= &m
->ResourceRecords
;
1580 AuthRecord
**d
= &m
->DuplicateRecords
;
1582 if ((mDNSs32
)rr
->resrec
.rroriginalttl
<= 0)
1583 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr
->resrec
.rroriginalttl
, ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1585 if (!rr
->resrec
.RecordType
)
1586 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m
, rr
)); return(mStatus_BadParamErr
); }
1588 if (m
->ShutdownTime
)
1589 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m
, rr
)); return(mStatus_ServiceNotRunning
); }
1591 if (m
->DivertMulticastAdvertisements
&& !AuthRecord_uDNS(rr
))
1593 mDNSInterfaceID previousID
= rr
->resrec
.InterfaceID
;
1594 if (rr
->resrec
.InterfaceID
== mDNSInterface_Any
|| rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1596 rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
;
1597 rr
->ARType
= AuthRecordLocalOnly
;
1599 if (rr
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
1601 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
1602 if (intf
&& !intf
->Advertise
) { rr
->resrec
.InterfaceID
= mDNSInterface_LocalOnly
; rr
->ARType
= AuthRecordLocalOnly
; }
1604 if (rr
->resrec
.InterfaceID
!= previousID
)
1605 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m
, rr
));
1608 if (RRLocalOnly(rr
))
1610 if (CheckAuthSameRecord(&m
->rrauth
, rr
))
1612 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1613 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1614 return(mStatus_AlreadyRegistered
);
1619 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1622 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1623 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1624 return(mStatus_AlreadyRegistered
);
1628 while (*d
&& *d
!= rr
) d
=&(*d
)->next
;
1631 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1632 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1633 return(mStatus_AlreadyRegistered
);
1636 if (rr
->DependentOn
)
1638 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
1639 rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1640 else if (rr
->resrec
.RecordType
!= kDNSRecordTypeKnownUnique
)
1642 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1643 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1644 return(mStatus_Invalid
);
1646 if (!(rr
->DependentOn
->resrec
.RecordType
& (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
)))
1648 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1649 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->DependentOn
->resrec
.RecordType
);
1650 return(mStatus_Invalid
);
1654 rr
->next
= mDNSNULL
;
1656 // Field Group 1: The actual information pertaining to this resource record
1657 // Set up by client prior to call
1659 // Field Group 2: Persistent metadata for Authoritative Records
1660 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1661 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1662 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1663 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1664 // rr->Callback = already set in mDNS_SetupResourceRecord
1665 // rr->Context = already set in mDNS_SetupResourceRecord
1666 // rr->RecordType = already set in mDNS_SetupResourceRecord
1667 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1668 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1669 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1670 if (rr
->AutoTarget
&& target
) target
->c
[0] = 0;
1672 // Field Group 3: Transient state for Authoritative Records
1673 rr
->Acknowledged
= mDNSfalse
;
1674 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
1675 rr
->ProbeRestartCount
= 0;
1676 rr
->AnnounceCount
= InitialAnnounceCount
;
1677 rr
->RequireGoodbye
= mDNSfalse
;
1678 rr
->AnsweredLocalQ
= mDNSfalse
;
1679 rr
->IncludeInProbe
= mDNSfalse
;
1680 rr
->ImmedUnicast
= mDNSfalse
;
1681 rr
->SendNSECNow
= mDNSNULL
;
1682 rr
->ImmedAnswer
= mDNSNULL
;
1683 rr
->ImmedAdditional
= mDNSNULL
;
1684 rr
->SendRNow
= mDNSNULL
;
1685 rr
->v4Requester
= zerov4Addr
;
1686 rr
->v6Requester
= zerov6Addr
;
1687 rr
->NextResponse
= mDNSNULL
;
1688 rr
->NR_AnswerTo
= mDNSNULL
;
1689 rr
->NR_AdditionalTo
= mDNSNULL
;
1690 if (!rr
->AutoTarget
) InitializeLastAPTime(m
, rr
);
1691 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1692 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1693 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1694 rr
->NewRData
= mDNSNULL
;
1695 rr
->newrdlength
= 0;
1696 rr
->UpdateCallback
= mDNSNULL
;
1697 rr
->UpdateCredits
= kMaxUpdateCredits
;
1698 rr
->NextUpdateCredit
= 0;
1699 rr
->UpdateBlocked
= 0;
1701 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1702 if (rr
->WakeUp
.HMAC
.l
[0] && !rr
->AddressProxy
.type
) rr
->AnnounceCount
= 2;
1704 // Field Group 4: Transient uDNS state for Authoritative Records
1705 rr
->state
= regState_Zero
;
1709 rr
->updateid
= zeroID
;
1710 rr
->updateIntID
= zeroOpaque64
;
1711 rr
->zone
= rr
->resrec
.name
;
1716 rr
->InFlightRData
= 0;
1717 rr
->InFlightRDLen
= 0;
1718 rr
->QueuedRData
= 0;
1719 rr
->QueuedRDLen
= 0;
1720 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1721 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1722 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1723 // times with different values if the external NAT port changes during the lifetime of the service registration.
1724 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1726 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1727 // rr->resrec.name->c = MUST be set by client
1728 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1729 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1730 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1731 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1733 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1734 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1735 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1736 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rr
->resrec
.rdlength
== 0) { rr
->resrec
.rdlength
= 1; rr
->resrec
.rdata
->u
.txt
.c
[0] = 0; }
1740 SetTargetToHostName(m
, rr
); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1741 #ifndef UNICAST_DISABLED
1742 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1743 // 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.
1744 if (rr
->state
== regState_NoTarget
)
1746 // Initialize the target so that we don't crash while logging etc.
1747 domainname
*tar
= GetRRDomainNameTarget(&rr
->resrec
);
1748 if (tar
) tar
->c
[0] = 0;
1749 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m
, rr
));
1755 rr
->resrec
.rdlength
= GetRDLength(&rr
->resrec
, mDNSfalse
);
1756 rr
->resrec
.rdestimate
= GetRDLength(&rr
->resrec
, mDNStrue
);
1759 if (!ValidateDomainName(rr
->resrec
.name
))
1760 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1762 // Don't do this until *after* we've set rr->resrec.rdlength
1763 if (!ValidateRData(rr
->resrec
.rrtype
, rr
->resrec
.rdlength
, rr
->resrec
.rdata
))
1764 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m
, rr
)); return(mStatus_Invalid
); }
1766 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
1767 rr
->resrec
.rdatahash
= target
? DomainNameHashValue(target
) : RDataHashValue(&rr
->resrec
);
1769 if (RRLocalOnly(rr
))
1771 // If this is supposed to be unique, make sure we don't have any name conflicts.
1772 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1773 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1774 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1775 // Hence, just bail out.
1776 // This comment is doesn’t make any sense. -- SC
1777 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
1779 if (CheckAuthRecordConflict(&m
->rrauth
, rr
))
1781 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m
, rr
), rr
, rr
->resrec
.InterfaceID
);
1782 return mStatus_NameConflict
;
1787 // For uDNS records, we don't support duplicate checks at this time.
1788 #ifndef UNICAST_DISABLED
1789 if (AuthRecord_uDNS(rr
))
1791 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1792 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1793 // 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.
1794 while (*p
) p
=&(*p
)->next
;
1796 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1798 rr
->ProbeRestartCount
= 0;
1799 rr
->AnnounceCount
= 0;
1800 if (rr
->state
!= regState_NoTarget
) ActivateUnicastRegistration(m
, rr
);
1801 return(mStatus_NoError
); // <--- Note: For unicast records, code currently bails out at this point
1805 // Now that we've finished building our new record, make sure it's not identical to one we already have
1806 if (RRLocalOnly(rr
))
1809 rr
->ProbeRestartCount
= 0;
1810 rr
->AnnounceCount
= 0;
1811 r
= CheckAuthIdenticalRecord(&m
->rrauth
, rr
);
1815 for (r
= m
->ResourceRecords
; r
; r
=r
->next
)
1816 if (RecordIsLocalDuplicate(r
, rr
))
1818 if (r
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) r
->AnnounceCount
= 0;
1825 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m
,rr
));
1827 // If the previous copy of this record is already verified unique,
1828 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1829 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1830 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1831 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
&& r
->resrec
.RecordType
== kDNSRecordTypeVerified
)
1836 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m
,rr
));
1837 if (RRLocalOnly(rr
))
1840 ag
= InsertAuthRecord(m
, &m
->rrauth
, rr
);
1841 if (ag
&& !ag
->NewLocalOnlyRecords
)
1843 m
->NewLocalOnlyRecords
= mDNStrue
;
1844 ag
->NewLocalOnlyRecords
= rr
;
1846 // No probing for LocalOnly records; acknowledge them right away
1847 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
) rr
->resrec
.RecordType
= kDNSRecordTypeVerified
;
1848 AcknowledgeRecord(m
, rr
);
1849 return(mStatus_NoError
);
1853 if (!m
->NewLocalRecords
) m
->NewLocalRecords
= rr
;
1858 if (!AuthRecord_uDNS(rr
)) // This check is superfluous, given that for unicast records we (currently) bail out above
1860 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1861 IncrementAutoTargetServices(m
, rr
);
1863 // For records that are not going to probe, acknowledge them right away
1864 if (rr
->resrec
.RecordType
!= kDNSRecordTypeUnique
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
1865 AcknowledgeRecord(m
, rr
);
1867 // Adding a record may affect whether or not we should sleep
1868 mDNS_UpdateAllowSleep(m
);
1871 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1872 // This is used by the in-NIC proxy to send the keepalive packets.
1873 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
1876 // Set the record type to known unique to prevent probing keep alive records.
1877 // Also make sure we do not announce the keepalive records.
1878 rr
->resrec
.RecordType
= kDNSRecordTypeKnownUnique
;
1879 rr
->AnnounceCount
= 0;
1880 getKeepaliveRaddr(m
, rr
, &raddr
);
1881 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1882 // asynchronous task to update the resource record
1883 mDNSPlatformGetRemoteMacAddr(&raddr
);
1886 return(mStatus_NoError
);
1889 mDNSlocal
void RecordProbeFailure(mDNS
*const m
, const AuthRecord
*const rr
)
1891 m
->ProbeFailTime
= m
->timenow
;
1892 m
->NumFailedProbes
++;
1893 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1894 // If a bunch of hosts have all been configured with the same name, then they'll all
1895 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1896 // up to name-10. After that they'll start adding random increments in the range 1-100,
1897 // so they're more likely to branch out in the available namespace and settle on a set of
1898 // unique names quickly. If after five more tries the host is still conflicting, then we
1899 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1900 if (m
->NumFailedProbes
>= 15)
1902 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
1903 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1904 m
->NumFailedProbes
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1908 mDNSlocal
void CompleteRDataUpdate(mDNS
*const m
, AuthRecord
*const rr
)
1910 RData
*OldRData
= rr
->resrec
.rdata
;
1911 mDNSu16 OldRDLen
= rr
->resrec
.rdlength
;
1912 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
); // Update our rdata
1913 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
1914 if (rr
->UpdateCallback
)
1915 rr
->UpdateCallback(m
, rr
, OldRData
, OldRDLen
); // ... and let the client know
1918 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1919 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1920 // Exported so uDNS.c can call this
1921 mDNSexport mStatus
mDNS_Deregister_internal(mDNS
*const m
, AuthRecord
*const rr
, mDNS_Dereg_type drt
)
1924 mDNSu8 RecordType
= rr
->resrec
.RecordType
;
1925 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
1926 mDNSBool dupList
= mDNSfalse
;
1928 if (RRLocalOnly(rr
))
1933 a
= AuthGroupForRecord(&m
->rrauth
, &rr
->resrec
);
1934 if (!a
) return mDNSfalse
;
1936 while (*rp
&& *rp
!= rr
) rp
=&(*rp
)->next
;
1941 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
1946 // We found our record on the main list. See if there are any duplicates that need special handling.
1947 if (drt
== mDNS_Dereg_conflict
) // If this was a conflict, see that all duplicates get the same treatment
1949 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1950 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1951 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
) if (RecordIsLocalDuplicate(r2
, rr
)) r2
->ProbeCount
= 0xFF;
1955 // Before we delete the record (and potentially send a goodbye packet)
1956 // first see if we have a record on the duplicate list ready to take over from it.
1957 AuthRecord
**d
= &m
->DuplicateRecords
;
1958 while (*d
&& !RecordIsLocalDuplicate(*d
, rr
)) d
=&(*d
)->next
;
1961 AuthRecord
*dup
= *d
;
1962 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1963 dup
, rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
1964 *d
= dup
->next
; // Cut replacement record from DuplicateRecords list
1965 if (RRLocalOnly(rr
))
1967 dup
->next
= mDNSNULL
;
1968 if (!InsertAuthRecord(m
, &m
->rrauth
, dup
)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m
, dup
));
1972 dup
->next
= rr
->next
; // And then...
1973 rr
->next
= dup
; // ... splice it in right after the record we're about to delete
1975 dup
->resrec
.RecordType
= rr
->resrec
.RecordType
;
1976 dup
->ProbeCount
= rr
->ProbeCount
;
1977 dup
->ProbeRestartCount
= rr
->ProbeRestartCount
;
1978 dup
->AnnounceCount
= rr
->AnnounceCount
;
1979 dup
->RequireGoodbye
= rr
->RequireGoodbye
;
1980 dup
->AnsweredLocalQ
= rr
->AnsweredLocalQ
;
1981 dup
->ImmedAnswer
= rr
->ImmedAnswer
;
1982 dup
->ImmedUnicast
= rr
->ImmedUnicast
;
1983 dup
->ImmedAdditional
= rr
->ImmedAdditional
;
1984 dup
->v4Requester
= rr
->v4Requester
;
1985 dup
->v6Requester
= rr
->v6Requester
;
1986 dup
->ThisAPInterval
= rr
->ThisAPInterval
;
1987 dup
->LastAPTime
= rr
->LastAPTime
;
1988 dup
->LastMCTime
= rr
->LastMCTime
;
1989 dup
->LastMCInterface
= rr
->LastMCInterface
;
1990 dup
->Private
= rr
->Private
;
1991 dup
->state
= rr
->state
;
1992 rr
->RequireGoodbye
= mDNSfalse
;
1993 rr
->AnsweredLocalQ
= mDNSfalse
;
1999 // We didn't find our record on the main list; try the DuplicateRecords list instead.
2000 p
= &m
->DuplicateRecords
;
2001 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
2002 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2005 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
2006 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
2007 // also that have been marked above in this function. In that case, we come here and if we don't
2008 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
2009 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
2011 rr
->WakeUp
.HMAC
= zeroEthAddr
;
2012 rr
->RequireGoodbye
= mDNSfalse
;
2013 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2016 if (*p
) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
2017 rr
, rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2022 // No need to log an error message if we already know this is a potentially repeated deregistration
2023 if (drt
!= mDNS_Dereg_repeat
)
2024 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr
, ARDisplayString(m
,rr
));
2025 return(mStatus_BadReferenceErr
);
2028 // If this is a shared record and we've announced it at least once,
2029 // we need to retract that announcement before we delete the record
2031 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2032 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2033 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2034 // mechanism to cope with the client callback modifying the question list while that's happening.
2035 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2036 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2037 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2038 // records, thereby invoking yet more callbacks, without limit.
2039 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2040 // actual goodbye packets.
2042 #ifndef UNICAST_DISABLED
2043 if (AuthRecord_uDNS(rr
))
2045 if (rr
->RequireGoodbye
)
2047 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2048 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2049 m
->LocalRemoveEvents
= mDNStrue
;
2050 uDNS_DeregisterRecord(m
, rr
);
2051 // At this point unconditionally we bail out
2052 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2053 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2054 // process and will complete asynchronously. Either way we don't need to do anything more here.
2055 return(mStatus_NoError
);
2057 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2058 // from the server. In that case, if the records have been part of a group update, clear the
2060 rr
->updateid
= zeroID
;
2062 // We defer cleaning up NAT state only after sending goodbyes. This is important because
2063 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2064 // This happens today when we turn on/off interface where we get multiple network transitions
2065 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2066 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2067 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2068 // NAT state here takes care of the case where we did not send goodbyes at all.
2069 if (rr
->NATinfo
.clientContext
)
2071 mDNS_StopNATOperation_internal(m
, &rr
->NATinfo
);
2072 rr
->NATinfo
.clientContext
= mDNSNULL
;
2074 if (rr
->nta
) { CancelGetZoneData(m
, rr
->nta
); rr
->nta
= mDNSNULL
; }
2075 if (rr
->tcp
) { DisposeTCPConn(rr
->tcp
); rr
->tcp
= mDNSNULL
; }
2077 #endif // UNICAST_DISABLED
2079 if (RecordType
== kDNSRecordTypeUnregistered
)
2080 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m
, rr
));
2081 else if (RecordType
== kDNSRecordTypeDeregistering
)
2083 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m
, rr
));
2084 return(mStatus_BadReferenceErr
);
2087 if (rr
->WakeUp
.HMAC
.l
[0] ||
2088 (((RecordType
== kDNSRecordTypeShared
) || (rr
->ARType
== AuthRecordLocalOnly
)) &&
2089 (rr
->RequireGoodbye
|| rr
->AnsweredLocalQ
)))
2091 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m
, rr
));
2092 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
2093 rr
->resrec
.rroriginalttl
= 0;
2094 rr
->AnnounceCount
= rr
->WakeUp
.HMAC
.l
[0] ? WakeupCount
: (drt
== mDNS_Dereg_rapid
) ? 1 : GoodbyeCount
;
2095 rr
->ThisAPInterval
= mDNSPlatformOneSecond
* 2;
2096 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
2097 m
->LocalRemoveEvents
= mDNStrue
;
2098 if (m
->NextScheduledResponse
- (m
->timenow
+ mDNSPlatformOneSecond
/10) >= 0)
2099 m
->NextScheduledResponse
= (m
->timenow
+ mDNSPlatformOneSecond
/10);
2103 if (!dupList
&& RRLocalOnly(rr
))
2105 AuthGroup
*ag
= RemoveAuthRecord(m
, &m
->rrauth
, rr
);
2106 if (ag
->NewLocalOnlyRecords
== rr
) ag
->NewLocalOnlyRecords
= rr
->next
;
2110 *p
= rr
->next
; // Cut this record from the list
2111 if (m
->NewLocalRecords
== rr
) m
->NewLocalRecords
= rr
->next
;
2112 DecrementAutoTargetServices(m
, rr
);
2114 // If someone is about to look at this, bump the pointer forward
2115 if (m
->CurrentRecord
== rr
) m
->CurrentRecord
= rr
->next
;
2116 rr
->next
= mDNSNULL
;
2118 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m
, rr
));
2119 rr
->resrec
.RecordType
= kDNSRecordTypeUnregistered
;
2121 if ((drt
== mDNS_Dereg_conflict
|| drt
== mDNS_Dereg_repeat
) && RecordType
== kDNSRecordTypeShared
)
2122 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2123 rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2125 // If we have an update queued up which never executed, give the client a chance to free that memory
2126 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
2129 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2130 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2131 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2132 // so any attempt to touch rr after this is likely to lead to a crash.
2133 if (drt
!= mDNS_Dereg_conflict
)
2135 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2136 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m
, rr
));
2137 if (rr
->RecordCallback
)
2138 rr
->RecordCallback(m
, rr
, mStatus_MemFree
); // MUST NOT touch rr after this
2139 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2143 RecordProbeFailure(m
, rr
);
2144 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2145 if (rr
->RecordCallback
)
2146 rr
->RecordCallback(m
, rr
, mStatus_NameConflict
); // MUST NOT touch rr after this
2147 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2148 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2149 // Note that with all the client callbacks going on, by the time we get here all the
2150 // records we marked may have been explicitly deregistered by the client anyway.
2151 r2
= m
->DuplicateRecords
;
2154 if (r2
->ProbeCount
!= 0xFF)
2160 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2161 // See if this record was also registered with any D2D plugins.
2162 D2D_stop_advertising_record(r2
);
2164 mDNS_Deregister_internal(m
, r2
, mDNS_Dereg_conflict
);
2165 // As this is a duplicate record, it will be unlinked from the list
2167 r2
= m
->DuplicateRecords
;
2172 mDNS_UpdateAllowSleep(m
);
2173 return(mStatus_NoError
);
2176 // ***************************************************************************
2177 #if COMPILER_LIKES_PRAGMA_MARK
2179 #pragma mark - Packet Sending Functions
2182 mDNSlocal
void AddRecordToResponseList(AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*add
)
2184 if (rr
->NextResponse
== mDNSNULL
&& *nrpp
!= &rr
->NextResponse
)
2187 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2188 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2189 // The referenced record will definitely be acceptable (by recursive application of this rule)
2190 if (add
&& add
->NR_AdditionalTo
) add
= add
->NR_AdditionalTo
;
2191 rr
->NR_AdditionalTo
= add
;
2192 *nrpp
= &rr
->NextResponse
;
2194 debugf("AddRecordToResponseList: %##s (%s) already in list", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
2197 mDNSlocal
void AddRRSetAdditionalsToResponseList(mDNS
*const m
, AuthRecord
***nrpp
, AuthRecord
*rr
, AuthRecord
*additional
, const mDNSInterfaceID InterfaceID
)
2200 if (additional
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2202 for (rr2
= m
->ResourceRecords
; rr2
; rr2
= rr2
->next
)
2204 if ((rr2
->resrec
.namehash
== additional
->resrec
.namehash
) &&
2205 (rr2
->resrec
.rrtype
== additional
->resrec
.rrtype
) &&
2206 (rr2
!= additional
) &&
2207 (rr2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) &&
2208 (rr2
->resrec
.rrclass
== additional
->resrec
.rrclass
) &&
2209 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) &&
2210 SameDomainName(rr2
->resrec
.name
, additional
->resrec
.name
))
2212 AddRecordToResponseList(nrpp
, rr2
, rr
);
2218 mDNSlocal
void AddAdditionalsToResponseList(mDNS
*const m
, AuthRecord
*ResponseRecords
, AuthRecord
***nrpp
, const mDNSInterfaceID InterfaceID
)
2220 AuthRecord
*rr
, *rr2
;
2221 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // For each record we plan to put
2223 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2224 // later in the "for" loop, and we will follow further "additional" links then.)
2225 if (rr
->Additional1
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional1
, InterfaceID
))
2227 AddRecordToResponseList(nrpp
, rr
->Additional1
, rr
);
2228 AddRRSetAdditionalsToResponseList(m
, nrpp
, rr
, rr
->Additional1
, InterfaceID
);
2231 if (rr
->Additional2
&& ResourceRecordIsValidInterfaceAnswer(rr
->Additional2
, InterfaceID
))
2233 AddRecordToResponseList(nrpp
, rr
->Additional2
, rr
);
2234 AddRRSetAdditionalsToResponseList(m
, nrpp
, rr
, rr
->Additional2
, InterfaceID
);
2237 // For SRV records, automatically add the Address record(s) for the target host
2238 if (rr
->resrec
.rrtype
== kDNSType_SRV
)
2240 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
2241 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2242 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
2243 rr
->resrec
.rdatahash
== rr2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2244 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, rr2
->resrec
.name
))
2245 AddRecordToResponseList(nrpp
, rr2
, rr
);
2247 else if (RRTypeIsAddressType(rr
->resrec
.rrtype
)) // For A or AAAA, put counterpart as additional
2249 for (rr2
=m
->ResourceRecords
; rr2
; rr2
=rr2
->next
) // Scan list of resource records
2250 if (RRTypeIsAddressType(rr2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2251 ResourceRecordIsValidInterfaceAnswer(rr2
, InterfaceID
) && // ... which are valid for answer ...
2252 rr
->resrec
.namehash
== rr2
->resrec
.namehash
&& // ... and have the same name
2253 SameDomainName(rr
->resrec
.name
, rr2
->resrec
.name
))
2254 AddRecordToResponseList(nrpp
, rr2
, rr
);
2256 else if (rr
->resrec
.rrtype
== kDNSType_PTR
) // For service PTR, see if we want to add DeviceInfo record
2258 if (ResourceRecordIsValidInterfaceAnswer(&m
->DeviceInfo
, InterfaceID
) &&
2259 SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2260 AddRecordToResponseList(nrpp
, &m
->DeviceInfo
, rr
);
2265 mDNSlocal
void SendDelayedUnicastResponse(mDNS
*const m
, const mDNSAddr
*const dest
, const mDNSInterfaceID InterfaceID
)
2268 AuthRecord
*ResponseRecords
= mDNSNULL
;
2269 AuthRecord
**nrp
= &ResponseRecords
;
2270 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
2272 // Make a list of all our records that need to be unicast to this destination
2273 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2275 // If we find we can no longer unicast this answer, clear ImmedUnicast
2276 if (rr
->ImmedAnswer
== mDNSInterfaceMark
||
2277 mDNSSameIPv4Address(rr
->v4Requester
, onesIPv4Addr
) ||
2278 mDNSSameIPv6Address(rr
->v6Requester
, onesIPv6Addr
) )
2279 rr
->ImmedUnicast
= mDNSfalse
;
2281 if (rr
->ImmedUnicast
&& rr
->ImmedAnswer
== InterfaceID
)
2283 if ((dest
->type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->v4Requester
, dest
->ip
.v4
)) ||
2284 (dest
->type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->v6Requester
, dest
->ip
.v6
)))
2286 rr
->ImmedAnswer
= mDNSNULL
; // Clear the state fields
2287 rr
->ImmedUnicast
= mDNSfalse
;
2288 rr
->v4Requester
= zerov4Addr
;
2289 rr
->v6Requester
= zerov6Addr
;
2291 // Only sent records registered for P2P over P2P interfaces
2292 if (intf
&& !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
))
2297 if (rr
->NextResponse
== mDNSNULL
&& nrp
!= &rr
->NextResponse
) // rr->NR_AnswerTo
2299 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
2301 nrp
= &rr
->NextResponse
;
2307 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
2309 while (ResponseRecords
)
2311 mDNSu8
*responseptr
= m
->omsg
.data
;
2313 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2315 // Put answers in the packet
2316 while (ResponseRecords
&& ResponseRecords
->NR_AnswerTo
)
2318 rr
= ResponseRecords
;
2319 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2320 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2322 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
);
2324 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2325 if (!newptr
&& m
->omsg
.h
.numAnswers
)
2327 break; // If packet full, send it now
2329 if (newptr
) responseptr
= newptr
;
2330 ResponseRecords
= rr
->NextResponse
;
2331 rr
->NextResponse
= mDNSNULL
;
2332 rr
->NR_AnswerTo
= mDNSNULL
;
2333 rr
->NR_AdditionalTo
= mDNSNULL
;
2334 rr
->RequireGoodbye
= mDNStrue
;
2337 // Add additionals, if there's space
2338 while (ResponseRecords
&& !ResponseRecords
->NR_AnswerTo
)
2340 rr
= ResponseRecords
;
2341 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2342 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2343 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
2344 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2346 if (newptr
) responseptr
= newptr
;
2347 if (newptr
&& m
->omsg
.h
.numAnswers
) rr
->RequireGoodbye
= mDNStrue
;
2348 else if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
->ImmedAnswer
= mDNSInterfaceMark
;
2349 ResponseRecords
= rr
->NextResponse
;
2350 rr
->NextResponse
= mDNSNULL
;
2351 rr
->NR_AnswerTo
= mDNSNULL
;
2352 rr
->NR_AdditionalTo
= mDNSNULL
;
2355 if (m
->omsg
.h
.numAnswers
)
2356 mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, InterfaceID
, mDNSNULL
, mDNSNULL
, dest
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
2360 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2361 // and the client's mStatus_MemFree callback will have been invoked
2362 mDNSexport
void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
)
2364 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m
, rr
));
2365 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2366 // it should go ahead and immediately dispose of this registration
2367 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
2368 rr
->RequireGoodbye
= mDNSfalse
;
2369 rr
->WakeUp
.HMAC
= zeroEthAddr
;
2370 if (rr
->AnsweredLocalQ
) { AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_rmv
); rr
->AnsweredLocalQ
= mDNSfalse
; }
2371 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
); // Don't touch rr after this
2374 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2375 // any deregistering records that remain in the m->ResourceRecords list.
2376 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2377 // which may change the record list and/or question list.
2378 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2379 mDNSlocal
void DiscardDeregistrations(mDNS
*const m
)
2381 if (m
->CurrentRecord
)
2382 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
2383 m
->CurrentRecord
= m
->ResourceRecords
;
2385 while (m
->CurrentRecord
)
2387 AuthRecord
*rr
= m
->CurrentRecord
;
2388 if (!AuthRecord_uDNS(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2389 CompleteDeregistration(m
, rr
); // Don't touch rr after this
2391 m
->CurrentRecord
= rr
->next
;
2395 mDNSlocal mStatus
GetLabelDecimalValue(const mDNSu8
*const src
, mDNSu8
*dst
)
2398 if (src
[0] < 1 || src
[0] > 3) return(mStatus_Invalid
);
2399 for (i
=1; i
<=src
[0]; i
++)
2401 if (src
[i
] < '0' || src
[i
] > '9') return(mStatus_Invalid
);
2402 val
= val
* 10 + src
[i
] - '0';
2404 if (val
> 255) return(mStatus_Invalid
);
2406 return(mStatus_NoError
);
2409 mDNSlocal mStatus
GetIPv4FromName(mDNSAddr
*const a
, const domainname
*const name
)
2411 int skip
= CountLabels(name
) - 6;
2412 if (skip
< 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2413 if (GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+3)->c
, &a
->ip
.v4
.b
[0]) ||
2414 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+2)->c
, &a
->ip
.v4
.b
[1]) ||
2415 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+1)->c
, &a
->ip
.v4
.b
[2]) ||
2416 GetLabelDecimalValue(SkipLeadingLabels(name
, skip
+0)->c
, &a
->ip
.v4
.b
[3])) return mStatus_Invalid
;
2417 a
->type
= mDNSAddrType_IPv4
;
2418 return(mStatus_NoError
);
2421 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2422 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2423 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2425 mDNSlocal mStatus
GetIPv6FromName(mDNSAddr
*const a
, const domainname
*const name
)
2428 const domainname
*n
;
2430 int skip
= CountLabels(name
) - 34;
2431 if (skip
< 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name
); return mStatus_Invalid
; }
2433 n
= SkipLeadingLabels(name
, skip
);
2434 for (i
=0; i
<16; i
++)
2436 if (n
->c
[0] != 1) return mStatus_Invalid
;
2437 l
= HexVal(n
->c
[1]);
2438 n
= (const domainname
*)(n
->c
+ 2);
2440 if (n
->c
[0] != 1) return mStatus_Invalid
;
2441 h
= HexVal(n
->c
[1]);
2442 n
= (const domainname
*)(n
->c
+ 2);
2444 if (l
<0 || h
<0) return mStatus_Invalid
;
2445 a
->ip
.v6
.b
[15-i
] = (mDNSu8
)((h
<< 4) | l
);
2448 a
->type
= mDNSAddrType_IPv6
;
2449 return(mStatus_NoError
);
2452 mDNSlocal mDNSs32
ReverseMapDomainType(const domainname
*const name
)
2454 int skip
= CountLabels(name
) - 2;
2457 const domainname
*suffix
= SkipLeadingLabels(name
, skip
);
2458 if (SameDomainName(suffix
, (const domainname
*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4
;
2459 if (SameDomainName(suffix
, (const domainname
*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6
;
2461 return(mDNSAddrType_None
);
2464 mDNSlocal
void SendARP(mDNS
*const m
, const mDNSu8 op
, const AuthRecord
*const rr
,
2465 const mDNSv4Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2468 mDNSu8
*ptr
= m
->omsg
.data
;
2469 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2470 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2472 // 0x00 Destination address
2473 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2475 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2476 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
2478 // 0x0C ARP Ethertype (0x0806)
2479 *ptr
++ = 0x08; *ptr
++ = 0x06;
2482 *ptr
++ = 0x00; *ptr
++ = 0x01; // Hardware address space; Ethernet = 1
2483 *ptr
++ = 0x08; *ptr
++ = 0x00; // Protocol address space; IP = 0x0800
2484 *ptr
++ = 6; // Hardware address length
2485 *ptr
++ = 4; // Protocol address length
2486 *ptr
++ = 0x00; *ptr
++ = op
; // opcode; Request = 1, Response = 2
2488 // 0x16 Sender hardware address (our MAC address)
2489 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[i
];
2491 // 0x1C Sender protocol address
2492 for (i
=0; i
<4; i
++) *ptr
++ = spa
->b
[i
];
2494 // 0x20 Target hardware address
2495 for (i
=0; i
<6; i
++) *ptr
++ = tha
->b
[i
];
2497 // 0x26 Target protocol address
2498 for (i
=0; i
<4; i
++) *ptr
++ = tpa
->b
[i
];
2500 // 0x2A Total ARP Packet length 42 bytes
2501 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2504 mDNSlocal mDNSu16
CheckSum(const void *const data
, mDNSs32 length
, mDNSu32 sum
)
2506 const mDNSu16
*ptr
= data
;
2507 while (length
> 0) { length
-= 2; sum
+= *ptr
++; }
2508 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2509 sum
= (sum
& 0xFFFF) + (sum
>> 16);
2510 return(sum
!= 0xFFFF ? sum
: 0);
2513 mDNSlocal mDNSu16
IPv6CheckSum(const mDNSv6Addr
*const src
, const mDNSv6Addr
*const dst
, const mDNSu8 protocol
, const void *const data
, const mDNSu32 length
)
2515 IPv6PseudoHeader ph
;
2518 ph
.len
.b
[0] = length
>> 24;
2519 ph
.len
.b
[1] = length
>> 16;
2520 ph
.len
.b
[2] = length
>> 8;
2521 ph
.len
.b
[3] = length
;
2525 ph
.pro
.b
[3] = protocol
;
2526 return CheckSum(&ph
, sizeof(ph
), CheckSum(data
, length
, 0));
2529 mDNSlocal
void SendNDP(mDNS
*const m
, const mDNSu8 op
, const mDNSu8 flags
, const AuthRecord
*const rr
,
2530 const mDNSv6Addr
*const spa
, const mDNSEthAddr
*const tha
, const mDNSv6Addr
*const tpa
, const mDNSEthAddr
*const dst
)
2533 mDNSOpaque16 checksum
;
2534 mDNSu8
*ptr
= m
->omsg
.data
;
2535 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2536 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2537 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2538 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] } };
2539 const mDNSv6Addr
*const v6dst
= (op
== NDP_Sol
) ? &mc
: tpa
;
2540 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, rr
->resrec
.InterfaceID
);
2541 if (!intf
) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr
->resrec
.InterfaceID
, ARDisplayString(m
,rr
)); return; }
2543 // 0x00 Destination address
2544 for (i
=0; i
<6; i
++) *ptr
++ = dst
->b
[i
];
2545 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2546 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2547 // link with a pointless link-layer multicast.
2548 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2549 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2553 // *ptr++ = tpa->b[0xD];
2554 // *ptr++ = tpa->b[0xE];
2555 // *ptr++ = tpa->b[0xF];
2557 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2558 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2560 // 0x0C IPv6 Ethertype (0x86DD)
2561 *ptr
++ = 0x86; *ptr
++ = 0xDD;
2564 *ptr
++ = 0x60; *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00; // Version, Traffic Class, Flow Label
2565 *ptr
++ = 0x00; *ptr
++ = 0x20; // Length
2566 *ptr
++ = 0x3A; // Protocol == ICMPv6
2567 *ptr
++ = 0xFF; // Hop Limit
2569 // 0x16 Sender IPv6 address
2570 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2572 // 0x26 Destination IPv6 address
2573 for (i
=0; i
<16; i
++) *ptr
++ = v6dst
->b
[i
];
2576 *ptr
++ = op
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2577 *ptr
++ = 0x00; // Code
2578 *ptr
++ = 0x00; *ptr
++ = 0x00; // Checksum placeholder (0x38, 0x39)
2580 *ptr
++ = 0x00; *ptr
++ = 0x00; *ptr
++ = 0x00;
2582 if (op
== NDP_Sol
) // Neighbor Solicitation. The NDP "target" is the address we seek.
2585 for (i
=0; i
<16; i
++) *ptr
++ = tpa
->b
[i
];
2586 // 0x4E Source Link-layer Address
2587 // <http://www.ietf.org/rfc/rfc2461.txt>
2588 // MUST NOT be included when the source IP address is the unspecified address.
2589 // Otherwise, on link layers that have addresses this option MUST be included
2590 // in multicast solicitations and SHOULD be included in unicast solicitations.
2591 if (!mDNSIPv6AddressIsZero(*spa
))
2593 *ptr
++ = NDP_SrcLL
; // Option Type 1 == Source Link-layer Address
2594 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2595 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2598 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2601 for (i
=0; i
<16; i
++) *ptr
++ = spa
->b
[i
];
2602 // 0x4E Target Link-layer Address
2603 *ptr
++ = NDP_TgtLL
; // Option Type 2 == Target Link-layer Address
2604 *ptr
++ = 0x01; // Option length 1 (in units of 8 octets)
2605 for (i
=0; i
<6; i
++) *ptr
++ = (tha
? *tha
: intf
->MAC
).b
[i
];
2608 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2609 m
->omsg
.data
[0x13] = ptr
- &m
->omsg
.data
[0x36]; // Compute actual length
2610 checksum
.NotAnInteger
= ~IPv6CheckSum(spa
, v6dst
, 0x3A, &m
->omsg
.data
[0x36], m
->omsg
.data
[0x13]);
2611 m
->omsg
.data
[0x38] = checksum
.b
[0];
2612 m
->omsg
.data
[0x39] = checksum
.b
[1];
2614 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, rr
->resrec
.InterfaceID
);
2617 mDNSlocal
void SetupTracerOpt(const mDNS
*const m
, rdataOPT
*const Trace
)
2619 mDNSu32 DNS_VERS
= _DNS_SD_H
;
2620 Trace
->u
.tracer
.platf
= m
->mDNS_plat
;
2621 Trace
->u
.tracer
.mDNSv
= DNS_VERS
;
2623 Trace
->opt
= kDNSOpt_Trace
;
2624 Trace
->optlen
= DNSOpt_TraceData_Space
- 4;
2627 mDNSlocal
void SetupOwnerOpt(const mDNS
*const m
, const NetworkInterfaceInfo
*const intf
, rdataOPT
*const owner
)
2629 owner
->u
.owner
.vers
= 0;
2630 owner
->u
.owner
.seq
= m
->SleepSeqNum
;
2631 owner
->u
.owner
.HMAC
= m
->PrimaryMAC
;
2632 owner
->u
.owner
.IMAC
= intf
->MAC
;
2633 owner
->u
.owner
.password
= zeroEthAddr
;
2635 // Don't try to compute the optlen until *after* we've set up the data fields
2636 // 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
2637 owner
->opt
= kDNSOpt_Owner
;
2638 owner
->optlen
= DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) - 4;
2641 mDNSlocal
void GrantUpdateCredit(AuthRecord
*rr
)
2643 if (++rr
->UpdateCredits
>= kMaxUpdateCredits
) rr
->NextUpdateCredit
= 0;
2644 else rr
->NextUpdateCredit
= NonZeroTime(rr
->NextUpdateCredit
+ kUpdateCreditRefreshInterval
);
2647 mDNSlocal mDNSBool
ShouldSendGoodbyesBeforeSleep(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, AuthRecord
*rr
)
2649 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2650 // and hence there is no need to check for Transfering state. But if we have sleep
2651 // proxies and partially sending goodbyes for some records, we will be in Transfering
2652 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2653 // we are not awake handles both cases.
2654 if ((rr
->AuthFlags
& AuthFlagsWakeOnly
) && (m
->SleepState
!= SleepState_Awake
))
2656 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m
, rr
));
2660 if (m
->SleepState
!= SleepState_Sleeping
)
2663 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2664 // whether you can send goodbyes or not.
2665 if (!intf
->SendGoodbyes
)
2667 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2672 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m
, rr
), intf
->InterfaceID
);
2677 // Note about acceleration of announcements to facilitate automatic coalescing of
2678 // multiple independent threads of announcements into a single synchronized thread:
2679 // The announcements in the packet may be at different stages of maturity;
2680 // One-second interval, two-second interval, four-second interval, and so on.
2681 // After we've put in all the announcements that are due, we then consider
2682 // whether there are other nearly-due announcements that are worth accelerating.
2683 // To be eligible for acceleration, a record MUST NOT be older (further along
2684 // its timeline) than the most mature record we've already put in the packet.
2685 // In other words, younger records can have their timelines accelerated to catch up
2686 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2687 // Older records cannot have their timelines accelerated; this would just widen
2688 // the gap between them and their younger bretheren and get them even more out of sync.
2690 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2691 // the record list and/or question list.
2692 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2693 mDNSlocal
void SendResponses(mDNS
*const m
)
2696 AuthRecord
*rr
, *r2
;
2697 mDNSs32 maxExistingAnnounceInterval
= 0;
2698 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
2700 m
->NextScheduledResponse
= m
->timenow
+ FutureTime
;
2702 if (m
->SleepState
== SleepState_Transferring
) RetrySPSRegistrations(m
);
2704 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2705 if (rr
->ImmedUnicast
)
2707 mDNSAddr v4
= { mDNSAddrType_IPv4
, {{{0}}} };
2708 mDNSAddr v6
= { mDNSAddrType_IPv6
, {{{0}}} };
2709 v4
.ip
.v4
= rr
->v4Requester
;
2710 v6
.ip
.v6
= rr
->v6Requester
;
2711 if (!mDNSIPv4AddressIsZero(rr
->v4Requester
)) SendDelayedUnicastResponse(m
, &v4
, rr
->ImmedAnswer
);
2712 if (!mDNSIPv6AddressIsZero(rr
->v6Requester
)) SendDelayedUnicastResponse(m
, &v6
, rr
->ImmedAnswer
);
2713 if (rr
->ImmedUnicast
)
2715 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m
, rr
));
2716 rr
->ImmedUnicast
= mDNSfalse
;
2721 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2724 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2725 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2727 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
2728 if (TimeToAnnounceThisRecord(rr
, m
->timenow
))
2730 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
2732 if (!rr
->WakeUp
.HMAC
.l
[0])
2734 if (rr
->AnnounceCount
) rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send goodbye packet on all interfaces
2738 mDNSBool unicastOnly
;
2739 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr
->AnnounceCount
-3, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
2740 unicastOnly
= ((rr
->AnnounceCount
== WakeupCount
) || (rr
->AnnounceCount
== WakeupCount
- 1)) ? mDNStrue
: mDNSfalse
;
2741 SendWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.IMAC
, &rr
->WakeUp
.password
, unicastOnly
);
2742 for (r2
= rr
; r2
; r2
=r2
->next
)
2743 if ((r2
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) && r2
->AnnounceCount
&& (r2
->resrec
.InterfaceID
== rr
->resrec
.InterfaceID
) &&
2744 mDNSSameEthAddress(&r2
->WakeUp
.IMAC
, &rr
->WakeUp
.IMAC
) && !mDNSSameEthAddress(&zeroEthAddr
, &r2
->WakeUp
.HMAC
))
2746 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2747 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2748 if (r2
->AddressProxy
.type
== mDNSAddrType_IPv6
&& r2
->AnnounceCount
== WakeupCount
)
2750 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2751 r2
->AnnounceCount
-3, &r2
->WakeUp
.HMAC
, &r2
->WakeUp
.IMAC
, ARDisplayString(m
,r2
));
2752 SendNDP(m
, NDP_Adv
, NDP_Override
, r2
, &r2
->AddressProxy
.ip
.v6
, &r2
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2754 r2
->LastAPTime
= m
->timenow
;
2755 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2756 if (--r2
->AnnounceCount
<= GoodbyeCount
) r2
->WakeUp
.HMAC
= zeroEthAddr
;
2760 else if (ResourceRecordIsValidAnswer(rr
))
2762 if (rr
->AddressProxy
.type
)
2764 if (!mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
2766 rr
->AnnounceCount
--;
2767 rr
->ThisAPInterval
*= 2;
2768 rr
->LastAPTime
= m
->timenow
;
2769 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv4
)
2771 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2772 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2773 SendARP(m
, 1, rr
, &rr
->AddressProxy
.ip
.v4
, &zeroEthAddr
, &rr
->AddressProxy
.ip
.v4
, &onesEthAddr
);
2775 else if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
2777 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2778 rr
->AnnounceCount
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
2779 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
2785 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2786 if (maxExistingAnnounceInterval
< rr
->ThisAPInterval
)
2787 maxExistingAnnounceInterval
= rr
->ThisAPInterval
;
2788 if (rr
->UpdateBlocked
) rr
->UpdateBlocked
= 0;
2794 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2795 // Eligible records that are more than half-way to their announcement time are accelerated
2796 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2797 if ((rr
->resrec
.InterfaceID
&& rr
->ImmedAnswer
) ||
2798 (rr
->ThisAPInterval
<= maxExistingAnnounceInterval
&&
2799 TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2) &&
2800 !rr
->AddressProxy
.type
&& // Don't include ARP Annoucements when considering which records to accelerate
2801 ResourceRecordIsValidAnswer(rr
)))
2802 rr
->ImmedAnswer
= mDNSInterfaceMark
; // Send on all interfaces
2804 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2805 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2806 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2807 // then all that means is that it won't get sent -- which would not be the end of the world.
2808 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2810 if (rr
->ImmedAnswer
&& rr
->resrec
.rrtype
== kDNSType_SRV
)
2811 for (r2
=m
->ResourceRecords
; r2
; r2
=r2
->next
) // Scan list of resource records
2812 if (RRTypeIsAddressType(r2
->resrec
.rrtype
) && // For all address records (A/AAAA) ...
2813 ResourceRecordIsValidAnswer(r2
) && // ... which are valid for answer ...
2814 rr
->LastMCTime
- r2
->LastMCTime
>= 0 && // ... which we have not sent recently ...
2815 rr
->resrec
.rdatahash
== r2
->resrec
.namehash
&& // ... whose name is the name of the SRV target
2816 SameDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, r2
->resrec
.name
) &&
2817 (rr
->ImmedAnswer
== mDNSInterfaceMark
|| rr
->ImmedAnswer
== r2
->resrec
.InterfaceID
))
2818 r2
->ImmedAdditional
= r2
->resrec
.InterfaceID
; // ... then mark this address record for sending too
2819 // We also make sure we send the DeviceInfo TXT record too, if necessary
2820 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2821 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2822 if (rr
->ImmedAnswer
&& rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->resrec
.rrtype
== kDNSType_PTR
)
2823 if (ResourceRecordIsValidAnswer(&m
->DeviceInfo
) && SameDomainLabel(rr
->resrec
.rdata
->u
.name
.c
, m
->DeviceInfo
.resrec
.name
->c
))
2825 if (!m
->DeviceInfo
.ImmedAnswer
) m
->DeviceInfo
.ImmedAnswer
= rr
->ImmedAnswer
;
2826 else m
->DeviceInfo
.ImmedAnswer
= mDNSInterfaceMark
;
2830 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2831 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2832 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2833 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2834 // -- 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
2835 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2836 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2837 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2839 if (rr
->ImmedAnswer
) // If we're sending this as answer, see that its whole RRSet is similarly marked
2841 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2843 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2844 (r2
->ImmedAnswer
!= mDNSInterfaceMark
) && (r2
->ImmedAnswer
!= rr
->ImmedAnswer
) &&
2845 SameResourceRecordSignature(r2
, rr
) &&
2846 ((rr
->ImmedAnswer
== mDNSInterfaceMark
) || IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAnswer
)))
2848 r2
->ImmedAnswer
= !r2
->ImmedAnswer
? rr
->ImmedAnswer
: mDNSInterfaceMark
;
2852 else if (rr
->ImmedAdditional
) // If we're sending this as additional, see that its whole RRSet is similarly marked
2854 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
2856 if ((r2
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && ResourceRecordIsValidAnswer(r2
) &&
2857 (r2
->ImmedAdditional
!= rr
->ImmedAdditional
) &&
2858 SameResourceRecordSignature(r2
, rr
) &&
2859 IsInterfaceValidForAuthRecord(r2
, rr
->ImmedAdditional
))
2861 r2
->ImmedAdditional
= rr
->ImmedAdditional
;
2867 // Now set SendRNow state appropriately
2868 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2870 if (rr
->ImmedAnswer
== mDNSInterfaceMark
) // Sending this record on all appropriate interfaces
2872 rr
->SendRNow
= !intf
? mDNSNULL
: (rr
->resrec
.InterfaceID
) ? rr
->resrec
.InterfaceID
: intf
->InterfaceID
;
2873 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional if sending as answer
2874 rr
->LastMCTime
= m
->timenow
;
2875 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2876 rr
->ProbeRestartCount
= 0; // Reset the probe restart count
2877 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2878 if (TimeToAnnounceThisRecord(rr
, m
->timenow
+ rr
->ThisAPInterval
/2))
2880 rr
->AnnounceCount
--;
2881 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
2882 rr
->ThisAPInterval
*= 2;
2883 rr
->LastAPTime
= m
->timenow
;
2884 debugf("Announcing %##s (%s) %d", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), rr
->AnnounceCount
);
2887 else if (rr
->ImmedAnswer
) // Else, just respond to a single query on single interface:
2889 rr
->SendRNow
= rr
->ImmedAnswer
; // Just respond on that interface
2890 rr
->ImmedAdditional
= mDNSNULL
; // No need to send as additional too
2891 rr
->LastMCTime
= m
->timenow
;
2892 rr
->LastMCInterface
= rr
->ImmedAnswer
;
2894 SetNextAnnounceProbeTime(m
, rr
);
2895 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2899 // *** 2. Loop through interface list, sending records as appropriate
2904 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
2905 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
2907 int numAnnounce
= 0;
2909 mDNSu8
*responseptr
= m
->omsg
.data
;
2911 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, ResponseFlags
);
2913 // First Pass. Look for:
2914 // 1. Deregistering records that need to send their goodbye packet
2915 // 2. Updated records that need to retract their old data
2916 // 3. Answers and announcements we need to send
2917 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2920 // Skip this interface if the record InterfaceID is *Any and the record is not
2921 // appropriate for the interface type.
2922 if ((rr
->SendRNow
== intf
->InterfaceID
) &&
2923 ((rr
->resrec
.InterfaceID
== mDNSInterface_Any
) && !mDNSPlatformValidRecordForInterface(rr
, intf
->InterfaceID
)))
2925 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2927 else if (rr
->SendRNow
== intf
->InterfaceID
)
2929 RData
*OldRData
= rr
->resrec
.rdata
;
2930 mDNSu16 oldrdlength
= rr
->resrec
.rdlength
;
2931 mDNSu8 active
= (mDNSu8
)
2932 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& !ShouldSendGoodbyesBeforeSleep(m
, intf
, rr
));
2934 if (rr
->NewRData
&& active
)
2936 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2937 if (ResourceRecordIsValidAnswer(rr
) && rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
2939 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, 0);
2940 if (newptr
) { responseptr
= newptr
; numDereg
++; rr
->RequireGoodbye
= mDNSfalse
; }
2941 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
2943 SetNewRData(&rr
->resrec
, rr
->NewRData
, rr
->newrdlength
);
2946 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
2947 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
2948 newptr
= PutRR_OS_TTL(responseptr
, &m
->omsg
.h
.numAnswers
, &rr
->resrec
, active
? rr
->resrec
.rroriginalttl
: 0);
2949 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
2952 responseptr
= newptr
;
2953 rr
->RequireGoodbye
= active
;
2954 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) numDereg
++;
2955 else if (rr
->LastAPTime
== m
->timenow
) numAnnounce
++;else numAnswer
++;
2958 if (rr
->NewRData
&& active
)
2959 SetNewRData(&rr
->resrec
, OldRData
, oldrdlength
);
2961 // The first time through (pktcount==0), if this record is verified unique
2962 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2963 if (!pktcount
&& active
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
2964 rr
->SendNSECNow
= mDNSInterfaceMark
;
2966 if (newptr
) // If succeeded in sending, advance to next interface
2968 // If sending on all interfaces, go to next interface; else we're finished now
2969 if (rr
->ImmedAnswer
== mDNSInterfaceMark
&& rr
->resrec
.InterfaceID
== mDNSInterface_Any
)
2970 rr
->SendRNow
= GetNextActiveInterfaceID(intf
);
2972 rr
->SendRNow
= mDNSNULL
;
2977 // Second Pass. Add additional records, if there's space.
2978 newptr
= responseptr
;
2979 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
2980 if (rr
->ImmedAdditional
== intf
->InterfaceID
)
2981 if (ResourceRecordIsValidAnswer(rr
))
2983 // If we have at least one answer already in the packet, then plan to add additionals too
2984 mDNSBool SendAdditional
= (m
->omsg
.h
.numAnswers
> 0);
2986 // If we're not planning to send any additionals, but this record is a unique one, then
2987 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2988 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2989 if (!SendAdditional
&& (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
2991 const AuthRecord
*a
;
2992 for (a
= m
->ResourceRecords
; a
; a
=a
->next
)
2993 if (a
->LastMCTime
== m
->timenow
&&
2994 a
->LastMCInterface
== intf
->InterfaceID
&&
2995 SameResourceRecordSignature(a
, rr
)) { SendAdditional
= mDNStrue
; break; }
2997 if (!SendAdditional
) // If we don't want to send this after all,
2998 rr
->ImmedAdditional
= mDNSNULL
; // then cancel its ImmedAdditional field
2999 else if (newptr
) // Else, try to add it if we can
3001 // The first time through (pktcount==0), if this record is verified unique
3002 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
3003 if (!pktcount
&& (rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && !rr
->SendNSECNow
)
3004 rr
->SendNSECNow
= mDNSInterfaceMark
;
3006 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
3007 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the cache flush bit so PutResourceRecord will set it
3008 newptr
= PutRR_OS(newptr
, &m
->omsg
.h
.numAdditionals
, &rr
->resrec
);
3009 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear cache flush bit back to normal state
3012 responseptr
= newptr
;
3013 rr
->ImmedAdditional
= mDNSNULL
;
3014 rr
->RequireGoodbye
= mDNStrue
;
3015 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
3016 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
3017 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3018 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3019 rr
->LastMCTime
= m
->timenow
;
3020 rr
->LastMCInterface
= intf
->InterfaceID
;
3025 // Third Pass. Add NSEC records, if there's space.
3026 // When we're generating an NSEC record in response to a specify query for that type
3027 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3028 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3029 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
3030 if (rr
->SendNSECNow
== mDNSInterfaceMark
|| rr
->SendNSECNow
== intf
->InterfaceID
)
3035 mDNS_SetupResourceRecord(&nsec
, mDNSNULL
, mDNSInterface_Any
, kDNSType_NSEC
, rr
->resrec
.rroriginalttl
, kDNSRecordTypeUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3036 nsec
.resrec
.rrclass
|= kDNSClass_UniqueRRSet
;
3037 AssignDomainName(&nsec
.namestorage
, rr
->resrec
.name
);
3038 ptr
= nsec
.rdatastorage
.u
.data
;
3039 len
= DomainNameLength(rr
->resrec
.name
);
3040 // We have a nxt name followed by window number, window length and a window bitmap
3041 nsec
.resrec
.rdlength
= len
+ 2 + NSEC_MCAST_WINDOW_SIZE
;
3042 if (nsec
.resrec
.rdlength
<= StandardAuthRDSize
)
3044 mDNSPlatformMemZero(ptr
, nsec
.resrec
.rdlength
);
3045 AssignDomainName((domainname
*)ptr
, rr
->resrec
.name
);
3047 *ptr
++ = 0; // window number
3048 *ptr
++ = NSEC_MCAST_WINDOW_SIZE
; // window length
3049 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
3050 if (ResourceRecordIsValidAnswer(r2
) && SameResourceRecordNameClassInterface(r2
, rr
))
3052 if (r2
->resrec
.rrtype
>= kDNSQType_ANY
) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m
, r2
)); break; }
3053 else ptr
[r2
->resrec
.rrtype
>> 3] |= 128 >> (r2
->resrec
.rrtype
& 7);
3055 newptr
= responseptr
;
3056 if (!r2
) // If we successfully built our NSEC record, add it to the packet now
3058 newptr
= PutRR_OS(responseptr
, &m
->omsg
.h
.numAdditionals
, &nsec
.resrec
);
3059 if (newptr
) responseptr
= newptr
;
3062 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec
.resrec
.rdlength
);
3064 // If we successfully put the NSEC record, clear the SendNSECNow flag
3065 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3066 if (newptr
|| rr
->SendNSECNow
== mDNSInterfaceMark
)
3068 rr
->SendNSECNow
= mDNSNULL
;
3069 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3070 for (r2
= rr
->next
; r2
; r2
=r2
->next
)
3071 if (SameResourceRecordNameClassInterface(r2
, rr
))
3072 if (r2
->SendNSECNow
== mDNSInterfaceMark
|| r2
->SendNSECNow
== intf
->InterfaceID
)
3073 r2
->SendNSECNow
= mDNSNULL
;
3077 if (m
->omsg
.h
.numAnswers
|| m
->omsg
.h
.numAdditionals
)
3079 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3080 if (OwnerRecordSpace
|| TraceRecordSpace
)
3083 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
3084 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
3085 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
3086 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
3087 if (OwnerRecordSpace
&& TraceRecordSpace
)
3089 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
3090 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
3091 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3092 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
3094 else if (OwnerRecordSpace
)
3096 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
3098 else if (TraceRecordSpace
)
3100 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
3102 newptr
= PutResourceRecord(&m
->omsg
, responseptr
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
);
3105 responseptr
= newptr
;
3107 else if (m
->omsg
.h
.numAnswers
+ m
->omsg
.h
.numAuthorities
+ m
->omsg
.h
.numAdditionals
== 1)
3109 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3110 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3114 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
3115 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
3119 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3120 numDereg
, numDereg
== 1 ? "" : "s",
3121 numAnnounce
, numAnnounce
== 1 ? "" : "s",
3122 numAnswer
, numAnswer
== 1 ? "" : "s",
3123 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s", intf
->InterfaceID
);
3125 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
3126 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, responseptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, mDNSfalse
);
3127 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
3128 if (++pktcount
>= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount
); break; }
3129 // There might be more things to send on this interface, so go around one more time and try again.
3131 else // Nothing more to send on this interface; go to next
3133 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
3134 #if MDNS_DEBUGMSGS && 0
3135 const char *const msg
= next
? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3136 debugf(msg
, intf
, next
);
3139 pktcount
= 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3144 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3147 if (m
->CurrentRecord
)
3148 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3149 m
->CurrentRecord
= m
->ResourceRecords
;
3150 while (m
->CurrentRecord
)
3152 rr
= m
->CurrentRecord
;
3153 m
->CurrentRecord
= rr
->next
;
3157 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
)
3158 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3159 IIDPrintable(rr
->SendRNow
), IIDPrintable(rr
->resrec
.InterfaceID
), rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
3160 rr
->SendRNow
= mDNSNULL
;
3163 if (rr
->ImmedAnswer
|| rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
3165 if (rr
->NewRData
) CompleteRDataUpdate(m
, rr
); // Update our rdata, clear the NewRData pointer, and return memory to the client
3167 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
&& rr
->AnnounceCount
== 0)
3169 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3170 if (!AuthRecord_uDNS(rr
)) CompleteDeregistration(m
, rr
); // Don't touch rr after this
3174 rr
->ImmedAnswer
= mDNSNULL
;
3175 rr
->ImmedUnicast
= mDNSfalse
;
3176 rr
->v4Requester
= zerov4Addr
;
3177 rr
->v6Requester
= zerov6Addr
;
3181 verbosedebugf("SendResponses: Next in %ld ticks", m
->NextScheduledResponse
- m
->timenow
);
3184 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3185 // so we want to be lazy about how frequently we do it.
3186 // 1. If a cache record is currently referenced by *no* active questions,
3187 // then we don't mind expiring it up to a minute late (who will know?)
3188 // 2. Else, if a cache record is due for some of its final expiration queries,
3189 // we'll allow them to be late by up to 2% of the TTL
3190 // 3. Else, if a cache record has completed all its final expiration queries without success,
3191 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3192 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3193 // so allow at most 1/10 second lateness
3194 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3195 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3196 #define CacheCheckGracePeriod(CR) ( \
3197 ((CR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3198 ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50) : \
3199 ((CR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3200 ((CR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3202 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3204 mDNSexport
void ScheduleNextCacheCheckTime(mDNS
*const m
, const mDNSu32 slot
, const mDNSs32 event
)
3206 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
3207 m
->rrcache_nextcheck
[slot
] = event
;
3208 if (m
->NextCacheCheck
- event
> 0)
3209 m
->NextCacheCheck
= event
;
3212 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3214 // rr->resrec.rroriginalttl
3215 // rr->UnansweredQueries
3216 // rr->CRActiveQuestion
3217 mDNSexport
void SetNextCacheCheckTimeForRecord(mDNS
*const m
, CacheRecord
*const rr
)
3219 rr
->NextRequiredQuery
= RRExpireTime(rr
);
3221 // If we have an active question, then see if we want to schedule a refresher query for this record.
3222 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3223 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
3225 rr
->NextRequiredQuery
-= TicksTTL(rr
)/20 * (MaxUnansweredQueries
- rr
->UnansweredQueries
);
3226 rr
->NextRequiredQuery
+= mDNSRandom((mDNSu32
)TicksTTL(rr
)/50);
3227 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3228 (rr
->NextRequiredQuery
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
,rr
));
3230 ScheduleNextCacheCheckTime(m
, HashSlotFromNameHash(rr
->resrec
.namehash
), NextCacheCheckEvent(rr
));
3233 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3234 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3235 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3237 // Delay before restarting questions on a flapping interface.
3238 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3239 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3240 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3241 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3243 mDNSexport mStatus
mDNS_Reconfirm_internal(mDNS
*const m
, CacheRecord
*const rr
, mDNSu32 interval
)
3245 if (interval
< kMinimumReconfirmTime
)
3246 interval
= kMinimumReconfirmTime
;
3247 if (interval
> 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3248 interval
= 0x10000000;
3250 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3251 if (RRExpireTime(rr
) - m
->timenow
> (mDNSs32
)((interval
* 4) / 3))
3253 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3254 // For all the reconfirmations in a given batch, we want to use the same random value
3255 // so that the reconfirmation questions can be grouped into a single query packet
3256 if (!m
->RandomReconfirmDelay
) m
->RandomReconfirmDelay
= 1 + mDNSRandom(FutureTime
);
3257 interval
+= m
->RandomReconfirmDelay
% ((interval
/3) + 1);
3258 rr
->TimeRcvd
= m
->timenow
- (mDNSs32
)interval
* 3;
3259 rr
->resrec
.rroriginalttl
= (interval
* 4 + mDNSPlatformOneSecond
- 1) / mDNSPlatformOneSecond
;
3260 SetNextCacheCheckTimeForRecord(m
, rr
);
3262 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3263 RRExpireTime(rr
) - m
->timenow
, CRDisplayString(m
, rr
), rr
->CRActiveQuestion
);
3264 return(mStatus_NoError
);
3267 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3268 // It also appends to the list of known answer records that need to be included,
3269 // and updates the forcast for the size of the known answer section.
3270 mDNSlocal mDNSBool
BuildQuestion(mDNS
*const m
, const NetworkInterfaceInfo
*intf
, DNSMessage
*query
, mDNSu8
**queryptr
,
3271 DNSQuestion
*q
, CacheRecord
***kalistptrptr
, mDNSu32
*answerforecast
)
3273 mDNSBool ucast
= (q
->LargeAnswers
|| q
->RequestUnicast
) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3274 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3275 const mDNSu8
*const limit
= query
->data
+ NormalMaxDNSMessageData
;
3276 mDNSu8
*newptr
= putQuestion(query
, *queryptr
, limit
- *answerforecast
, &q
->qname
, q
->qtype
, (mDNSu16
)(q
->qclass
| ucbit
));
3279 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3284 mDNSu32 forecast
= *answerforecast
;
3285 const CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3287 CacheRecord
**ka
= *kalistptrptr
; // Make a working copy of the pointer we're going to update
3289 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // If we have a resource record in our cache,
3290 if (cr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3291 !(cr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
) && // which is a shared (i.e. not unique) record type
3292 cr
->NextInKAList
== mDNSNULL
&& ka
!= &cr
->NextInKAList
&& // which is not already in the known answer list
3293 cr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3294 SameNameCacheRecordAnswersQuestion(cr
, q
) && // which answers our question
3295 cr
->TimeRcvd
+ TicksTTL(cr
)/2 - m
->timenow
> // and its half-way-to-expiry time is at least 1 second away
3296 mDNSPlatformOneSecond
) // (also ensures we never include goodbye records with TTL=1)
3298 // We don't want to include unique records in the Known Answer section. The Known Answer section
3299 // is intended to suppress floods of shared-record replies from many other devices on the network.
3300 // That concept really does not apply to unique records, and indeed if we do send a query for
3301 // which we have a unique record already in our cache, then including that unique record as a
3302 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3304 *ka
= cr
; // Link this record into our known answer chain
3305 ka
= &cr
->NextInKAList
;
3306 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3307 forecast
+= 12 + cr
->resrec
.rdestimate
;
3308 // If we're trying to put more than one question in this packet, and it doesn't fit
3309 // then undo that last question and try again next time
3310 if (query
->h
.numQuestions
> 1 && newptr
+ forecast
>= limit
)
3312 query
->h
.numQuestions
--;
3313 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3314 q
->qname
.c
, DNSTypeName(q
->qtype
), newptr
+ forecast
- query
->data
, query
->h
.numQuestions
);
3315 ka
= *kalistptrptr
; // Go back to where we started and retract these answer records
3316 while (*ka
) { CacheRecord
*c
= *ka
; *ka
= mDNSNULL
; ka
= &c
->NextInKAList
; }
3317 return(mDNSfalse
); // Return false, so we'll try again in the next packet
3321 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3322 *queryptr
= newptr
; // Update the packet pointer
3323 *answerforecast
= forecast
; // Update the forecast
3324 *kalistptrptr
= ka
; // Update the known answer list pointer
3325 if (ucast
) q
->ExpectUnicastResp
= NonZeroTime(m
->timenow
);
3327 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // For every resource record in our cache,
3328 if (cr
->resrec
.InterfaceID
== q
->SendQNow
&& // received on this interface
3329 cr
->NextInKAList
== mDNSNULL
&& ka
!= &cr
->NextInKAList
&& // which is not in the known answer list
3330 SameNameCacheRecordAnswersQuestion(cr
, q
)) // which answers our question
3332 cr
->UnansweredQueries
++; // indicate that we're expecting a response
3333 cr
->LastUnansweredTime
= m
->timenow
;
3334 SetNextCacheCheckTimeForRecord(m
, cr
);
3341 // When we have a query looking for a specified name, but there appear to be no answers with
3342 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3343 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3344 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3345 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3346 // A typical reconfirmation scenario might go like this:
3347 // Depth 0: Name "myhost.local" has no address records
3348 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3349 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3350 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3351 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3352 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3353 mDNSlocal
void ReconfirmAntecedents(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSInterfaceID InterfaceID
, const int depth
)
3356 const CacheGroup
*cg
;
3358 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth
, name
->c
);
3359 if (!InterfaceID
) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3360 FORALL_CACHERECORDS(slot
, cg
, cr
)
3362 const domainname
*crtarget
;
3363 if (cr
->resrec
.InterfaceID
!= InterfaceID
) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3364 if (cr
->resrec
.rdatahash
!= namehash
) continue; // Skip records whose rdata hash doesn't match the name hash.
3365 crtarget
= GetRRDomainNameTarget(&cr
->resrec
);
3366 if (crtarget
&& SameDomainName(crtarget
, name
))
3368 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth
, InterfaceID
, CRDisplayString(m
, cr
));
3369 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
3371 ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, InterfaceID
, depth
+1);
3376 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3377 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3378 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3379 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3380 mDNSlocal
const CacheRecord
*CacheHasAddressTypeForName(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
3382 CacheGroup
*const cg
= CacheGroupForName(m
, namehash
, name
);
3383 const CacheRecord
*cr
= cg
? cg
->members
: mDNSNULL
;
3384 while (cr
&& !RRTypeIsAddressType(cr
->resrec
.rrtype
)) cr
=cr
->next
;
3389 mDNSlocal
const CacheRecord
*FindSPSInCache1(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*const c0
, const CacheRecord
*const c1
)
3391 #ifndef SPC_DISABLED
3392 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3393 const CacheRecord
*cr
, *bestcr
= mDNSNULL
;
3394 mDNSu32 bestmetric
= 1000000;
3395 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
3396 if (cr
->resrec
.rrtype
== kDNSType_PTR
&& cr
->resrec
.rdlength
>= 6) // If record is PTR type, with long enough name,
3397 if (cr
!= c0
&& cr
!= c1
) // that's not one we've seen before,
3398 if (SameNameCacheRecordAnswersQuestion(cr
, q
)) // and answers our browse query,
3399 if (!IdenticalSameNameRecord(&cr
->resrec
, &m
->SPSRecords
.RR_PTR
.resrec
)) // and is not our own advertised service...
3401 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
3402 if (bestmetric
> metric
) { bestmetric
= metric
; bestcr
= cr
; }
3405 #else // SPC_DISABLED
3412 #endif // SPC_DISABLED
3415 mDNSlocal
void CheckAndSwapSPS(const CacheRecord
**sps1
, const CacheRecord
**sps2
)
3417 const CacheRecord
*swap_sps
;
3418 mDNSu32 metric1
, metric2
;
3420 if (!(*sps1
) || !(*sps2
)) return;
3421 metric1
= SPSMetric((*sps1
)->resrec
.rdata
->u
.name
.c
);
3422 metric2
= SPSMetric((*sps2
)->resrec
.rdata
->u
.name
.c
);
3423 if (!SPSFeatures((*sps1
)->resrec
.rdata
->u
.name
.c
) && SPSFeatures((*sps2
)->resrec
.rdata
->u
.name
.c
) && (metric2
>= metric1
))
3431 mDNSlocal
void ReorderSPSByFeature(const CacheRecord
*sps
[3])
3433 CheckAndSwapSPS(&sps
[0], &sps
[1]);
3434 CheckAndSwapSPS(&sps
[0], &sps
[2]);
3435 CheckAndSwapSPS(&sps
[1], &sps
[2]);
3439 // Finds the three best Sleep Proxies we currently have in our cache
3440 mDNSexport
void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3])
3442 sps
[0] = FindSPSInCache1(m
, q
, mDNSNULL
, mDNSNULL
);
3443 sps
[1] = !sps
[0] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], mDNSNULL
);
3444 sps
[2] = !sps
[1] ? mDNSNULL
: FindSPSInCache1(m
, q
, sps
[0], sps
[1]);
3446 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3447 // only if they have equally good metric and support features.
3448 ReorderSPSByFeature(sps
);
3451 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3452 mDNSlocal
void ExpireDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
)
3455 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3458 mDNSlocal
void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 time
, mDNSInterfaceID InterfaceID
)
3461 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Time
- time
< 0) ds
[i
].InterfaceID
= mDNSNULL
;
3464 mDNSlocal mDNSBool
SuppressOnThisInterface(const DupSuppressInfo ds
[DupSuppressInfoSize
], const NetworkInterfaceInfo
* const intf
)
3467 mDNSBool v4
= !intf
->IPv4Available
; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3468 mDNSBool v6
= !intf
->IPv6Available
; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3469 for (i
=0; i
<DupSuppressInfoSize
; i
++)
3470 if (ds
[i
].InterfaceID
== intf
->InterfaceID
)
3472 if (ds
[i
].Type
== mDNSAddrType_IPv4
) v4
= mDNStrue
;
3473 else if (ds
[i
].Type
== mDNSAddrType_IPv6
) v6
= mDNStrue
;
3474 if (v4
&& v6
) return(mDNStrue
);
3479 mDNSlocal
void RecordDupSuppressInfo(DupSuppressInfo ds
[DupSuppressInfoSize
], mDNSs32 Time
, mDNSInterfaceID InterfaceID
, mDNSs32 Type
)
3483 // See if we have this one in our list somewhere already
3484 for (i
=0; i
<DupSuppressInfoSize
; i
++) if (ds
[i
].InterfaceID
== InterfaceID
&& ds
[i
].Type
== Type
) break;
3486 // If not, find a slot we can re-use
3487 if (i
>= DupSuppressInfoSize
)
3490 for (j
=1; j
<DupSuppressInfoSize
&& ds
[i
].InterfaceID
; j
++)
3491 if (!ds
[j
].InterfaceID
|| ds
[j
].Time
- ds
[i
].Time
< 0)
3495 // Record the info about this query we saw
3497 ds
[i
].InterfaceID
= InterfaceID
;
3501 mDNSlocal
void mDNSSendWakeOnResolve(mDNS
*const m
, DNSQuestion
*q
)
3504 mDNSInterfaceID InterfaceID
= q
->InterfaceID
;
3505 domainname
*d
= &q
->qname
;
3507 // We can't send magic packets without knowing which interface to send it on.
3508 if (InterfaceID
== mDNSInterface_Any
|| LocalOnlyOrP2PInterface(InterfaceID
))
3510 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID
, q
->qname
.c
);
3514 // Split MAC@IPAddress and pass them separately
3517 for (i
= 1; i
< len
; i
++)
3521 char EthAddr
[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3522 char IPAddr
[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3525 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q
->qname
.c
, cnt
);
3528 if ((i
- 1) > (int) (sizeof(EthAddr
) - 1))
3530 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q
->qname
.c
, i
- 1);
3533 if ((len
- i
) > (int)(sizeof(IPAddr
) - 1))
3535 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q
->qname
.c
, len
- i
);
3538 mDNSPlatformMemCopy(EthAddr
, &d
->c
[1], i
- 1);
3540 mDNSPlatformMemCopy(IPAddr
, &d
->c
[i
+ 1], len
- i
);
3541 IPAddr
[len
- i
] = 0;
3542 m
->mDNSStats
.WakeOnResolves
++;
3543 mDNSPlatformSendWakeupPacket(InterfaceID
, EthAddr
, IPAddr
, InitialWakeOnResolveCount
- q
->WakeOnResolveCount
);
3546 else if (d
->c
[i
] == ':')
3549 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q
->qname
.c
);
3553 mDNSlocal mDNSBool
AccelerateThisQuery(mDNS
*const m
, DNSQuestion
*q
)
3555 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3556 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/10))
3559 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3560 if (TimeToSendThisQuestion(q
, m
->timenow
+ q
->ThisQInterval
/2))
3562 // We forecast: qname (n) type (2) class (2)
3563 mDNSu32 forecast
= (mDNSu32
)DomainNameLength(&q
->qname
) + 4;
3564 const CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
3565 const CacheRecord
*cr
;
3566 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
) // If we have a resource record in our cache,
3567 if (cr
->resrec
.rdlength
<= SmallRecordLimit
&& // which is small enough to sensibly fit in the packet
3568 SameNameCacheRecordAnswersQuestion(cr
, q
) && // which answers our question
3569 cr
->TimeRcvd
+ TicksTTL(cr
)/2 - m
->timenow
>= 0 && // and it is less than half-way to expiry
3570 cr
->NextRequiredQuery
- (m
->timenow
+ q
->ThisQInterval
) > 0) // and we'll ask at least once again before NextRequiredQuery
3572 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3573 forecast
+= 12 + cr
->resrec
.rdestimate
;
3574 if (forecast
>= 512) return(mDNSfalse
); // If this would add 512 bytes or more to the packet, don't accelerate
3582 // How Standard Queries are generated:
3583 // 1. The Question Section contains the question
3584 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3586 // How Probe Queries are generated:
3587 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3588 // if some other host is already using *any* records with this name, we want to know about it.
3589 // 2. The Authority Section contains the proposed values we intend to use for one or more
3590 // of our records with that name (analogous to the Update section of DNS Update packets)
3591 // because if some other host is probing at the same time, we each want to know what the other is
3592 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3594 mDNSlocal
void SendQueries(mDNS
*const m
)
3602 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3603 mDNSs32 maxExistingQuestionInterval
= 0;
3604 const NetworkInterfaceInfo
*intf
= GetFirstActiveInterface(m
->HostInterfaces
);
3605 CacheRecord
*KnownAnswerList
= mDNSNULL
;
3607 // 1. If time for a query, work out what we need to do
3609 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3610 // to their NextRequiredQuery to be worth batching them together with this one
3611 FORALL_CACHERECORDS(slot
, cg
, cr
)
3613 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
3615 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
3617 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
3618 q
= cr
->CRActiveQuestion
;
3619 ExpireDupSuppressInfoOnInterface(q
->DupSuppress
, m
->timenow
- TicksTTL(cr
)/20, cr
->resrec
.InterfaceID
);
3620 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3621 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3622 if (!mDNSOpaque16IsZero(q
->TargetQID
))
3624 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
3625 cr
->UnansweredQueries
++;
3626 m
->mDNSStats
.CacheRefreshQueries
++;
3628 else if (q
->SendQNow
== mDNSNULL
)
3630 q
->SendQNow
= cr
->resrec
.InterfaceID
;
3632 else if (q
->SendQNow
!= cr
->resrec
.InterfaceID
)
3634 q
->SendQNow
= mDNSInterfaceMark
;
3637 // Indicate that this question was marked for sending
3638 // to update an existing cached answer record.
3639 // The browse throttling logic below uses this to determine
3640 // if the query should be sent.
3641 if (mDNSOpaque16IsZero(q
->TargetQID
))
3642 q
->CachedAnswerNeedsUpdate
= mDNStrue
;
3647 // Scan our list of questions to see which:
3648 // *WideArea* queries need to be sent
3649 // *unicast* queries need to be sent
3650 // *multicast* queries we're definitely going to send
3651 if (m
->CurrentQuestion
)
3652 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3653 m
->CurrentQuestion
= m
->Questions
;
3654 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
3656 q
= m
->CurrentQuestion
;
3657 if (mDNSOpaque16IsZero(q
->TargetQID
) && TimeToSendThisQuestion(q
, m
->timenow
))
3659 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3660 q
->SendQNow
= mDNSInterfaceMark
; // Mark this question for sending on all interfaces
3661 if (maxExistingQuestionInterval
< q
->ThisQInterval
)
3662 maxExistingQuestionInterval
= q
->ThisQInterval
;
3664 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3665 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3666 // m->CurrentQuestion point to the right question
3667 if (q
== m
->CurrentQuestion
) m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3669 while (m
->CurrentQuestion
)
3671 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
3672 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
3674 m
->CurrentQuestion
= mDNSNULL
;
3676 // Scan our list of questions
3677 // (a) to see if there are any more that are worth accelerating, and
3678 // (b) to update the state variables for *all* the questions we're going to send
3679 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3680 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3681 // 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.
3682 m
->NextScheduledQuery
= m
->timenow
+ FutureTime
;
3683 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3685 if (mDNSOpaque16IsZero(q
->TargetQID
)
3686 && (q
->SendQNow
|| (ActiveQuestion(q
) && q
->ThisQInterval
<= maxExistingQuestionInterval
&& AccelerateThisQuery(m
,q
))))
3688 // If at least halfway to next query time, advance to next interval
3689 // If less than halfway to next query time, then
3690 // treat this as logically a repeat of the last transmission, without advancing the interval
3691 if (m
->timenow
- (q
->LastQTime
+ (q
->ThisQInterval
/2)) >= 0)
3693 // If we have reached the answer threshold for this question,
3694 // don't send it again until MaxQuestionInterval unless:
3695 // one of its cached answers needs to be refreshed,
3696 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3697 if (q
->BrowseThreshold
3698 && (q
->CurrentAnswers
>= q
->BrowseThreshold
)
3699 && (q
->CachedAnswerNeedsUpdate
== mDNSfalse
)
3700 && !((q
->flags
& kDNSServiceFlagsThresholdFinder
) && (q
->ThisQInterval
== InitialQuestionInterval
)))
3702 q
->SendQNow
= mDNSNULL
;
3703 q
->ThisQInterval
= MaxQuestionInterval
;
3704 q
->LastQTime
= m
->timenow
;
3705 q
->RequestUnicast
= 0;
3706 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3707 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
3711 // Mark this question for sending on all interfaces
3712 q
->SendQNow
= mDNSInterfaceMark
;
3713 q
->ThisQInterval
*= QuestionIntervalStep
;
3716 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3717 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->ThisQInterval
/ InitialQuestionInterval
, q
->RequestUnicast
);
3719 if (q
->ThisQInterval
> MaxQuestionInterval
)
3721 q
->ThisQInterval
= MaxQuestionInterval
;
3723 else if (mDNSOpaque16IsZero(q
->TargetQID
) && q
->InterfaceID
&&
3724 q
->CurrentAnswers
== 0 && q
->ThisQInterval
== InitialQuestionInterval
* QuestionIntervalStep3
&& !q
->RequestUnicast
&&
3725 !(RRTypeIsAddressType(q
->qtype
) && CacheHasAddressTypeForName(m
, &q
->qname
, q
->qnamehash
)))
3727 // Generally don't need to log this.
3728 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3729 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3730 // and when there simply happen to be no instances of the service the client is looking
3731 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3732 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3733 q
->qname
.c
, DNSTypeName(q
->qtype
));
3734 // Sending third query, and no answers yet; time to begin doubting the source
3735 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, q
->InterfaceID
, 0);
3739 // Mark for sending. (If no active interfaces, then don't even try.)
3740 q
->SendOnAll
= (q
->SendQNow
== mDNSInterfaceMark
);
3743 q
->SendQNow
= !intf
? mDNSNULL
: (q
->InterfaceID
) ? q
->InterfaceID
: intf
->InterfaceID
;
3744 q
->LastQTime
= m
->timenow
;
3747 // If we recorded a duplicate suppression for this question less than half an interval ago,
3748 // then we consider it recent enough that we don't need to do an identical query ourselves.
3749 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
- q
->ThisQInterval
/2);
3751 q
->LastQTxTime
= m
->timenow
;
3752 q
->RecentAnswerPkts
= 0;
3753 if (q
->RequestUnicast
) q
->RequestUnicast
--;
3755 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3756 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3757 SetNextQueryTime(m
,q
);
3760 // 2. Scan our authoritative RR list to see what probes we might need to send
3762 m
->NextScheduledProbe
= m
->timenow
+ FutureTime
;
3764 if (m
->CurrentRecord
)
3765 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
3766 m
->CurrentRecord
= m
->ResourceRecords
;
3767 while (m
->CurrentRecord
)
3769 ar
= m
->CurrentRecord
;
3770 m
->CurrentRecord
= ar
->next
;
3771 if (!AuthRecord_uDNS(ar
) && ar
->resrec
.RecordType
== kDNSRecordTypeUnique
) // For all records that are still probing...
3773 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3774 if (m
->timenow
- (ar
->LastAPTime
+ ar
->ThisAPInterval
) < 0)
3776 SetNextAnnounceProbeTime(m
, ar
);
3778 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3779 else if (ar
->ProbeCount
)
3781 if (ar
->AddressProxy
.type
== mDNSAddrType_IPv4
)
3783 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3784 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3785 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3786 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3787 // A similar concern may apply to the NDP Probe too. -- SC
3788 LogSPS("SendQueries ARP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3789 SendARP(m
, 1, ar
, &zerov4Addr
, &zeroEthAddr
, &ar
->AddressProxy
.ip
.v4
, &ar
->WakeUp
.IMAC
);
3791 else if (ar
->AddressProxy
.type
== mDNSAddrType_IPv6
)
3793 LogSPS("SendQueries NDP Probe %d %s %s", ar
->ProbeCount
, InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), ARDisplayString(m
,ar
));
3794 // IPv6 source = zero
3795 // No target hardware address
3796 // IPv6 target address is address we're probing
3797 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3798 SendNDP(m
, NDP_Sol
, 0, ar
, &zerov6Addr
, mDNSNULL
, &ar
->AddressProxy
.ip
.v6
, &ar
->WakeUp
.IMAC
);
3800 // Mark for sending. (If no active interfaces, then don't even try.)
3801 ar
->SendRNow
= (!intf
|| ar
->WakeUp
.HMAC
.l
[0]) ? mDNSNULL
: ar
->resrec
.InterfaceID
? ar
->resrec
.InterfaceID
: intf
->InterfaceID
;
3802 ar
->LastAPTime
= m
->timenow
;
3803 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3804 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3805 if (ar
->ProbeCount
> DefaultProbeCountForTypeUnique
)
3806 ar
->ProbeCount
= DefaultProbeCountForTypeUnique
;
3808 SetNextAnnounceProbeTime(m
, ar
);
3809 if (ar
->ProbeCount
== 0)
3811 // If this is the last probe for this record, then see if we have any matching records
3812 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3814 for (r2
= m
->DuplicateRecords
; r2
; r2
=r2
->next
)
3815 if (r2
->resrec
.RecordType
== kDNSRecordTypeUnique
&& RecordIsLocalDuplicate(r2
, ar
))
3817 // ... then acknowledge this record to the client.
3818 // We do this optimistically, just as we're about to send the third probe.
3819 // This helps clients that both advertise and browse, and want to filter themselves
3820 // from the browse results list, because it helps ensure that the registration
3821 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3822 // A potential downside is that we could deliver a registration confirmation and then find out
3823 // moments later that there's a name conflict, but applications have to be prepared to handle
3824 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3825 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
);
3828 // else, if it has now finished probing, move it to state Verified,
3829 // and update m->NextScheduledResponse so it will be announced
3832 if (!ar
->Acknowledged
) AcknowledgeRecord(m
, ar
); // Defensive, just in case it got missed somehow
3833 ar
->resrec
.RecordType
= kDNSRecordTypeVerified
;
3834 ar
->ThisAPInterval
= DefaultAnnounceIntervalForTypeUnique
;
3835 ar
->LastAPTime
= m
->timenow
- DefaultAnnounceIntervalForTypeUnique
;
3836 SetNextAnnounceProbeTime(m
, ar
);
3840 m
->CurrentRecord
= m
->DuplicateRecords
;
3841 while (m
->CurrentRecord
)
3843 ar
= m
->CurrentRecord
;
3844 m
->CurrentRecord
= ar
->next
;
3845 if (ar
->resrec
.RecordType
== kDNSRecordTypeUnique
&& ar
->ProbeCount
== 0 && !ar
->Acknowledged
)
3846 AcknowledgeRecord(m
, ar
);
3849 // 3. Now we know which queries and probes we're sending,
3850 // go through our interface list sending the appropriate queries on each interface
3853 int OwnerRecordSpace
= (m
->AnnounceOwner
&& intf
->MAC
.l
[0]) ? DNSOpt_Header_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
) : 0;
3854 int TraceRecordSpace
= (mDNS_McastTracingEnabled
&& MDNS_TRACER
) ? DNSOpt_Header_Space
+ DNSOpt_TraceData_Space
: 0;
3855 mDNSu8
*queryptr
= m
->omsg
.data
;
3856 mDNSBool useBackgroundTrafficClass
= mDNSfalse
; // set if we should use background traffic class
3858 InitializeDNSMessage(&m
->omsg
.h
, zeroID
, QueryFlags
);
3859 if (KnownAnswerList
) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3860 if (!KnownAnswerList
)
3862 // Start a new known-answer list
3863 CacheRecord
**kalistptr
= &KnownAnswerList
;
3864 mDNSu32 answerforecast
= OwnerRecordSpace
+ TraceRecordSpace
; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3866 // Put query questions in this packet
3867 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
3869 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->SendQNow
== intf
->InterfaceID
))
3871 mDNSBool Suppress
= mDNSfalse
;
3872 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3873 SuppressOnThisInterface(q
->DupSuppress
, intf
) ? "Suppressing" : "Putting ",
3874 q
->qname
.c
, DNSTypeName(q
->qtype
), queryptr
- m
->omsg
.data
, queryptr
+ answerforecast
- m
->omsg
.data
);
3876 // If interface is P2P type, verify that query should be sent over it.
3877 if (!mDNSPlatformValidQuestionForInterface(q
, intf
))
3879 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3881 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3882 else if ((Suppress
= SuppressOnThisInterface(q
->DupSuppress
, intf
)) ||
3883 BuildQuestion(m
, intf
, &m
->omsg
, &queryptr
, q
, &kalistptr
, &answerforecast
))
3886 m
->mDNSStats
.DupQuerySuppressions
++;
3888 q
->SendQNow
= (q
->InterfaceID
|| !q
->SendOnAll
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3889 if (q
->WakeOnResolveCount
)
3891 mDNSSendWakeOnResolve(m
, q
);
3892 q
->WakeOnResolveCount
--;
3895 // use background traffic class if any included question requires it
3896 if (q
->UseBackgroundTraffic
)
3898 useBackgroundTrafficClass
= mDNStrue
;
3904 // Put probe questions in this packet
3905 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3907 if (ar
->SendRNow
!= intf
->InterfaceID
)
3910 // If interface is a P2P variant, verify that the probe should be sent over it.
3911 if (!mDNSPlatformValidRecordForInterface(ar
, intf
->InterfaceID
))
3913 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3914 ar
->IncludeInProbe
= mDNSfalse
;
3918 mDNSBool ucast
= (ar
->ProbeCount
>= DefaultProbeCountForTypeUnique
-1) && m
->CanReceiveUnicastOn5353
&& intf
->SupportsUnicastMDNSResponse
;
3919 mDNSu16 ucbit
= (mDNSu16
)(ucast
? kDNSQClass_UnicastResponse
: 0);
3920 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.numQuestions
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
);
3921 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3922 mDNSu32 forecast
= answerforecast
+ 12 + ar
->resrec
.rdestimate
;
3923 mDNSBool putProbe
= mDNStrue
;
3924 mDNSu16 qclass
= ar
->resrec
.rrclass
| ucbit
;
3926 {// Determine if this probe question is already in packet's dns message
3927 const mDNSu8
*questionptr
= m
->omsg
.data
;
3928 DNSQuestion question
;
3930 for (n
= 0; n
< m
->omsg
.h
.numQuestions
&& questionptr
; n
++)
3932 questionptr
= getQuestion(&m
->omsg
, questionptr
, limit
, mDNSInterface_Any
, &question
);
3933 if (questionptr
&& (question
.qtype
== kDNSQType_ANY
) && (question
.qclass
== qclass
) &&
3934 (question
.qnamehash
== ar
->resrec
.namehash
) && SameDomainName(&question
.qname
, ar
->resrec
.name
))
3936 putProbe
= mDNSfalse
; // set to false if already in message
3944 mDNSu8
*newptr
= putQuestion(&m
->omsg
, queryptr
, limit
- forecast
, ar
->resrec
.name
, kDNSQType_ANY
, qclass
);
3948 answerforecast
= forecast
;
3949 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3950 ar
->IncludeInProbe
= mDNStrue
;
3951 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3952 ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
), ar
->ProbeCount
, ar
->resrec
.InterfaceID
, ar
->resrec
.rdestimate
, answerforecast
);
3957 ar
->SendRNow
= (ar
->resrec
.InterfaceID
) ? mDNSNULL
: GetNextActiveInterfaceID(intf
);
3958 ar
->IncludeInProbe
= mDNStrue
;
3964 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3965 while (KnownAnswerList
)
3967 CacheRecord
*ka
= KnownAnswerList
;
3968 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- ka
->TimeRcvd
)) / mDNSPlatformOneSecond
;
3969 mDNSu8
*newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAnswers
, &ka
->resrec
, ka
->resrec
.rroriginalttl
- SecsSinceRcvd
,
3970 m
->omsg
.data
+ NormalMaxDNSMessageData
- OwnerRecordSpace
- TraceRecordSpace
);
3973 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3974 ka
->resrec
.name
->c
, DNSTypeName(ka
->resrec
.rrtype
), queryptr
- m
->omsg
.data
, newptr
- m
->omsg
.data
);
3976 KnownAnswerList
= ka
->NextInKAList
;
3977 ka
->NextInKAList
= mDNSNULL
;
3981 // If we ran out of space and we have more than one question in the packet, that's an error --
3982 // we shouldn't have put more than one question if there was a risk of us running out of space.
3983 if (m
->omsg
.h
.numQuestions
> 1)
3984 LogMsg("SendQueries: Put %d answers; No more space for known answers", m
->omsg
.h
.numAnswers
);
3985 m
->omsg
.h
.flags
.b
[0] |= kDNSFlag0_TC
;
3990 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
3992 if (ar
->IncludeInProbe
)
3994 mDNSu8
*newptr
= PutResourceRecord(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAuthorities
, &ar
->resrec
);
3995 ar
->IncludeInProbe
= mDNSfalse
;
3996 if (newptr
) queryptr
= newptr
;
3997 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m
,ar
));
4001 if (queryptr
> m
->omsg
.data
)
4003 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
4004 if (OwnerRecordSpace
|| TraceRecordSpace
)
4007 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
4008 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
4009 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
4010 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
4011 if (OwnerRecordSpace
&& TraceRecordSpace
)
4013 opt
.resrec
.rdlength
+= sizeof(rdataOPT
); // Two options in this OPT record
4014 opt
.resrec
.rdestimate
+= sizeof(rdataOPT
);
4015 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
4016 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[1]);
4018 else if (OwnerRecordSpace
)
4020 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
4022 else if (TraceRecordSpace
)
4024 SetupTracerOpt(m
, &opt
.resrec
.rdata
->u
.opt
[0]);
4026 queryptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, queryptr
, &m
->omsg
.h
.numAdditionals
,
4027 &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
4030 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "", TraceRecordSpace
? "TRACER" : "",
4031 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
4033 if (queryptr
> m
->omsg
.data
+ NormalMaxDNSMessageData
)
4035 if (m
->omsg
.h
.numQuestions
!= 1 || m
->omsg
.h
.numAnswers
!= 0 || m
->omsg
.h
.numAuthorities
!= 1 || m
->omsg
.h
.numAdditionals
!= 1)
4036 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace
? "OWNER" : "",
4037 TraceRecordSpace
? "TRACER" : "", m
->omsg
.data
, m
->omsg
.data
+ NormalMaxDNSMessageData
, queryptr
, m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numAnswers
,
4038 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAdditionals
, ARDisplayString(m
, &opt
));
4042 if ((m
->omsg
.h
.flags
.b
[0] & kDNSFlag0_TC
) && m
->omsg
.h
.numQuestions
> 1)
4043 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m
->omsg
.h
.numQuestions
);
4044 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4045 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
4046 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
4047 m
->omsg
.h
.numAuthorities
, m
->omsg
.h
.numAuthorities
== 1 ? "" : "s", IIDPrintable(intf
->InterfaceID
), intf
->ifname
);
4048 if (intf
->IPv4Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v4
, MulticastDNSPort
, mDNSNULL
, useBackgroundTrafficClass
);
4049 if (intf
->IPv6Available
) mDNSSendDNSMessage(m
, &m
->omsg
, queryptr
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &AllDNSLinkGroup_v6
, MulticastDNSPort
, mDNSNULL
, useBackgroundTrafficClass
);
4050 if (!m
->SuppressSending
) m
->SuppressSending
= NonZeroTime(m
->timenow
+ (mDNSPlatformOneSecond
+9)/10);
4051 if (++pktcount
>= 1000)
4052 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount
); break; }
4053 // There might be more records left in the known answer list, or more questions to send
4054 // on this interface, so go around one more time and try again.
4056 else // Nothing more to send on this interface; go to next
4058 const NetworkInterfaceInfo
*next
= GetFirstActiveInterface(intf
->next
);
4059 #if MDNS_DEBUGMSGS && 0
4060 const char *const msg
= next
? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4061 debugf(msg
, intf
, next
);
4067 // 4. Final housekeeping
4069 // 4a. Debugging check: Make sure we announced all our records
4070 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
4073 if (ar
->ARType
!= AuthRecordLocalOnly
&& ar
->ARType
!= AuthRecordP2P
)
4074 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4075 IIDPrintable(ar
->SendRNow
), IIDPrintable(ar
->resrec
.InterfaceID
), ARDisplayString(m
, ar
));
4076 ar
->SendRNow
= mDNSNULL
;
4079 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4080 // that their interface which went away might come back again, the logic will want to send queries
4081 // for those records, but we can't because their interface isn't here any more, so to keep the
4082 // state machine ticking over we just pretend we did so.
4083 // If the interface does not come back in time, the cache record will expire naturally
4084 FORALL_CACHERECORDS(slot
, cg
, cr
)
4086 if (cr
->CRActiveQuestion
&& cr
->UnansweredQueries
< MaxUnansweredQueries
)
4088 if (m
->timenow
+ TicksTTL(cr
)/50 - cr
->NextRequiredQuery
>= 0)
4090 cr
->UnansweredQueries
++;
4091 cr
->CRActiveQuestion
->SendQNow
= mDNSNULL
;
4092 SetNextCacheCheckTimeForRecord(m
, cr
);
4097 // 4c. Debugging check: Make sure we sent all our planned questions
4098 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4099 // we legitimately couldn't send because the interface is no longer available
4100 for (q
= m
->Questions
; q
; q
=q
->next
)
4105 for (x
= m
->NewQuestions
; x
; x
=x
->next
) if (x
== q
) break; // Check if this question is a NewQuestion
4106 // There will not be an active interface for questions applied to mDNSInterface_BLE
4107 // so don't log the warning in that case.
4108 if (q
->InterfaceID
!= mDNSInterface_BLE
)
4109 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4110 IIDPrintable(q
->SendQNow
), x
? "new" : "old", IIDPrintable(q
->InterfaceID
), q
->qname
.c
, DNSTypeName(q
->qtype
));
4111 q
->SendQNow
= mDNSNULL
;
4113 q
->CachedAnswerNeedsUpdate
= mDNSfalse
;
4117 mDNSlocal
void SendWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*EthAddr
, mDNSOpaque48
*password
, mDNSBool unicastOnly
)
4121 mDNSu8
*ptr
= m
->omsg
.data
;
4122 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
4123 if (!intf
) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID
); return; }
4125 // 0x00 Destination address
4126 for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4128 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4129 for (i
=0; i
<6; i
++) *ptr
++ = intf
->MAC
.b
[0];
4131 // 0x0C Ethertype (0x0842)
4135 // 0x0E Wakeup sync sequence
4136 for (i
=0; i
<6; i
++) *ptr
++ = 0xFF;
4139 for (j
=0; j
<16; j
++) for (i
=0; i
<6; i
++) *ptr
++ = EthAddr
->b
[i
];
4142 for (i
=0; i
<6; i
++) *ptr
++ = password
->b
[i
];
4144 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4148 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4149 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4150 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4151 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4152 // So, we send one of each, unicast first, then broadcast second.
4153 for (i
=0; i
<6; i
++) m
->omsg
.data
[i
] = 0xFF;
4154 mDNSPlatformSendRawPacket(m
->omsg
.data
, ptr
, InterfaceID
);
4158 // ***************************************************************************
4159 #if COMPILER_LIKES_PRAGMA_MARK
4161 #pragma mark - RR List Management & Task Management
4164 // Whenever a question is answered, reset its state so that we don't query
4165 // the network repeatedly. This happens first time when we answer the question and
4166 // and later when we refresh the cache.
4167 mDNSlocal
void ResetQuestionState(mDNS
*const m
, DNSQuestion
*q
)
4169 q
->LastQTime
= m
->timenow
;
4170 q
->LastQTxTime
= m
->timenow
;
4171 q
->RecentAnswerPkts
= 0;
4172 q
->ThisQInterval
= MaxQuestionInterval
;
4173 q
->RequestUnicast
= 0;
4174 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4175 // Reset unansweredQueries so that we don't penalize this server later when we
4176 // start sending queries when the cache expires.
4177 q
->unansweredQueries
= 0;
4179 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4182 mDNSlocal
void AdjustUnansweredQueries(mDNS
*const m
, CacheRecord
*const rr
)
4184 const mDNSs32 expireTime
= RRExpireTime(rr
);
4185 const mDNSu32 interval
= TicksTTL(rr
) / 20; // Calculate 5% of the cache record's TTL.
4188 // If the record is expired or UnansweredQueries is already at the max, then return early.
4189 if (((m
->timenow
- expireTime
) >= 0) || (rr
->UnansweredQueries
>= MaxUnansweredQueries
)) return;
4193 LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr
), CRDisplayString(m
, rr
));
4197 // Calculate the number of whole 5% TTL intervals between now and expiration time.
4198 rem
= ((mDNSu32
)(expireTime
- m
->timenow
)) / interval
;
4200 // Calculate the expected number of remaining refresher queries.
4201 // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4202 if (rem
> MaxUnansweredQueries
) rem
= MaxUnansweredQueries
;
4204 // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4205 // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4206 // refresher queries would have been sent if the cache record did have an active question. The cache record's
4207 // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4208 // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4209 // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4210 // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4211 // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4212 // Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4213 if ((MaxUnansweredQueries
- rr
->UnansweredQueries
) > (mDNSs32
)rem
)
4215 if (rem
== 0) rem
++;
4216 rr
->UnansweredQueries
= (mDNSu8
)(MaxUnansweredQueries
- rem
);
4220 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4221 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4222 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4223 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4224 mDNSexport
void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
)
4226 DNSQuestion
*const q
= m
->CurrentQuestion
;
4227 const mDNSBool followcname
= FollowCNAME(q
, &rr
->resrec
, AddRecord
);
4229 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4230 q
->CurrentAnswers
, AddRecord
? "Add" : "Rmv", MortalityDisplayString(rr
->resrec
.mortality
),
4231 rr
->resrec
.rroriginalttl
, CRDisplayString(m
, rr
));
4233 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4234 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4235 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4236 // we check to see if that query already has a unique local answer.
4237 if (q
->LOAddressAnswers
)
4239 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4240 "LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
),
4241 q
->LOAddressAnswers
);
4245 if (q
->Suppressed
&& (AddRecord
!= QC_suppressed
))
4247 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4248 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4249 // that are timing out, which we know are answered with negative cache record when timing out.
4250 if (!q
->TimeoutQuestion
|| rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
|| (m
->timenow
- q
->StopTime
< 0))
4254 // Set the record to immortal if appropriate
4255 if (AddRecord
== QC_add
&& Question_uDNS(q
) && rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&&
4256 q
->allowExpired
!= AllowExpired_None
&& rr
->resrec
.mortality
== Mortality_Mortal
) rr
->resrec
.mortality
= Mortality_Immortal
; // Update a non-expired cache record to immortal if appropriate
4258 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4259 if ((AddRecord
== QC_add
) && Question_uDNS(q
) && !followcname
&& !q
->metrics
.answered
)
4261 mDNSBool skipUpdate
= mDNSfalse
;
4262 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4263 if (!q
->dnsservice
|| (mdns_dns_service_get_resolver_type(q
->dnsservice
) != mdns_resolver_type_normal
))
4265 skipUpdate
= mDNStrue
;
4270 const domainname
* queryName
;
4271 mDNSu32 responseLatencyMs
, querySendCount
;
4272 mDNSBool isForCellular
;
4274 queryName
= q
->metrics
.originalQName
? q
->metrics
.originalQName
: &q
->qname
;
4275 querySendCount
= q
->metrics
.querySendCount
;
4276 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4279 querySendCount
+= mdns_querier_get_send_count(q
->querier
);
4281 isForCellular
= mdns_dns_service_interface_is_cellular(q
->dnsservice
);
4283 isForCellular
= (q
->qDNSServer
&& q
->qDNSServer
->isCell
);
4285 if (q
->metrics
.querySendCount
> 0)
4287 responseLatencyMs
= ((m
->timenow
- q
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
4291 responseLatencyMs
= 0;
4293 MetricsUpdateDNSQueryStats(queryName
, q
->qtype
, &rr
->resrec
, querySendCount
, q
->metrics
.expiredAnswerState
,
4294 q
->metrics
.dnsOverTCPState
, responseLatencyMs
, isForCellular
);
4296 q
->metrics
.answered
= mDNStrue
;
4299 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4300 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4301 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4303 if (AddRecord
== QC_add
&& !q
->DuplicateOf
&& rr
->CRActiveQuestion
!= q
&& rr
->resrec
.mortality
!= Mortality_Ghost
)
4305 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4306 rr
->CRActiveQuestion
, q
, CRDisplayString(m
,rr
), q
->CurrentAnswers
);
4307 if (!rr
->CRActiveQuestion
)
4309 m
->rrcache_active
++; // If not previously active, increment rrcache_active count
4310 AdjustUnansweredQueries(m
, rr
); // Adjust UnansweredQueries in case the record missed out on refresher queries
4312 rr
->CRActiveQuestion
= q
; // We know q is non-null
4313 SetNextCacheCheckTimeForRecord(m
, rr
);
4317 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4318 // (b) a normal add, where we have at least one unique-type answer,
4319 // then there's no need to keep polling the network.
4320 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4321 // We do this for mDNS questions and uDNS one-shot questions, but not for
4322 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4323 if ((AddRecord
== QC_addnocache
&& !q
->RequestUnicast
) ||
4324 (AddRecord
== QC_add
&& (q
->ExpectUnique
|| (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))))
4325 if (ActiveQuestion(q
) && (mDNSOpaque16IsZero(q
->TargetQID
) || !q
->LongLived
))
4327 ResetQuestionState(m
, q
);
4330 if (rr
->DelayDelivery
) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4332 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4333 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4334 if (!mDNSOpaque16IsZero(q
->TargetQID
) && DNS64StateMachine(m
, q
, &rr
->resrec
, AddRecord
)) return;
4338 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) // If negative answer, check if we need to try Punycode conversion
4341 if (PerformNextPunycodeConversion(q
, &newname
)) // Itertative Punycode conversion succeeded, so reissue question with new name
4343 UDPSocket
*const sock
= q
->LocalSocket
; // Save old socket and transaction ID
4344 const mDNSOpaque16 id
= q
->TargetQID
;
4345 q
->LocalSocket
= mDNSNULL
;
4346 mDNS_StopQuery_internal(m
, q
); // Stop old query
4347 AssignDomainName(&q
->qname
, &newname
); // Update qname
4348 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
4349 mDNS_StartQuery_internal(m
, q
); // Start new query
4351 if (sock
) // Transplant saved socket, if appropriate
4353 if (q
->DuplicateOf
) mDNSPlatformUDPClose(sock
);
4354 else { q
->LocalSocket
= sock
; q
->TargetQID
= id
; }
4356 return; // All done for now; wait until we get the next answer
4359 #endif // USE_LIBIDN
4361 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4362 // for the purpose of retrying search domains/timeout OR the question is suppressed
4363 if (rr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
|| (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
)))
4364 if (!AddRecord
|| (AddRecord
!= QC_suppressed
&& AddRecord
!= QC_forceresponse
&& !q
->ReturnIntermed
)) return;
4366 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4367 if (q
->QuestionCallback
&& !q
->NoAnswer
&& (!followcname
|| q
->ReturnIntermed
))
4369 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4370 if (q
->qtype
!= kDNSType_NSEC
&& RRAssertsNonexistence(&rr
->resrec
, q
->qtype
))
4372 if (mDNSOpaque16IsZero(q
->TargetQID
))
4375 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4376 mDNSPlatformMemZero(&neg
, sizeof(neg
));
4377 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->dnsservice
);
4379 MakeNegativeCacheRecord(m
, &neg
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 1, rr
->resrec
.InterfaceID
, q
->qDNSServer
);
4381 q
->QuestionCallback(m
, q
, &neg
.resrec
, AddRecord
);
4386 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4387 if (DNS64ShouldAnswerQuestion(q
, &rr
->resrec
))
4389 DNS64AnswerCurrentQuestion(m
, &rr
->resrec
, AddRecord
);
4394 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4395 get_denial_records_from_negative_cache_to_dnssec_context(q
->DNSSECStatus
.enable_dnssec
,
4396 q
->DNSSECStatus
.context
, rr
);
4397 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4398 q
->QuestionCallback(m
, q
, &rr
->resrec
, AddRecord
);
4401 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4403 // Note: Proceed with caution after this point because client callback function
4404 // invoked above is allowed to do anything, such as starting/stopping queries
4405 // (including this one itself, or the next or previous query in the linked list),
4406 // registering/deregistering records, starting/stopping NAT traversals, etc.
4408 if (m
->CurrentQuestion
== q
)
4410 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4411 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4412 // first before following it
4413 if (followcname
) AnswerQuestionByFollowingCNAME(m
, q
, &rr
->resrec
);
4415 // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4416 if (rr
->resrec
.mortality
== Mortality_Ghost
&& !q
->firstExpiredQname
.c
[0] && (q
->allowExpired
== AllowExpired_AllowExpiredAnswers
) && rr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
4418 debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m
,rr
), q
);
4419 // Note: question->qname is already changed at this point if following a CNAME
4420 AssignDomainName(&q
->firstExpiredQname
, rr
->resrec
.name
); // Update firstExpiredQname
4425 mDNSlocal
void CacheRecordDeferredAdd(mDNS
*const m
, CacheRecord
*cr
)
4427 cr
->DelayDelivery
= 0;
4428 if (m
->CurrentQuestion
)
4429 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4430 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4431 m
->CurrentQuestion
= m
->Questions
;
4432 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4434 DNSQuestion
*q
= m
->CurrentQuestion
;
4435 if (CacheRecordAnswersQuestion(cr
, q
))
4436 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
4437 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4438 m
->CurrentQuestion
= q
->next
;
4440 m
->CurrentQuestion
= mDNSNULL
;
4443 mDNSlocal mDNSs32
CheckForSoonToExpireRecords(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
)
4445 const mDNSs32 threshold
= m
->timenow
+ mDNSPlatformOneSecond
; // See if there are any records expiring within one second
4446 const mDNSs32 start
= m
->timenow
- 0x10000000;
4447 mDNSs32 delay
= start
;
4448 CacheGroup
*cg
= CacheGroupForName(m
, namehash
, name
);
4449 const CacheRecord
*rr
;
4451 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
4453 if (threshold
- RRExpireTime(rr
) >= 0) // If we have records about to expire within a second
4455 if (delay
- RRExpireTime(rr
) < 0) // then delay until after they've been deleted
4456 delay
= RRExpireTime(rr
);
4459 if (delay
- start
> 0)
4460 return(NonZeroTime(delay
));
4465 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4466 // If new questions are created as a result of invoking client callbacks, they will be added to
4467 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4468 // rr is a new CacheRecord just received into our cache
4469 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4470 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4471 // which may change the record list and/or question list.
4472 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4473 mDNSlocal
void CacheRecordAdd(mDNS
*const m
, CacheRecord
*cr
)
4477 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4478 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4479 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
4481 if (CacheRecordAnswersQuestion(cr
, q
))
4483 // If this question is one that's actively sending queries, and it's received ten answers within one
4484 // second of sending the last query packet, then that indicates some radical network topology change,
4485 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4486 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4487 // because we will anyway send another query within a few seconds. The first reset query is sent out
4488 // randomized over the next four seconds to reduce possible synchronization between machines.
4489 if (q
->LastAnswerPktNum
!= m
->PktNum
)
4491 q
->LastAnswerPktNum
= m
->PktNum
;
4492 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
) && ++q
->RecentAnswerPkts
>= 10 &&
4493 q
->ThisQInterval
> InitialQuestionInterval
* QuestionIntervalStep3
&& m
->timenow
- q
->LastQTxTime
< mDNSPlatformOneSecond
)
4495 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4496 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->RecentAnswerPkts
, q
->ThisQInterval
);
4497 q
->LastQTime
= m
->timenow
- InitialQuestionInterval
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*4);
4498 q
->ThisQInterval
= InitialQuestionInterval
;
4499 SetNextQueryTime(m
,q
);
4502 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr
, cr
->resrec
.name
->c
,
4503 DNSTypeName(cr
->resrec
.rrtype
), cr
->resrec
.rroriginalttl
, cr
->resrec
.rDNSServer
?
4504 &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
, mDNSVal16(cr
->resrec
.rDNSServer
?
4505 cr
->resrec
.rDNSServer
->port
: zeroIPPort
), q
);
4506 q
->CurrentAnswers
++;
4508 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4509 q
->unansweredQueries
= 0;
4511 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
4512 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
4513 if (q
->CurrentAnswers
> 4000)
4515 static int msgcount
= 0;
4516 if (msgcount
++ < 10)
4517 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4518 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->CurrentAnswers
);
4519 cr
->resrec
.rroriginalttl
= 0;
4520 cr
->UnansweredQueries
= MaxUnansweredQueries
;
4525 if (!cr
->DelayDelivery
)
4527 if (m
->CurrentQuestion
)
4528 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4529 m
->CurrentQuestion
= m
->Questions
;
4530 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4532 q
= m
->CurrentQuestion
;
4533 if (CacheRecordAnswersQuestion(cr
, q
))
4534 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
4535 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4536 m
->CurrentQuestion
= q
->next
;
4538 m
->CurrentQuestion
= mDNSNULL
;
4541 SetNextCacheCheckTimeForRecord(m
, cr
);
4544 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4545 // If new questions are created as a result of invoking client callbacks, they will be added to
4546 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4547 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4548 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4549 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4550 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4551 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4552 // which may change the record list and/or question list.
4553 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4554 mDNSlocal
void NoCacheAnswer(mDNS
*const m
, CacheRecord
*cr
)
4556 LogMsg("No cache space: Delivering non-cached result for %##s", m
->rec
.r
.resrec
.name
->c
);
4557 if (m
->CurrentQuestion
)
4558 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4559 m
->CurrentQuestion
= m
->Questions
;
4560 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4561 // since we're not caching the record and we'll get no opportunity to do this later
4562 while (m
->CurrentQuestion
)
4564 DNSQuestion
*q
= m
->CurrentQuestion
;
4565 if (CacheRecordAnswersQuestion(cr
, q
))
4566 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_addnocache
); // QC_addnocache means "don't expect remove events for this"
4567 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4568 m
->CurrentQuestion
= q
->next
;
4570 m
->CurrentQuestion
= mDNSNULL
;
4573 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4574 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4575 // If new questions are created as a result of invoking client callbacks, they will be added to
4576 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4577 // cr is an existing cache CacheRecord that just expired and is being deleted
4578 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4579 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4580 // which may change the record list and/or question list.
4581 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4582 mDNSlocal
void CacheRecordRmv(mDNS
*const m
, CacheRecord
*cr
)
4584 if (m
->CurrentQuestion
)
4585 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4586 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
4587 m
->CurrentQuestion
= m
->Questions
;
4589 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4590 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4591 while (m
->CurrentQuestion
&& m
->CurrentQuestion
!= m
->NewQuestions
)
4593 DNSQuestion
*q
= m
->CurrentQuestion
;
4594 // When a question enters suppressed state, we generate RMV events and generate a negative
4595 // response. A cache may be present that answers this question e.g., cache entry generated
4596 // before the question became suppressed. We need to skip the suppressed questions here as
4597 // the RMV event has already been generated.
4598 if (!q
->Suppressed
&& CacheRecordAnswersQuestion(cr
, q
) &&
4599 (q
->allowExpired
== AllowExpired_None
|| cr
->resrec
.mortality
== Mortality_Mortal
))
4601 verbosedebugf("CacheRecordRmv %p %s", cr
, CRDisplayString(m
, cr
));
4602 q
->FlappingInterface1
= mDNSNULL
;
4603 q
->FlappingInterface2
= mDNSNULL
;
4605 if (q
->CurrentAnswers
== 0)
4607 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4608 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4609 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->qDNSServer
? &q
->qDNSServer
->addr
: mDNSNULL
,
4610 mDNSVal16(q
->qDNSServer
? q
->qDNSServer
->port
: zeroIPPort
));
4615 q
->CurrentAnswers
--;
4616 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
4617 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
4620 // If we have dropped below the answer threshold for this mDNS question,
4621 // restart the queries at InitialQuestionInterval.
4622 if (mDNSOpaque16IsZero(q
->TargetQID
) && (q
->BrowseThreshold
> 0) && (q
->CurrentAnswers
< q
->BrowseThreshold
))
4624 q
->ThisQInterval
= InitialQuestionInterval
;
4625 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4626 SetNextQueryTime(m
,q
);
4627 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4628 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->BrowseThreshold
);
4630 if (cr
->resrec
.rdata
->MaxRDLength
) // Never generate "remove" events for negative results
4632 if ((q
->CurrentAnswers
== 0) && mDNSOpaque16IsZero(q
->TargetQID
))
4634 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4635 q
->qname
.c
, DNSTypeName(q
->qtype
));
4636 ReconfirmAntecedents(m
, &q
->qname
, q
->qnamehash
, cr
->resrec
.InterfaceID
, 0);
4638 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_rmv
);
4641 if (m
->CurrentQuestion
== q
) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4642 m
->CurrentQuestion
= q
->next
;
4644 m
->CurrentQuestion
= mDNSNULL
;
4647 mDNSlocal
void ReleaseCacheEntity(mDNS
*const m
, CacheEntity
*e
)
4649 #if MDNS_MALLOC_DEBUGGING >= 1
4651 for (i
=0; i
<sizeof(*e
); i
++) ((char*)e
)[i
] = 0xFF;
4653 e
->next
= m
->rrcache_free
;
4654 m
->rrcache_free
= e
;
4655 m
->rrcache_totalused
--;
4658 mDNSlocal
void ReleaseCacheGroup(mDNS
*const m
, CacheGroup
**cp
)
4660 CacheEntity
*e
= (CacheEntity
*)(*cp
);
4661 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4662 if ((*cp
)->rrcache_tail
!= &(*cp
)->members
)
4663 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4664 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4665 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4666 if ((*cp
)->name
!= (domainname
*)((*cp
)->namestorage
)) mDNSPlatformMemFree((*cp
)->name
);
4667 (*cp
)->name
= mDNSNULL
;
4668 *cp
= (*cp
)->next
; // Cut record from list
4669 ReleaseCacheEntity(m
, e
);
4672 mDNSlocal
void ReleaseAdditionalCacheRecords(mDNS
*const m
, CacheRecord
**rp
)
4676 CacheRecord
*rr
= *rp
;
4677 *rp
= (*rp
)->next
; // Cut record from list
4678 if (rr
->resrec
.rdata
&& rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
)
4680 mDNSPlatformMemFree(rr
->resrec
.rdata
);
4681 rr
->resrec
.rdata
= mDNSNULL
;
4683 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4684 // of the CacheGroup.
4685 if (rr
->resrec
.name
)
4687 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
));
4688 mDNSPlatformMemFree((void *)rr
->resrec
.name
);
4689 rr
->resrec
.name
= mDNSNULL
;
4691 // Don't count the NSEC3 records used by anonymous browse/reg
4692 if (!rr
->resrec
.InterfaceID
)
4694 m
->rrcache_totalused_unicast
-= rr
->resrec
.rdlength
;
4696 ReleaseCacheEntity(m
, (CacheEntity
*)rr
);
4700 mDNSexport
void ReleaseCacheRecord(mDNS
*const m
, CacheRecord
*r
)
4704 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4705 if (r
->resrec
.rdata
&& r
->resrec
.rdata
!= (RData
*)&r
->smallrdatastorage
) mDNSPlatformMemFree(r
->resrec
.rdata
);
4706 r
->resrec
.rdata
= mDNSNULL
;
4707 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4708 mdns_forget(&r
->resrec
.dnsservice
);
4711 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4712 release_denial_records_in_cache_record(r
);
4715 cg
= CacheGroupForRecord(m
, &r
->resrec
);
4719 // It is okay to have this printed for NSEC/NSEC3s
4720 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4722 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4723 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4724 // (which is handled below) and in that case it should be freed here.
4725 if (r
->resrec
.name
&& cg
&& r
->resrec
.name
!= cg
->name
)
4727 debugf("ReleaseCacheRecord: freeing %##s (%s)", r
->resrec
.name
->c
, DNSTypeName(r
->resrec
.rrtype
));
4728 mDNSPlatformMemFree((void *)r
->resrec
.name
);
4730 r
->resrec
.name
= mDNSNULL
;
4732 if (!r
->resrec
.InterfaceID
)
4734 m
->rrcache_totalused_unicast
-= r
->resrec
.rdlength
;
4737 ReleaseAdditionalCacheRecords(m
, &r
->soa
);
4739 ReleaseCacheEntity(m
, (CacheEntity
*)r
);
4742 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4743 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4744 // callbacks for old records are delivered before callbacks for newer records.
4745 mDNSlocal
void CheckCacheExpiration(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*const cg
)
4747 CacheRecord
**rp
= &cg
->members
;
4749 if (m
->lock_rrcache
) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4750 m
->lock_rrcache
= 1;
4754 CacheRecord
*const rr
= *rp
;
4755 mDNSBool recordReleased
= mDNSfalse
;
4756 mDNSs32 event
= RRExpireTime(rr
);
4757 if (m
->timenow
- event
>= 0) // If expired, delete it
4759 if (rr
->CRActiveQuestion
) // If this record has one or more active questions, tell them it's going away
4761 DNSQuestion
*q
= rr
->CRActiveQuestion
;
4762 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4763 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4764 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4765 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4766 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4767 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4768 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4769 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4770 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4771 if (((mDNSOpaque16IsZero(q
->TargetQID
) && (rr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)) ||
4772 (!mDNSOpaque16IsZero(q
->TargetQID
) && !q
->LongLived
)) && ActiveQuestion(q
))
4774 q
->ThisQInterval
= InitialQuestionInterval
;
4775 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
4776 SetNextQueryTime(m
, q
);
4778 CacheRecordRmv(m
, rr
);
4779 m
->rrcache_active
--;
4782 event
+= MAX_GHOST_TIME
; // Adjust so we can check for a ghost expiration
4783 if (rr
->resrec
.mortality
== Mortality_Mortal
|| // Normal expired mortal record that needs released
4784 rr
->resrec
.rroriginalttl
== 0 || // Non-mortal record that is set to be purged
4785 (rr
->resrec
.mortality
== Mortality_Ghost
&& m
->timenow
- event
>= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago
4786 { // Release as normal
4787 *rp
= rr
->next
; // Cut it from the list before ReleaseCacheRecord
4788 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4789 MortalityDisplayString(rr
->resrec
.mortality
),
4790 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4791 ReleaseCacheRecord(m
, rr
);
4792 recordReleased
= mDNStrue
;
4794 else // An immortal record needs to become a ghost when it expires
4795 { // Don't release this entry
4796 if (rr
->resrec
.mortality
== Mortality_Immortal
)
4798 rr
->resrec
.mortality
= Mortality_Ghost
; // Expired immortal records become ghosts
4799 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4800 MortalityDisplayString(rr
->resrec
.mortality
),
4801 m
->timenow
- rr
->TimeRcvd
, rr
->resrec
.rroriginalttl
, rr
->CRActiveQuestion
, CRDisplayString(m
, rr
));
4805 else // else, not expired; see if we need to query
4807 // If waiting to delay delivery, do nothing until then
4808 if (rr
->DelayDelivery
&& rr
->DelayDelivery
- m
->timenow
> 0)
4809 event
= rr
->DelayDelivery
;
4812 if (rr
->DelayDelivery
) CacheRecordDeferredAdd(m
, rr
);
4813 if (rr
->CRActiveQuestion
&& rr
->UnansweredQueries
< MaxUnansweredQueries
)
4815 if (m
->timenow
- rr
->NextRequiredQuery
< 0) // If not yet time for next query
4816 event
= NextCacheCheckEvent(rr
); // then just record when we want the next query
4817 else // else trigger our question to go out now
4819 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4820 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4821 m
->NextScheduledQuery
= m
->timenow
;
4822 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4823 // which will correctly update m->NextCacheCheck for us.
4824 event
= m
->timenow
+ FutureTime
;
4830 if (!recordReleased
) // Schedule if we did not release the record
4832 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4833 (event
- m
->timenow
) / mDNSPlatformOneSecond
, CacheCheckGracePeriod(rr
), CRDisplayString(m
, rr
));
4834 if (m
->rrcache_nextcheck
[slot
] - event
> 0)
4835 m
->rrcache_nextcheck
[slot
] = event
;
4839 if (cg
->rrcache_tail
!= rp
) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg
->rrcache_tail
, rp
);
4840 cg
->rrcache_tail
= rp
;
4841 m
->lock_rrcache
= 0;
4844 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4846 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4847 // returns true if there is an answer.
4849 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4850 // returns true to indicate the same.
4851 mDNSlocal mDNSBool
AnswerQuestionWithLORecord(mDNS
*const m
, DNSQuestion
*q
, mDNSBool checkOnly
)
4856 if (m
->CurrentRecord
)
4857 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
4859 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
4862 m
->CurrentRecord
= ag
->members
;
4863 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
4865 AuthRecord
*rr
= m
->CurrentRecord
;
4866 m
->CurrentRecord
= rr
->next
;
4868 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4869 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4871 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4872 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4873 // we handle both mDNSInterface_Any and scoped questions.
4875 if (rr
->ARType
== AuthRecordLocalOnly
|| (rr
->ARType
== AuthRecordP2P
&& (q
->InterfaceID
== mDNSInterface_Any
|| q
->InterfaceID
== mDNSInterface_BLE
)))
4876 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
4880 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q
->qname
.c
, DNSTypeName(q
->qtype
),
4881 ARDisplayString(m
, rr
));
4882 m
->CurrentRecord
= mDNSNULL
;
4885 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_add
);
4886 if (m
->CurrentQuestion
!= q
)
4887 break; // If callback deleted q, then we're finished here
4891 m
->CurrentRecord
= mDNSNULL
;
4893 if (m
->CurrentQuestion
!= q
)
4895 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4899 if (q
->LOAddressAnswers
)
4901 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4902 q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4906 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4907 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4908 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4909 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4910 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4913 lr
= ag
->NewLocalOnlyRecords
;
4916 if (UniqueLocalOnlyRecord(lr
) && LocalOnlyRecordAnswersQuestion(lr
, q
))
4918 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4919 " LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), q
->LOAddressAnswers
);
4928 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4929 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4931 mDNSlocal
void AnswerSuppressedQuestion(mDNS
*const m
, DNSQuestion
*q
)
4933 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4934 // just deactivate the DNSQuestion.
4935 if (q
->ReturnIntermed
)
4937 GenerateNegativeResponse(m
, mDNSInterface_Any
, QC_suppressed
);
4941 q
->ThisQInterval
= 0;
4945 mDNSlocal
void AnswerNewQuestion(mDNS
*const m
)
4947 mDNSBool ShouldQueryImmediately
= mDNStrue
;
4948 DNSQuestion
*const q
= m
->NewQuestions
; // Grab the question we're going to answer
4949 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4950 if (!mDNSOpaque16IsZero(q
->TargetQID
)) DNS64HandleNewQuestion(m
, q
);
4952 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
4954 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
4956 if (cg
) CheckCacheExpiration(m
, HashSlotFromNameHash(q
->qnamehash
), cg
);
4957 if (m
->NewQuestions
!= q
) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit
; }
4958 m
->NewQuestions
= q
->next
;
4959 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4960 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4962 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4963 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4964 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4965 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4966 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4967 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4968 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4969 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4971 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4972 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4973 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4974 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4976 if (m
->lock_rrcache
) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4977 // This should be safe, because calling the client's question callback may cause the
4978 // question list to be modified, but should not ever cause the rrcache list to be modified.
4979 // If the client's question callback deletes the question, then m->CurrentQuestion will
4980 // be advanced, and we'll exit out of the loop
4981 m
->lock_rrcache
= 1;
4982 if (m
->CurrentQuestion
) {
4983 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4984 "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME
" (" PUB_S
")",
4985 m
->CurrentQuestion
->request_id
, mDNSVal16(m
->CurrentQuestion
->TargetQID
),
4986 DM_NAME_PARAM(&m
->CurrentQuestion
->qname
), DNSTypeName(m
->CurrentQuestion
->qtype
));
4989 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
4991 if (q
->NoAnswer
== NoAnswer_Fail
)
4993 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
4994 "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME
" (" PUB_S
")",
4995 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
4997 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4998 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->dnsservice
);
5000 MakeNegativeCacheRecord(m
, &m
->rec
.r
, &q
->qname
, q
->qnamehash
, q
->qtype
, q
->qclass
, 60, mDNSInterface_Any
, q
->qDNSServer
);
5002 q
->NoAnswer
= NoAnswer_Normal
; // Temporarily turn off answer suppression
5003 AnswerCurrentQuestionWithResourceRecord(m
, &m
->rec
.r
, QC_addnocache
);
5004 // Don't touch the question if it has been stopped already
5005 if (m
->CurrentQuestion
== q
) q
->NoAnswer
= NoAnswer_Fail
; // Restore NoAnswer state
5006 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
5009 if (m
->CurrentQuestion
!= q
)
5011 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
5015 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
5016 // or P2P record, then we are done.
5017 if (AnswerQuestionWithLORecord(m
, q
, mDNSfalse
))
5020 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5021 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5022 // the question out.
5025 AnswerSuppressedQuestion(m
, q
);
5030 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
5031 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
5033 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5034 mDNSu32 SecsSinceRcvd
= ((mDNSu32
)(m
->timenow
- cr
->TimeRcvd
)) / mDNSPlatformOneSecond
;
5035 mDNSBool IsExpired
= (cr
->resrec
.rroriginalttl
<= SecsSinceRcvd
);
5036 if (IsExpired
&& q
->allowExpired
!= AllowExpired_AllowExpiredAnswers
) continue; // Go to next one in loop
5038 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5039 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5040 if ((cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) || (q
->ExpectUnique
))
5041 ShouldQueryImmediately
= mDNSfalse
;
5042 q
->CurrentAnswers
++;
5043 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
++;
5044 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
++;
5045 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5046 if (q
->metrics
.expiredAnswerState
== ExpiredAnswer_Allowed
) q
->metrics
.expiredAnswerState
= IsExpired
? ExpiredAnswer_AnsweredWithExpired
: ExpiredAnswer_AnsweredWithCache
;
5048 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5049 cr
->LastCachedAnswerTime
= m
->timenow
;
5050 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q
->TargetQID
) ? CacheRequestType_multicast
: CacheRequestType_unicast
, CacheState_hit
);
5052 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_add
);
5053 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5055 else if (mDNSOpaque16IsZero(q
->TargetQID
) && RRTypeIsAddressType(cr
->resrec
.rrtype
) && RRTypeIsAddressType(q
->qtype
))
5056 ShouldQueryImmediately
= mDNSfalse
;
5058 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5059 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5060 if (m
->CurrentQuestion
!= q
) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit
; }
5062 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5063 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q
->TargetQID
) ? CacheRequestType_multicast
: CacheRequestType_unicast
, CacheState_miss
);
5065 q
->InitialCacheMiss
= mDNStrue
; // Initial cache check is done, so mark as a miss from now on
5066 if (q
->allowExpired
== AllowExpired_AllowExpiredAnswers
)
5068 q
->allowExpired
= AllowExpired_MakeAnswersImmortal
; // After looking through the cache for an answer, demote to make immortal
5069 if (q
->firstExpiredQname
.c
[0]) // If an original query name was saved on an expired answer, start it over in case it is updated
5071 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
5072 "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME
" for allowExpiredAnswers question",
5073 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->firstExpiredQname
));
5074 mDNS_StopQuery_internal(m
, q
); // Stop old query
5075 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5076 if (!SameDomainName(&q
->qname
, &q
->firstExpiredQname
))
5078 Querier_PrepareQuestionForUnwindRestart(q
);
5081 AssignDomainName(&q
->qname
, &q
->firstExpiredQname
); // Update qname
5082 q
->qnamehash
= DomainNameHashValue(&q
->qname
); // and namehash
5083 mDNS_StartQuery_internal(m
, q
); // start new query
5084 q
->CNAMEReferrals
= 0; // Reset referral count
5085 q
->firstExpiredQname
.c
[0] = 0; // Erase the domain name
5089 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5090 // Hence we don't execute the following block of code for those cases.
5091 if (ShouldQueryImmediately
&& ActiveQuestion(q
))
5093 debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q
->request_id
, mDNSVal16(q
->TargetQID
), q
->qname
.c
, DNSTypeName(q
->qtype
));
5094 q
->ThisQInterval
= InitialQuestionInterval
;
5095 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5096 if (mDNSOpaque16IsZero(q
->TargetQID
)) // For mDNS, spread packets to avoid a burst of simultaneous queries
5098 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5099 if (!m
->RandomQueryDelay
)
5100 m
->RandomQueryDelay
= (mDNSPlatformOneSecond
+ mDNSRandom(mDNSPlatformOneSecond
*5) - 1) / 50 + 1;
5101 q
->LastQTime
+= m
->RandomQueryDelay
;
5105 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5106 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5107 // answers for this question until *after* its scheduled transmission time, in which case
5108 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5109 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5110 SetNextQueryTime(m
,q
);
5113 m
->CurrentQuestion
= mDNSNULL
;
5114 m
->lock_rrcache
= 0;
5117 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5118 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
5119 mDNSlocal
void AnswerNewLocalOnlyQuestion(mDNS
*const m
)
5122 DNSQuestion
*q
= m
->NewLocalOnlyQuestions
; // Grab the question we're going to answer
5123 mDNSBool retEv
= mDNSfalse
;
5124 m
->NewLocalOnlyQuestions
= q
->next
; // Advance NewLocalOnlyQuestions to the next (if any)
5126 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5128 if (m
->CurrentQuestion
)
5129 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5130 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5131 m
->CurrentQuestion
= q
; // Indicate which question we're answering, so we'll know if it gets deleted
5133 if (m
->CurrentRecord
)
5134 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
5136 // 1. First walk the LocalOnly records answering the LocalOnly question
5137 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5138 // walk the ResourceRecords list delivering the answers
5139 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
5142 m
->CurrentRecord
= ag
->members
;
5143 while (m
->CurrentRecord
&& m
->CurrentRecord
!= ag
->NewLocalOnlyRecords
)
5145 AuthRecord
*rr
= m
->CurrentRecord
;
5146 m
->CurrentRecord
= rr
->next
;
5147 if (LocalOnlyRecordAnswersQuestion(rr
, q
))
5150 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_add
);
5151 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5156 if (m
->CurrentQuestion
== q
)
5158 m
->CurrentRecord
= m
->ResourceRecords
;
5160 while (m
->CurrentRecord
&& m
->CurrentRecord
!= m
->NewLocalRecords
)
5162 AuthRecord
*ar
= m
->CurrentRecord
;
5163 m
->CurrentRecord
= ar
->next
;
5164 if (AuthRecordAnswersQuestion(ar
, q
))
5167 AnswerLocalQuestionWithLocalAuthRecord(m
, ar
, QC_add
);
5168 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
5173 // The local host is the authoritative source for LocalOnly questions
5174 // so if no records exist and client requested intermediates, then generate a negative response
5175 if (!retEv
&& (m
->CurrentQuestion
== q
) && q
->ReturnIntermed
)
5176 GenerateNegativeResponse(m
, mDNSInterface_LocalOnly
, QC_forceresponse
);
5178 m
->CurrentQuestion
= mDNSNULL
;
5179 m
->CurrentRecord
= mDNSNULL
;
5182 mDNSlocal CacheEntity
*GetCacheEntity(mDNS
*const m
, const CacheGroup
*const PreserveCG
)
5184 CacheEntity
*e
= mDNSNULL
;
5186 if (m
->lock_rrcache
) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL
); }
5187 m
->lock_rrcache
= 1;
5189 // If we have no free records, ask the client layer to give us some more memory
5190 if (!m
->rrcache_free
&& m
->MainCallback
)
5192 if (m
->rrcache_totalused
!= m
->rrcache_size
)
5194 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
5195 "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5196 m
->rrcache_totalused
, m
->rrcache_size
);
5199 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5200 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5201 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5202 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5203 // and recycle them, instead of allocating more memory.
5204 if (m
->rrcache_size
> 5000 && m
->rrcache_size
/ 32 > m
->rrcache_active
)
5206 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
5207 "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5208 m
->rrcache_size
, m
->rrcache_active
);
5212 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5213 m
->MainCallback(m
, mStatus_GrowCache
);
5214 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5218 // If we still have no free records, recycle all the records we can.
5219 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5220 if (!m
->rrcache_free
)
5222 mDNSu32 oldtotalused
= m
->rrcache_totalused
;
5224 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5226 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5229 CacheRecord
**rp
= &(*cp
)->members
;
5232 // Records that answer still-active questions are not candidates for recycling
5233 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5234 if ((*rp
)->CRActiveQuestion
|| (*rp
)->NextInCFList
)
5238 CacheRecord
*rr
= *rp
;
5239 *rp
= (*rp
)->next
; // Cut record from list
5240 ReleaseCacheRecord(m
, rr
);
5243 if ((*cp
)->rrcache_tail
!= rp
)
5244 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot
, (*cp
)->rrcache_tail
, rp
);
5245 (*cp
)->rrcache_tail
= rp
;
5246 if ((*cp
)->members
|| (*cp
)==PreserveCG
) cp
=&(*cp
)->next
;
5247 else ReleaseCacheGroup(m
, cp
);
5250 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5251 oldtotalused
- m
->rrcache_totalused
, oldtotalused
, m
->rrcache_totalused
);
5254 if (m
->rrcache_free
) // If there are records in the free list, take one
5256 e
= m
->rrcache_free
;
5257 m
->rrcache_free
= e
->next
;
5258 if (++m
->rrcache_totalused
>= m
->rrcache_report
)
5260 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "RR Cache now using %u objects", m
->rrcache_totalused
);
5261 if (m
->rrcache_report
< 100) m
->rrcache_report
+= 10;
5262 else if (m
->rrcache_report
< 1000) m
->rrcache_report
+= 100;
5263 else m
->rrcache_report
+= 1000;
5265 mDNSPlatformMemZero(e
, sizeof(*e
));
5268 m
->lock_rrcache
= 0;
5273 mDNSlocal CacheRecord
*GetCacheRecord(mDNS
*const m
, CacheGroup
*cg
, mDNSu16 RDLength
)
5275 CacheRecord
*r
= (CacheRecord
*)GetCacheEntity(m
, cg
);
5278 r
->resrec
.rdata
= (RData
*)&r
->smallrdatastorage
; // By default, assume we're usually going to be using local storage
5279 if (RDLength
> InlineCacheRDSize
) // If RDLength is too big, allocate extra storage
5281 r
->resrec
.rdata
= (RData
*) mDNSPlatformMemAllocateClear(sizeofRDataHeader
+ RDLength
);
5282 if (r
->resrec
.rdata
) r
->resrec
.rdata
->MaxRDLength
= r
->resrec
.rdlength
= RDLength
;
5283 else { ReleaseCacheEntity(m
, (CacheEntity
*)r
); r
= mDNSNULL
; }
5289 mDNSlocal CacheGroup
*GetCacheGroup(mDNS
*const m
, const mDNSu32 slot
, const ResourceRecord
*const rr
)
5291 mDNSu16 namelen
= DomainNameLength(rr
->name
);
5292 CacheGroup
*cg
= (CacheGroup
*)GetCacheEntity(m
, mDNSNULL
);
5293 if (!cg
) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr
->name
->c
); return(mDNSNULL
); }
5294 cg
->next
= m
->rrcache_hash
[slot
];
5295 cg
->namehash
= rr
->namehash
;
5296 cg
->members
= mDNSNULL
;
5297 cg
->rrcache_tail
= &cg
->members
;
5298 if (namelen
> sizeof(cg
->namestorage
))
5299 cg
->name
= (domainname
*) mDNSPlatformMemAllocate(namelen
);
5301 cg
->name
= (domainname
*)cg
->namestorage
;
5304 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr
->name
->c
);
5305 ReleaseCacheEntity(m
, (CacheEntity
*)cg
);
5308 AssignDomainName(cg
->name
, rr
->name
);
5310 if (CacheGroupForRecord(m
, rr
)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr
->name
->c
);
5311 m
->rrcache_hash
[slot
] = cg
;
5312 if (CacheGroupForRecord(m
, rr
) != cg
) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr
->name
->c
);
5317 mDNSexport
void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
)
5321 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5322 // a positive answer using an expired record (e.g. from an interface that has gone away).
5323 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5324 // summary deletion without giving the proper callback to any questions that are monitoring it.
5325 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5326 rr
->TimeRcvd
= m
->timenow
- mDNSPlatformOneSecond
* 60;
5327 rr
->UnansweredQueries
= MaxUnansweredQueries
;
5328 rr
->resrec
.rroriginalttl
= 0;
5329 SetNextCacheCheckTimeForRecord(m
, rr
);
5332 mDNSexport mDNSs32
mDNS_TimeNow(const mDNS
*const m
)
5335 mDNSPlatformLock(m
);
5338 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5339 if (!m
->timenow
) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m
->mDNS_busy
);
5342 if (m
->timenow
) time
= m
->timenow
;
5343 else time
= mDNS_TimeNow_NoLock(m
);
5344 mDNSPlatformUnlock(m
);
5348 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5349 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5350 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5351 #define SetSPSProxyListChanged(X) do { \
5352 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5353 m->SPSProxyListChanged = (X); } while(0)
5355 // Called from mDNS_Execute() to expire stale proxy records
5356 mDNSlocal
void CheckProxyRecords(mDNS
*const m
, AuthRecord
*list
)
5358 m
->CurrentRecord
= list
;
5359 while (m
->CurrentRecord
)
5361 AuthRecord
*rr
= m
->CurrentRecord
;
5362 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& rr
->WakeUp
.HMAC
.l
[0])
5364 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5365 // so we need to cease proxying for *all* records we may have, expired or not.
5366 if (m
->SPSSocket
&& m
->timenow
- rr
->TimeExpire
< 0) // If proxy record not expired yet, update m->NextScheduledSPS
5368 if (m
->NextScheduledSPS
- rr
->TimeExpire
> 0)
5369 m
->NextScheduledSPS
= rr
->TimeExpire
;
5371 else // else proxy record expired, so remove it
5373 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5374 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, ARDisplayString(m
, rr
));
5375 SetSPSProxyListChanged(rr
->resrec
.InterfaceID
);
5376 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
5377 // Don't touch rr after this -- memory may have been free'd
5380 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5381 // new records could have been added to the end of the list as a result of that call.
5382 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
5383 m
->CurrentRecord
= rr
->next
;
5387 mDNSlocal
void CheckRmvEventsForLocalRecords(mDNS
*const m
)
5389 while (m
->CurrentRecord
)
5391 AuthRecord
*rr
= m
->CurrentRecord
;
5392 if (rr
->AnsweredLocalQ
&& rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
)
5394 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m
, rr
));
5395 rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
5396 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_rmv
);
5397 if (m
->CurrentRecord
== rr
) // If rr still exists in list, restore its state now
5399 rr
->resrec
.RecordType
= kDNSRecordTypeDeregistering
;
5400 rr
->AnsweredLocalQ
= mDNSfalse
;
5401 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5402 // For LocalOnly records, we don't do that and hence we need to do that here.
5403 if (RRLocalOnly(rr
)) CompleteDeregistration(m
, rr
);
5406 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5407 m
->CurrentRecord
= rr
->next
;
5411 mDNSlocal
void TimeoutQuestions_internal(mDNS
*const m
, DNSQuestion
* questions
, mDNSInterfaceID InterfaceID
)
5413 if (m
->CurrentQuestion
)
5414 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m
->CurrentQuestion
->qname
.c
,
5415 DNSTypeName(m
->CurrentQuestion
->qtype
));
5416 m
->CurrentQuestion
= questions
;
5417 while (m
->CurrentQuestion
)
5419 DNSQuestion
*const q
= m
->CurrentQuestion
;
5422 if (!q
->TimeoutQuestion
)
5423 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5425 if (m
->timenow
- q
->StopTime
>= 0)
5427 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q
, q
->qname
.c
, m
->timenow
- q
->StopTime
);
5428 q
->LOAddressAnswers
= 0; // unset since timing out the question
5429 GenerateNegativeResponse(m
, InterfaceID
, QC_forceresponse
);
5430 if (m
->CurrentQuestion
== q
) q
->StopTime
= 0;
5434 if (m
->NextScheduledStopTime
- q
->StopTime
> 0)
5435 m
->NextScheduledStopTime
= q
->StopTime
;
5438 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5439 // We can't do this at the start of the loop because GenerateNegativeResponse
5440 // depends on having m->CurrentQuestion point to the right question
5441 if (m
->CurrentQuestion
== q
)
5442 m
->CurrentQuestion
= q
->next
;
5444 m
->CurrentQuestion
= mDNSNULL
;
5447 mDNSlocal
void TimeoutQuestions(mDNS
*const m
)
5449 m
->NextScheduledStopTime
= m
->timenow
+ FutureTime
; // push reschedule of TimeoutQuestions to way off into the future
5450 TimeoutQuestions_internal(m
, m
->Questions
, mDNSInterface_Any
);
5451 TimeoutQuestions_internal(m
, m
->LocalOnlyQuestions
, mDNSInterface_LocalOnly
);
5454 mDNSlocal
void mDNSCoreFreeProxyRR(mDNS
*const m
)
5456 AuthRecord
*rrPtr
= m
->SPSRRSet
, *rrNext
= mDNSNULL
;
5457 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__
);
5460 rrNext
= rrPtr
->next
;
5461 mDNSPlatformMemFree(rrPtr
);
5464 m
->SPSRRSet
= mDNSNULL
;
5467 mDNSexport mDNSs32
mDNS_Execute(mDNS
*const m
)
5469 mDNS_Lock(m
); // Must grab lock before trying to read m->timenow
5471 if (m
->timenow
- m
->NextScheduledEvent
>= 0)
5474 AuthRecord
*head
, *tail
;
5478 verbosedebugf("mDNS_Execute");
5480 if (m
->CurrentQuestion
)
5481 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5482 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5484 if (m
->CurrentRecord
)
5485 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m
, m
->CurrentRecord
));
5487 // 1. If we're past the probe suppression time, we can clear it
5488 if (m
->SuppressProbes
&& m
->timenow
- m
->SuppressProbes
>= 0) m
->SuppressProbes
= 0;
5490 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5491 if (m
->NumFailedProbes
&& m
->timenow
- m
->ProbeFailTime
>= mDNSPlatformOneSecond
* 10) m
->NumFailedProbes
= 0;
5493 // 3. Purge our cache of stale old records
5494 if (m
->rrcache_size
&& m
->timenow
- m
->NextCacheCheck
>= 0)
5496 mDNSu32 numchecked
= 0;
5497 m
->NextCacheCheck
= m
->timenow
+ FutureTime
;
5498 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5500 if (m
->timenow
- m
->rrcache_nextcheck
[slot
] >= 0)
5502 CacheGroup
**cp
= &m
->rrcache_hash
[slot
];
5503 m
->rrcache_nextcheck
[slot
] = m
->timenow
+ FutureTime
;
5506 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked
, slot
, *cp
? (*cp
)->name
: (domainname
*)"\x04NULL");
5508 CheckCacheExpiration(m
, slot
, *cp
);
5509 if ((*cp
)->members
) cp
=&(*cp
)->next
;
5510 else ReleaseCacheGroup(m
, cp
);
5513 // Even if we didn't need to actually check this slot yet, still need to
5514 // factor its nextcheck time into our overall NextCacheCheck value
5515 if (m
->NextCacheCheck
- m
->rrcache_nextcheck
[slot
] > 0)
5516 m
->NextCacheCheck
= m
->rrcache_nextcheck
[slot
];
5518 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked
, m
->NextCacheCheck
- m
->timenow
);
5521 if (m
->timenow
- m
->NextScheduledSPS
>= 0)
5523 m
->NextScheduledSPS
= m
->timenow
+ FutureTime
;
5524 CheckProxyRecords(m
, m
->DuplicateRecords
); // Clear m->DuplicateRecords first, then m->ResourceRecords
5525 CheckProxyRecords(m
, m
->ResourceRecords
);
5528 SetSPSProxyListChanged(mDNSNULL
); // Perform any deferred BPF reconfiguration now
5530 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5531 // as records could have expired during that check
5532 if (m
->timenow
- m
->NextScheduledKA
>= 0)
5534 m
->NextScheduledKA
= m
->timenow
+ FutureTime
;
5535 mDNS_SendKeepalives(m
);
5538 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5539 if (m
->NextBonjourDisableTime
&& (m
->timenow
- m
->NextBonjourDisableTime
>= 0))
5541 // Schedule immediate network change processing to leave the multicast group
5542 // since the delay time has expired since the previous active registration or query.
5543 m
->NetworkChanged
= m
->timenow
;
5544 m
->NextBonjourDisableTime
= 0;
5545 m
->BonjourEnabled
= 0;
5547 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5551 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5552 if (m
->AnnounceOwner
&& m
->timenow
- m
->AnnounceOwner
>= 0)
5554 m
->AnnounceOwner
= 0;
5557 if (m
->DelaySleep
&& m
->timenow
- m
->DelaySleep
>= 0)
5560 if (m
->SleepState
== SleepState_Transferring
)
5562 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5563 BeginSleepProcessing(m
);
5567 // 4. See if we can answer any of our new local questions from the cache
5568 for (i
=0; m
->NewQuestions
&& i
<1000; i
++)
5570 if (m
->NewQuestions
->DelayAnswering
&& m
->timenow
- m
->NewQuestions
->DelayAnswering
< 0) break;
5571 AnswerNewQuestion(m
);
5573 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5575 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5576 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5577 for (i
=0; i
<1000 && m
->LocalRemoveEvents
; i
++)
5579 m
->LocalRemoveEvents
= mDNSfalse
;
5580 m
->CurrentRecord
= m
->ResourceRecords
;
5581 CheckRmvEventsForLocalRecords(m
);
5582 // Walk the LocalOnly records and deliver the RMV events
5583 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5584 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5586 m
->CurrentRecord
= ag
->members
;
5587 if (m
->CurrentRecord
) CheckRmvEventsForLocalRecords(m
);
5591 if (i
>= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5593 for (i
=0; m
->NewLocalOnlyQuestions
&& i
<1000; i
++) AnswerNewLocalOnlyQuestion(m
);
5594 if (i
>= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5596 head
= tail
= mDNSNULL
;
5597 for (i
=0; i
<1000 && m
->NewLocalRecords
&& m
->NewLocalRecords
!= head
; i
++)
5599 AuthRecord
*rr
= m
->NewLocalRecords
;
5600 m
->NewLocalRecords
= m
->NewLocalRecords
->next
;
5601 if (LocalRecordReady(rr
))
5603 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5604 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_add
);
5608 // If we have just one record that is not ready, we don't have to unlink and
5609 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5610 // terminate and set the NewLocalRecords to rr.
5611 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m
, rr
));
5612 if (head
!= mDNSNULL
|| m
->NewLocalRecords
!= mDNSNULL
)
5613 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head
, m
->NewLocalRecords
);
5619 AuthRecord
**p
= &m
->ResourceRecords
; // Find this record in our list of active records
5620 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m
, rr
));
5621 // if this is the first record we are skipping, move to the end of the list.
5622 // if we have already skipped records before, append it at the end.
5623 while (*p
&& *p
!= rr
) p
=&(*p
)->next
;
5624 if (*p
) *p
= rr
->next
; // Cut this record from the list
5625 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m
, rr
)); break; }
5628 while (*p
) p
=&(*p
)->next
;
5637 rr
->next
= mDNSNULL
;
5640 m
->NewLocalRecords
= head
;
5641 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head
? ARDisplayString(m
, head
) : "NULL"));
5643 if (i
>= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5645 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5646 // to our local questions
5647 if (m
->NewLocalOnlyRecords
)
5649 m
->NewLocalOnlyRecords
= mDNSfalse
;
5650 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5652 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5654 for (i
=0; i
<100 && ag
->NewLocalOnlyRecords
; i
++)
5656 AuthRecord
*rr
= ag
->NewLocalOnlyRecords
;
5657 ag
->NewLocalOnlyRecords
= ag
->NewLocalOnlyRecords
->next
;
5658 // LocalOnly records should always be ready as they never probe
5659 if (LocalRecordReady(rr
))
5661 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m
, rr
));
5662 AnswerAllLocalQuestionsWithLocalAuthRecord(m
, rr
, QC_add
);
5664 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m
, rr
));
5666 // We limit about 100 per AuthGroup that can be serviced at a time
5667 if (i
>= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5672 // 5. See what packets we need to send
5673 if (m
->mDNSPlatformStatus
!= mStatus_NoError
|| (m
->SleepState
== SleepState_Sleeping
))
5674 DiscardDeregistrations(m
);
5675 if (m
->mDNSPlatformStatus
== mStatus_NoError
&& (m
->SuppressSending
== 0 || m
->timenow
- m
->SuppressSending
>= 0))
5677 // If the platform code is ready, and we're not suppressing packet generation right now
5678 // then send our responses, probes, and questions.
5679 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5680 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5681 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5682 // Finally, we send responses, including the previously mentioned records that just completed probing.
5683 m
->SuppressSending
= 0;
5685 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5686 if (m
->timenow
- m
->NextScheduledQuery
>= 0 || m
->timenow
- m
->NextScheduledProbe
>= 0) SendQueries(m
);
5687 if (m
->timenow
- m
->NextScheduledQuery
>= 0)
5690 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5691 m
->timenow
, m
->NextScheduledQuery
, m
->timenow
- m
->NextScheduledQuery
);
5692 m
->NextScheduledQuery
= m
->timenow
+ mDNSPlatformOneSecond
;
5693 for (q
= m
->Questions
; q
&& q
!= m
->NewQuestions
; q
=q
->next
)
5694 if (ActiveQuestion(q
) && m
->timenow
- NextQSendTime(q
) >= 0)
5695 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
5697 if (m
->timenow
- m
->NextScheduledProbe
>= 0)
5699 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5700 m
->timenow
, m
->NextScheduledProbe
, m
->timenow
- m
->NextScheduledProbe
);
5701 m
->NextScheduledProbe
= m
->timenow
+ mDNSPlatformOneSecond
;
5704 // 7. Send Response packets, including probing records just advanced to announcing state
5705 if (m
->timenow
- m
->NextScheduledResponse
>= 0) SendResponses(m
);
5706 if (m
->timenow
- m
->NextScheduledResponse
>= 0)
5708 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5709 m
->NextScheduledResponse
= m
->timenow
+ mDNSPlatformOneSecond
;
5713 // Clear RandomDelay values, ready to pick a new different value next time
5714 m
->RandomQueryDelay
= 0;
5715 m
->RandomReconfirmDelay
= 0;
5717 // See if any questions (or local-only questions) have timed out
5718 if (m
->NextScheduledStopTime
&& m
->timenow
- m
->NextScheduledStopTime
>= 0) TimeoutQuestions(m
);
5719 #ifndef UNICAST_DISABLED
5720 if (m
->NextSRVUpdate
&& m
->timenow
- m
->NextSRVUpdate
>= 0) UpdateAllSRVRecords(m
);
5721 if (m
->timenow
- m
->NextScheduledNATOp
>= 0) CheckNATMappings(m
);
5722 if (m
->timenow
- m
->NextuDNSEvent
>= 0) uDNS_Tasks(m
);
5724 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5725 extern void serviceBLE();
5726 if (m
->NextBLEServiceTime
&& (m
->timenow
- m
->NextBLEServiceTime
>= 0)) serviceBLE();
5727 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5730 // Note about multi-threaded systems:
5731 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5732 // performing mDNS API operations that change our next scheduled event time.
5734 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5735 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5736 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5737 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5738 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5739 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5740 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5741 // without blocking. This avoids the race condition between the signal from the other thread arriving
5742 // just *before* or just *after* the main thread enters the blocking primitive.
5744 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5745 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5746 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5747 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5748 // by the time it gets to the timer callback function).
5750 mDNS_Unlock(m
); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5751 return(m
->NextScheduledEvent
);
5754 #ifndef UNICAST_DISABLED
5755 mDNSlocal
void SuspendLLQs(mDNS
*m
)
5758 for (q
= m
->Questions
; q
; q
= q
->next
)
5759 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->state
== LLQ_Established
)
5760 { q
->ReqLease
= 0; sendLLQRefresh(m
, q
); }
5762 #endif // UNICAST_DISABLED
5764 mDNSlocal mDNSBool
QuestionHasLocalAnswers(mDNS
*const m
, DNSQuestion
*q
)
5769 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
5772 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
5773 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5774 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
5776 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q
, q
->qname
.c
, DNSTypeName(q
->qtype
), ARDisplayString(m
, rr
));
5783 // ActivateUnicastQuery() is called from three places:
5784 // 1. When a new question is created
5785 // 2. On wake from sleep
5786 // 3. When the DNS configuration changes
5787 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5788 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5789 mDNSlocal
void ActivateUnicastQuery(mDNS
*const m
, DNSQuestion
*const question
, mDNSBool ScheduleImmediately
)
5791 if (!question
->DuplicateOf
)
5793 debugf("ActivateUnicastQuery: %##s %s%s",
5794 question
->qname
.c
, DNSTypeName(question
->qtype
), ScheduleImmediately
? " ScheduleImmediately" : "");
5795 question
->CNAMEReferrals
= 0;
5796 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
5797 if (question
->LongLived
)
5799 question
->state
= LLQ_Init
;
5800 question
->id
= zeroOpaque64
;
5801 question
->servPort
= zeroIPPort
;
5802 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
5804 // If the question has local answers, then we don't want answers from outside
5805 if (ScheduleImmediately
&& !QuestionHasLocalAnswers(m
, question
))
5807 question
->ThisQInterval
= InitialQuestionInterval
;
5808 question
->LastQTime
= m
->timenow
- question
->ThisQInterval
;
5809 SetNextQueryTime(m
, question
);
5814 // Caller should hold the lock
5815 mDNSexport
void mDNSCoreRestartAddressQueries(mDNS
*const m
, mDNSBool SearchDomainsChanged
, FlushCache flushCacheRecords
,
5816 CallbackBeforeStartQuery BeforeStartCallback
, void *context
)
5819 DNSQuestion
*restart
= mDNSNULL
;
5823 // 1. Flush the cache records
5824 if (flushCacheRecords
) flushCacheRecords(m
);
5826 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5827 // we are going to stop the question. Hence we need to deliver the RMV event before we
5828 // stop the question.
5830 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5831 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5832 // *any* other question which could be the next one that we may process here. RestartQuestion
5833 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5834 // if the "next" question is stopped while the CurrentQuestion is stopped
5836 if (m
->RestartQuestion
)
5837 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5838 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
5840 m
->RestartQuestion
= m
->Questions
;
5841 while (m
->RestartQuestion
)
5843 q
= m
->RestartQuestion
;
5844 m
->RestartQuestion
= q
->next
;
5845 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5846 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5847 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5848 // question followed by the original query that refers to this GetZoneData question, we will end up
5849 // freeing the GetZoneData question and then start the "freed" question at the end.
5851 if (IsGetZoneDataQuestion(q
))
5853 DNSQuestion
*refq
= q
->next
;
5854 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5855 // debug stuff, we just try to find the referencing question and don't do much with it
5858 if (q
== &refq
->nta
->question
)
5860 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq
, refq
->qname
.c
, DNSTypeName(refq
->qtype
), q
);
5867 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5868 if (q
->qtype
!= kDNSType_A
&& q
->qtype
!= kDNSType_AAAA
&& q
->qtype
!= kDNSType_CNAME
) continue;
5870 // If the search domains did not change, then we restart all the queries. Otherwise, only
5871 // for queries for which we "might" have appended search domains ("might" because we may
5872 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5873 if (!SearchDomainsChanged
|| q
->AppendSearchDomains
)
5875 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5876 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5877 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5878 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5879 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5880 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5881 // for the original query using these cache entries as ADDs were never delivered using these cache
5882 // entries and hence this order is needed.
5884 // If the query is suppressed, the RMV events won't be delivered
5885 if (!CacheRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5887 // Suppressed status does not affect questions that are answered using local records
5888 if (!LocalRecordRmvEventsForQuestion(m
, q
)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5890 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q
,
5891 q
->qname
.c
, DNSTypeName(q
->qtype
), q
->AppendSearchDomains
);
5892 mDNS_StopQuery_internal(m
, q
);
5893 if (q
->ResetHandler
) q
->ResetHandler(q
);
5899 // 3. Callback before we start the query
5900 if (BeforeStartCallback
) BeforeStartCallback(m
, context
);
5902 // 4. Restart all the stopped queries
5906 restart
= restart
->next
;
5908 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
5909 mDNS_StartQuery_internal(m
, q
);
5913 mDNSexport
void mDNSCoreRestartQueries(mDNS
*const m
)
5917 #ifndef UNICAST_DISABLED
5918 // Retrigger all our uDNS questions
5919 if (m
->CurrentQuestion
)
5920 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5921 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
5922 m
->CurrentQuestion
= m
->Questions
;
5923 while (m
->CurrentQuestion
)
5925 q
= m
->CurrentQuestion
;
5926 m
->CurrentQuestion
= m
->CurrentQuestion
->next
;
5927 if (!mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
5929 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5930 mdns_querier_forget(&q
->querier
);
5932 ActivateUnicastQuery(m
, q
, mDNStrue
);
5937 // Retrigger all our mDNS questions
5938 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
5939 mDNSCoreRestartQuestion(m
, q
);
5942 // restart question if it's multicast and currently active
5943 mDNSexport
void mDNSCoreRestartQuestion(mDNS
*const m
, DNSQuestion
*q
)
5945 if (mDNSOpaque16IsZero(q
->TargetQID
) && ActiveQuestion(q
))
5947 q
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
5948 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
5949 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
;
5950 q
->RecentAnswerPkts
= 0;
5951 ExpireDupSuppressInfo(q
->DupSuppress
, m
->timenow
);
5952 m
->NextScheduledQuery
= m
->timenow
;
5956 // restart the probe/announce cycle for multicast record
5957 mDNSexport
void mDNSCoreRestartRegistration(mDNS
*const m
, AuthRecord
*rr
, int announceCount
)
5959 if (!AuthRecord_uDNS(rr
))
5961 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
&& !rr
->DependentOn
) rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
5962 rr
->ProbeCount
= DefaultProbeCountForRecordType(rr
->resrec
.RecordType
);
5964 if (mDNS_KeepaliveRecord(&rr
->resrec
))
5966 rr
->AnnounceCount
= 0; // Do not announce keepalive records
5970 // announceCount < 0 indicates default announce count should be used
5971 if (announceCount
< 0)
5972 announceCount
= InitialAnnounceCount
;
5973 if (rr
->AnnounceCount
< (mDNSu8
)announceCount
)
5974 rr
->AnnounceCount
= (mDNSu8
)announceCount
;
5977 rr
->SendNSECNow
= mDNSNULL
;
5978 InitializeLastAPTime(m
, rr
);
5982 // ***************************************************************************
5983 #if COMPILER_LIKES_PRAGMA_MARK
5985 #pragma mark - Power Management (Sleep/Wake)
5988 mDNSexport
void mDNS_UpdateAllowSleep(mDNS
*const m
)
5990 #ifndef IDLESLEEPCONTROL_DISABLED
5991 mDNSBool allowSleep
= mDNStrue
;
5996 if (m
->SystemSleepOnlyIfWakeOnLAN
)
5998 // Don't sleep if we are a proxy for any services
5999 if (m
->ProxyRecords
)
6001 allowSleep
= mDNSfalse
;
6002 mDNS_snprintf(reason
, sizeof(reason
), "sleep proxy for %d records", m
->ProxyRecords
);
6003 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m
->ProxyRecords
);
6006 if (allowSleep
&& mDNSCoreHaveAdvertisedMulticastServices(m
))
6008 // Scan the list of active interfaces
6009 NetworkInterfaceInfo
*intf
;
6010 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6012 if (intf
->McastTxRx
&& !intf
->Loopback
&& !mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
6014 // Disallow sleep if this interface doesn't support NetWake
6017 allowSleep
= mDNSfalse
;
6018 mDNS_snprintf(reason
, sizeof(reason
), "%s does not support NetWake", intf
->ifname
);
6019 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf
->ifname
);
6023 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
6024 // that will be offloaded. If not, we should prevent sleep.
6025 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
6026 #if APPLE_OSX_mDNSResponder
6027 if (!SupportsInNICProxy(intf
))
6030 // Disallow sleep if there is no sleep proxy server
6031 const CacheRecord
*cr
= FindSPSInCache1(m
, &intf
->NetWakeBrowse
, mDNSNULL
, mDNSNULL
);
6032 if ( cr
== mDNSNULL
)
6034 allowSleep
= mDNSfalse
;
6035 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server on %s", intf
->ifname
);
6036 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf
->ifname
);
6039 else if (m
->SPSType
!= 0)
6041 mDNSu32 mymetric
= LocalSPSMetric(m
);
6042 mDNSu32 metric
= SPSMetric(cr
->resrec
.rdata
->u
.name
.c
);
6043 if (metric
>= mymetric
)
6045 allowSleep
= mDNSfalse
;
6046 mDNS_snprintf(reason
, sizeof(reason
), "No sleep proxy server with better metric on %s", intf
->ifname
);
6047 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf
->ifname
);
6057 // Call the platform code to enable/disable sleep
6058 mDNSPlatformSetAllowSleep(allowSleep
, reason
);
6061 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6064 mDNSlocal mDNSBool
mDNSUpdateOkToSend(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSu32 scopeid
)
6066 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6067 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6069 if (AuthRecord_uDNS(rr
) || (rr
->AuthFlags
& AuthFlagsWakeOnly
) || mDNSOpaque16IsZero(rr
->updateid
) ||
6070 m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) < 0)
6075 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6076 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6077 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6078 // updateid and we should have returned from above.
6080 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6081 // platform function to extract the value from "intf" every time.
6083 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6084 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6090 mDNSexport
void UpdateRMAC(mDNS
*const m
, void *context
)
6092 IPAddressMACMapping
*addrmap
= (IPAddressMACMapping
*)context
;
6093 m
->CurrentRecord
= m
->ResourceRecords
;
6097 LogMsg("UpdateRMAC: Address mapping is NULL");
6101 while (m
->CurrentRecord
)
6103 AuthRecord
*rr
= m
->CurrentRecord
;
6104 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6105 if (!rr
->WakeUp
.HMAC
.l
[0] && mDNS_KeepaliveRecord(&rr
->resrec
))
6108 getKeepaliveRaddr(m
, rr
, &raddr
);
6109 if (mDNSSameAddress(&raddr
, &addrmap
->ipaddr
))
6111 // Update the MAC address only if it is not a zero MAC address
6112 mDNSEthAddr macAddr
;
6113 mDNSu8
*ptr
= GetValueForMACAddr((mDNSu8
*)(addrmap
->ethaddr
), (mDNSu8
*) (addrmap
->ethaddr
+ sizeof(addrmap
->ethaddr
)), &macAddr
);
6114 if (ptr
!= mDNSNULL
&& !mDNSEthAddressIsZero(macAddr
))
6116 UpdateKeepaliveRData(m
, rr
, mDNSNULL
, mDNStrue
, (char *)(addrmap
->ethaddr
));
6120 m
->CurrentRecord
= rr
->next
;
6124 mDNSPlatformMemFree(addrmap
);
6128 mDNSexport mStatus
UpdateKeepaliveRData(mDNS
*const m
, AuthRecord
*rr
, NetworkInterfaceInfo
*const intf
, mDNSBool updateMac
, char *ethAddr
)
6130 mDNSu16 newrdlength
;
6131 mDNSAddr laddr
= zeroAddr
;
6132 mDNSAddr raddr
= zeroAddr
;
6133 mDNSEthAddr eth
= zeroEthAddr
;
6134 mDNSIPPort lport
= zeroIPPort
;
6135 mDNSIPPort rport
= zeroIPPort
;
6136 mDNSu32 timeout
= 0;
6146 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6147 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6148 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
6149 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
))
6151 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m
, rr
), &laddr
, lport
.NotAnInteger
, &raddr
, rport
.NotAnInteger
);
6152 return mStatus_UnknownErr
;
6157 if (laddr
.type
== mDNSAddrType_IPv4
)
6158 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
);
6160 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
);
6165 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6166 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6167 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6168 mDNSPlatformMemZero(&mti
, sizeof (mDNSTCPInfo
));
6169 ret
= mDNSPlatformRetrieveTCPInfo(&laddr
, &lport
, &raddr
, &rport
, &mti
);
6170 if (ret
!= mStatus_NoError
)
6172 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret
);
6175 if ((intf
!= mDNSNULL
) && (mti
.IntfId
!= intf
->InterfaceID
))
6177 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti
.IntfId
, intf
->InterfaceID
);
6178 return mStatus_BadParamErr
;
6181 if (laddr
.type
== mDNSAddrType_IPv4
)
6182 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
);
6184 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
);
6187 // Did we insert a null byte at the end ?
6188 if (newrdlength
== (sizeof(txt
.c
) - 1))
6190 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m
, rr
));
6191 return mStatus_NoMemoryErr
;
6194 // Include the length for the null byte at the end
6195 txt
.c
[0] = newrdlength
+ 1;
6196 // Account for the first length byte and the null byte at the end
6199 rdsize
= newrdlength
> sizeof(RDataBody
) ? newrdlength
: sizeof(RDataBody
);
6200 newrd
= (RData
*) mDNSPlatformMemAllocate(sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
6201 if (!newrd
) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr
; }
6203 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
6204 mDNSPlatformMemCopy(&newrd
->u
, txt
.c
, newrdlength
);
6206 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6207 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6208 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6209 // free that memory here before copying in the new data.
6210 if ( rr
->resrec
.rdata
!= &rr
->rdatastorage
)
6212 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m
, rr
));
6213 mDNSPlatformMemFree(rr
->resrec
.rdata
);
6215 SetNewRData(&rr
->resrec
, newrd
, newrdlength
); // Update our rdata
6217 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m
, rr
));
6218 return mStatus_NoError
;
6221 mDNSlocal
void SendSPSRegistrationForOwner(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
, const OwnerOptData
*const owner
)
6223 const int optspace
= DNSOpt_Header_Space
+ DNSOpt_LeaseData_Space
+ DNSOpt_Owner_Space(&m
->PrimaryMAC
, &intf
->MAC
);
6224 const int sps
= intf
->NextSPSAttempt
/ 3;
6229 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6230 if (!intf
->SPSAddr
[sps
].type
)
6232 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6233 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
6234 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
6235 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf
->ifname
, intf
->NextSPSAttempt
, sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6239 // Mark our mDNS records (not unicast records) for transfer to SPS
6240 if (mDNSOpaque16IsZero(id
))
6242 // We may have to register this record over multiple interfaces and we don't want to
6243 // overwrite the id. We send the registration over interface X with id "IDX" and before
6244 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6245 // for "IDX". Hence, we want to use the same ID across all interfaces.
6247 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6248 // option check below will set the same ID across the records from the same owner. Records
6249 // with different owner option gets different ID.
6250 msgid
= mDNS_NewMessageID(m
);
6251 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6253 if (!(rr
->AuthFlags
& AuthFlagsWakeOnly
) && rr
->resrec
.RecordType
> kDNSRecordTypeDeregistering
)
6255 if (rr
->resrec
.InterfaceID
== intf
->InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
6257 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6259 rr
->SendRNow
= mDNSInterfaceMark
; // mark it now
6260 // When we are registering on the first interface, rr->updateid is zero in which case
6261 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6262 // At the end, all the updates sent across all the interfaces with the same ID.
6263 if (mDNSOpaque16IsZero(rr
->updateid
))
6264 rr
->updateid
= msgid
;
6266 msgid
= rr
->updateid
;
6277 mDNSu8
*p
= m
->omsg
.data
;
6278 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6279 // For now we follow that same logic for SPS registrations too.
6280 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6281 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6282 InitializeDNSMessage(&m
->omsg
.h
, msgid
, UpdateReqFlags
);
6284 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6285 if (rr
->SendRNow
|| mDNSUpdateOkToSend(m
, rr
, intf
, scopeid
))
6287 if (mDNSPlatformMemSame(owner
, &rr
->WakeUp
, sizeof(*owner
)))
6290 const mDNSu8
*const limit
= m
->omsg
.data
+ (m
->omsg
.h
.mDNS_numUpdates
? NormalMaxDNSMessageData
: AbsoluteMaxDNSMessageData
) - optspace
;
6292 // If we can't update the keepalive record, don't send it
6293 if (mDNS_KeepaliveRecord(&rr
->resrec
) && (UpdateKeepaliveRData(m
, rr
, intf
, mDNSfalse
, mDNSNULL
) != mStatus_NoError
))
6295 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
6297 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
6299 rr
->SendRNow
= mDNSNULL
;
6303 if (rr
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)
6304 rr
->resrec
.rrclass
|= kDNSClass_UniqueRRSet
; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6305 newptr
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.mDNS_numUpdates
, &rr
->resrec
, rr
->resrec
.rroriginalttl
, limit
);
6306 rr
->resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
; // Make sure to clear 'unique' bit back to normal state
6308 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf
->ifname
, p
- m
->omsg
.data
, limit
- m
->omsg
.data
, ARDisplayString(m
, rr
));
6311 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
));
6312 rr
->SendRNow
= mDNSNULL
;
6313 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
6314 rr
->LastAPTime
= m
->timenow
;
6315 // should be initialized above
6316 if (mDNSOpaque16IsZero(rr
->updateid
)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m
, rr
));
6317 if (m
->NextScheduledResponse
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6318 m
->NextScheduledResponse
= (rr
->LastAPTime
+ rr
->ThisAPInterval
);
6324 if (!m
->omsg
.h
.mDNS_numUpdates
) break;
6328 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
6329 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
6330 opt
.resrec
.rdlength
= sizeof(rdataOPT
) * 2; // Two options in this OPT record
6331 opt
.resrec
.rdestimate
= sizeof(rdataOPT
) * 2;
6332 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
6333 opt
.resrec
.rdata
->u
.opt
[0].optlen
= DNSOpt_LeaseData_Space
- 4;
6334 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= DEFAULT_UPDATE_LEASE
;
6335 if (!owner
->HMAC
.l
[0]) // If no owner data,
6336 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[1]); // use our own interface information
6337 else // otherwise, use the owner data we were given
6339 opt
.resrec
.rdata
->u
.opt
[1].u
.owner
= *owner
;
6340 opt
.resrec
.rdata
->u
.opt
[1].opt
= kDNSOpt_Owner
;
6341 opt
.resrec
.rdata
->u
.opt
[1].optlen
= DNSOpt_Owner_Space(&owner
->HMAC
, &owner
->IMAC
) - 4;
6343 LogSPS("SendSPSRegistration put %s %s", intf
->ifname
, ARDisplayString(m
, &opt
));
6344 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
6346 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m
->omsg
.h
.mDNS_numUpdates
, ARDisplayString(m
, &opt
));
6351 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf
->ifname
, intf
->NextSPSAttempt
, sps
,
6352 mDNSVal16(m
->omsg
.h
.id
), m
->omsg
.h
.mDNS_numUpdates
, p
- m
->omsg
.data
, &intf
->SPSAddr
[sps
], mDNSVal16(intf
->SPSPort
[sps
]));
6353 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6354 err
= mDNSSendDNSMessage(m
, &m
->omsg
, p
, intf
->InterfaceID
, mDNSNULL
, mDNSNULL
, &intf
->SPSAddr
[sps
], intf
->SPSPort
[sps
], mDNSNULL
, mDNSfalse
);
6355 if (err
) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err
);
6356 if (err
&& intf
->SPSAddr
[sps
].type
== mDNSAddrType_IPv4
&& intf
->NetWakeResolve
[sps
].ThisQInterval
== -1)
6358 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps
, intf
->NetWakeResolve
[sps
].qname
.c
);
6359 intf
->NetWakeResolve
[sps
].qtype
= kDNSType_AAAA
;
6360 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[sps
]);
6367 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
* 10; // If successful, update NextSPSAttemptTime
6370 if (mDNSOpaque16IsZero(id
) && intf
->NextSPSAttempt
< 8) intf
->NextSPSAttempt
++;
6373 mDNSlocal mDNSBool
RecordIsFirstOccurrenceOfOwner(mDNS
*const m
, const AuthRecord
*const rr
)
6376 for (ar
= m
->ResourceRecords
; ar
&& ar
!= rr
; ar
=ar
->next
)
6377 if (mDNSPlatformMemSame(&rr
->WakeUp
, &ar
->WakeUp
, sizeof(rr
->WakeUp
))) return mDNSfalse
;
6381 mDNSlocal
void mDNSCoreStoreProxyRR(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, AuthRecord
*const rr
)
6383 AuthRecord
*newRR
= (AuthRecord
*) mDNSPlatformMemAllocateClear(sizeof(*newRR
));
6384 if (newRR
== mDNSNULL
)
6386 LogSPS("%s : could not allocate memory for new resource record", __func__
);
6390 mDNS_SetupResourceRecord(newRR
, mDNSNULL
, InterfaceID
, rr
->resrec
.rrtype
,
6391 rr
->resrec
.rroriginalttl
, rr
->resrec
.RecordType
,
6392 rr
->ARType
, mDNSNULL
, mDNSNULL
);
6394 AssignDomainName(&newRR
->namestorage
, &rr
->namestorage
);
6395 newRR
->resrec
.rdlength
= DomainNameLength(rr
->resrec
.name
);
6396 newRR
->resrec
.namehash
= DomainNameHashValue(newRR
->resrec
.name
);
6397 newRR
->resrec
.rrclass
= rr
->resrec
.rrclass
;
6399 if (rr
->resrec
.rrtype
== kDNSType_A
)
6401 newRR
->resrec
.rdata
->u
.ipv4
= rr
->resrec
.rdata
->u
.ipv4
;
6403 else if (rr
->resrec
.rrtype
== kDNSType_AAAA
)
6405 newRR
->resrec
.rdata
->u
.ipv6
= rr
->resrec
.rdata
->u
.ipv6
;
6407 SetNewRData(&newRR
->resrec
, mDNSNULL
, 0);
6409 // Insert the new node at the head of the list.
6410 newRR
->next
= m
->SPSRRSet
;
6411 m
->SPSRRSet
= newRR
;
6412 LogSPS("%s : Storing proxy record : %s ", __func__
, ARDisplayString(m
, rr
));
6415 // Some records are interface specific and some are not. The ones that are supposed to be registered
6416 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6417 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6418 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6419 // registration on all the interfaces
6420 mDNSlocal
void SPSInitRecordsBeforeUpdate(mDNS
*const m
, mDNSOpaque64 updateIntID
, mDNSBool
*WakeOnlyService
)
6423 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID
.l
[1], updateIntID
.l
[0]);
6425 *WakeOnlyService
= mDNSfalse
;
6427 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6428 // make sure that the old sleep proxy records are removed.
6429 mDNSCoreFreeProxyRR(m
);
6431 // For records that are registered only on a specific interface, mark only that bit as it will
6432 // never be registered on any other interface. For others, it should be sent on all interfaces.
6433 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6435 ar
->updateIntID
= zeroOpaque64
;
6436 ar
->updateid
= zeroID
;
6437 if (AuthRecord_uDNS(ar
))
6441 if (ar
->AuthFlags
& AuthFlagsWakeOnly
)
6443 if (ar
->resrec
.RecordType
== kDNSRecordTypeShared
&& ar
->RequireGoodbye
)
6445 ar
->ImmedAnswer
= mDNSInterfaceMark
;
6446 *WakeOnlyService
= mDNStrue
;
6450 if (!ar
->resrec
.InterfaceID
)
6452 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID
.l
[1], updateIntID
.l
[0], ARDisplayString(m
, ar
));
6453 ar
->updateIntID
= updateIntID
;
6457 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6459 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, ar
->resrec
.InterfaceID
, mDNStrue
);
6460 if ((scopeid
< (sizeof(updateIntID
) * mDNSNBBY
)) && bit_get_opaque64(updateIntID
, scopeid
))
6462 bit_set_opaque64(ar
->updateIntID
, scopeid
);
6463 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid
, ar
->updateIntID
.l
[1],
6464 ar
->updateIntID
.l
[0], ARDisplayString(m
, ar
));
6468 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid
);
6471 // Store the A and AAAA records that we registered with the sleep proxy.
6472 // We will use this to prevent spurious name conflicts that may occur when we wake up
6473 if (ar
->resrec
.rrtype
== kDNSType_A
|| ar
->resrec
.rrtype
== kDNSType_AAAA
)
6475 mDNSCoreStoreProxyRR(m
, ar
->resrec
.InterfaceID
, ar
);
6480 mDNSlocal
void SendSPSRegistration(mDNS
*const m
, NetworkInterfaceInfo
*const intf
, const mDNSOpaque16 id
)
6483 OwnerOptData owner
= zeroOwner
;
6485 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6487 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
6489 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)) && RecordIsFirstOccurrenceOfOwner(m
, ar
))
6492 SendSPSRegistrationForOwner(m
, intf
, id
, &owner
);
6497 // RetrySPSRegistrations is called from SendResponses, with the lock held
6498 mDNSlocal
void RetrySPSRegistrations(mDNS
*const m
)
6501 NetworkInterfaceInfo
*intf
;
6503 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6504 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6505 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10)
6506 intf
->NextSPSAttemptTime
++;
6508 // Retry any record registrations that are due
6509 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6510 if (!AuthRecord_uDNS(rr
) && !mDNSOpaque16IsZero(rr
->updateid
) && m
->timenow
- (rr
->LastAPTime
+ rr
->ThisAPInterval
) >= 0)
6512 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6514 // If we still have registrations pending on this interface, send it now
6515 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6516 if ((scopeid
>= (sizeof(rr
->updateIntID
) * mDNSNBBY
) || bit_get_opaque64(rr
->updateIntID
, scopeid
)) &&
6517 (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== intf
->InterfaceID
))
6519 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr
->updateIntID
.l
[1], rr
->updateIntID
.l
[0], mDNSVal16(rr
->updateid
), ARDisplayString(m
, rr
));
6520 SendSPSRegistration(m
, intf
, rr
->updateid
);
6525 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6526 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6527 if (intf
->NextSPSAttempt
&& intf
->NextSPSAttemptTime
== m
->timenow
+ mDNSPlatformOneSecond
* 10 && intf
->NextSPSAttempt
< 8)
6528 intf
->NextSPSAttempt
++;
6531 mDNSlocal
void NetWakeResolve(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
6533 NetworkInterfaceInfo
*intf
= (NetworkInterfaceInfo
*)question
->QuestionContext
;
6534 int sps
= (int)(question
- intf
->NetWakeResolve
);
6536 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps
, AddRecord
, RRDisplayString(m
, answer
));
6538 if (!AddRecord
) return; // Don't care about REMOVE events
6539 if (answer
->rrtype
!= question
->qtype
) return; // Don't care about CNAMEs
6541 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6543 if (answer
->rrtype
== kDNSType_SRV
)
6545 // 1. Got the SRV record; now look up the target host's IP address
6546 mDNS_StopQuery(m
, question
);
6547 intf
->SPSPort
[sps
] = answer
->rdata
->u
.srv
.port
;
6548 AssignDomainName(&question
->qname
, &answer
->rdata
->u
.srv
.target
);
6549 question
->qtype
= kDNSType_A
;
6550 mDNS_StartQuery(m
, question
);
6552 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== sizeof(mDNSv4Addr
))
6554 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6555 mDNS_StopQuery(m
, question
);
6556 question
->ThisQInterval
= -1;
6557 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv4
;
6558 intf
->SPSAddr
[sps
].ip
.v4
= answer
->rdata
->u
.ipv4
;
6560 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6563 else if (answer
->rrtype
== kDNSType_A
&& answer
->rdlength
== 0)
6565 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6566 mDNS_StopQuery(m
, question
);
6567 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps
, question
->qname
.c
);
6568 question
->qtype
= kDNSType_AAAA
;
6569 mDNS_StartQuery(m
, question
);
6571 else if (answer
->rrtype
== kDNSType_AAAA
&& answer
->rdlength
== sizeof(mDNSv6Addr
) && mDNSv6AddressIsLinkLocal(&answer
->rdata
->u
.ipv6
))
6573 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6574 mDNS_StopQuery(m
, question
);
6575 question
->ThisQInterval
= -1;
6576 intf
->SPSAddr
[sps
].type
= mDNSAddrType_IPv6
;
6577 intf
->SPSAddr
[sps
].ip
.v6
= answer
->rdata
->u
.ipv6
;
6579 if (sps
== intf
->NextSPSAttempt
/3) SendSPSRegistration(m
, intf
, zeroID
); // If we're ready for this result, use it now
6584 mDNSexport mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
)
6587 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6588 if (mDNS_KeepaliveRecord(&rr
->resrec
) || (rr
->resrec
.rrtype
== kDNSType_SRV
&& !AuthRecord_uDNS(rr
) && !mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, DiscardPort
)))
6593 #define WAKE_ONLY_SERVICE 1
6594 #define AC_ONLY_SERVICE 2
6596 #ifdef APPLE_OSX_mDNSResponder
6597 mDNSlocal
void SendGoodbyesForSelectServices(mDNS
*const m
, mDNSBool
*servicePresent
, mDNSu32 serviceType
)
6600 *servicePresent
= mDNSfalse
;
6602 // Mark all the records we need to deregister and send them
6603 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6605 // If the service type is wake only service and the auth flags match and requires a goodbye
6606 // OR if the service type is AC only and it is not a keepalive record,
6607 // mark the records we need to deregister and send them
6608 if ((serviceType
== WAKE_ONLY_SERVICE
&& (rr
->AuthFlags
& AuthFlagsWakeOnly
) &&
6609 rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
) ||
6610 (serviceType
== AC_ONLY_SERVICE
&& !mDNS_KeepaliveRecord(&rr
->resrec
)))
6612 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6613 *servicePresent
= mDNStrue
;
6619 #ifdef APPLE_OSX_mDNSResponder
6620 // This function is used only in the case of local NIC proxy. For external
6621 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6622 // walk the resource records.
6623 mDNSlocal
void SendGoodbyesForWakeOnlyService(mDNS
*const m
, mDNSBool
*WakeOnlyService
)
6625 return SendGoodbyesForSelectServices(m
, WakeOnlyService
, WAKE_ONLY_SERVICE
);
6627 #endif // APPLE_OSX_mDNSResponder
6630 mDNSlocal
void SendSleepGoodbyes(mDNS
*const m
, mDNSBool AllInterfaces
, mDNSBool unicast
)
6633 m
->SleepState
= SleepState_Sleeping
;
6635 // If AllInterfaces is not set, the caller has already marked it appropriately
6636 // on which interfaces this should be sent.
6639 NetworkInterfaceInfo
*intf
;
6640 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6642 intf
->SendGoodbyes
= 1;
6647 #ifndef UNICAST_DISABLED
6648 SleepRecordRegistrations(m
); // If we have no SPS, need to deregister our uDNS records
6649 #endif /* UNICAST_DISABLED */
6652 // Mark all the records we need to deregister and send them
6653 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
6654 if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
&& rr
->RequireGoodbye
)
6655 rr
->ImmedAnswer
= mDNSInterfaceMark
;
6660 * This function attempts to detect if multiple interfaces are on the same subnet.
6661 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6662 * IPv6 link local addresses that are configured by default on all interfaces make
6663 * it hard to make this determination
6665 * The 'real' fix for this would be to send out multicast packets over one interface
6666 * and conclude that multiple interfaces are on the same subnet only if these packets
6667 * are seen on other interfaces on the same system
6669 mDNSlocal mDNSBool
skipSameSubnetRegistration(mDNS
*const m
, mDNSInterfaceID
*regID
, mDNSu32 count
, mDNSInterfaceID intfid
)
6671 NetworkInterfaceInfo
*intf
;
6672 NetworkInterfaceInfo
*newIntf
;
6675 for (newIntf
= FirstInterfaceForID(m
, intfid
); newIntf
; newIntf
= newIntf
->next
)
6677 if ((newIntf
->InterfaceID
!= intfid
) ||
6678 (newIntf
->ip
.type
!= mDNSAddrType_IPv4
))
6682 for ( i
= 0; i
< count
; i
++)
6684 for (intf
= FirstInterfaceForID(m
, regID
[i
]); intf
; intf
= intf
->next
)
6686 if ((intf
->InterfaceID
!= regID
[i
]) ||
6687 (intf
->ip
.type
!= mDNSAddrType_IPv4
))
6691 if ((intf
->ip
.ip
.v4
.NotAnInteger
& intf
->mask
.ip
.v4
.NotAnInteger
) == (newIntf
->ip
.ip
.v4
.NotAnInteger
& newIntf
->mask
.ip
.v4
.NotAnInteger
))
6693 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__
, intf
->ifname
);
6702 mDNSlocal
void DoKeepaliveCallbacks(mDNS
*m
)
6704 // Loop through the keepalive records and callback with an error
6705 m
->CurrentRecord
= m
->ResourceRecords
;
6706 while (m
->CurrentRecord
)
6708 AuthRecord
*const rr
= m
->CurrentRecord
;
6709 if ((mDNS_KeepaliveRecord(&rr
->resrec
)) && (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
))
6711 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m
, rr
));
6712 if (rr
->RecordCallback
)
6713 rr
->RecordCallback(m
, rr
, mStatus_BadStateErr
);
6715 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
6716 m
->CurrentRecord
= rr
->next
;
6720 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6721 mDNSlocal
void BeginSleepProcessing(mDNS
*const m
)
6723 mDNSBool SendGoodbyes
= mDNStrue
;
6724 mDNSBool WakeOnlyService
= mDNSfalse
;
6725 mDNSBool invokeKACallback
= mDNStrue
;
6726 const CacheRecord
*sps
[3] = { mDNSNULL
};
6727 mDNSOpaque64 updateIntID
= zeroOpaque64
;
6728 mDNSInterfaceID registeredIntfIDS
[128] = { 0 };
6729 mDNSu32 registeredCount
= 0;
6730 int skippedRegistrations
= 0;
6732 m
->NextScheduledSPRetry
= m
->timenow
;
6734 // Clear out the SCDynamic entry that stores the external SPS information
6735 mDNSPlatformClearSPSData();
6737 if (!m
->SystemWakeOnLANEnabled
) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6738 else if (!mDNSCoreHaveAdvertisedMulticastServices(m
)) LogSPS("BeginSleepProcessing: No advertised services");
6739 else // If we have at least one advertised service
6741 NetworkInterfaceInfo
*intf
;
6742 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
6744 mDNSBool skipFullSleepProxyRegistration
= mDNSfalse
;
6745 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6746 intf
->SendGoodbyes
= 0;
6748 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6750 if (!intf
->McastTxRx
|| mDNSPlatformInterfaceIsD2D(intf
->InterfaceID
))
6752 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf
->ifname
);
6756 // If we are not capable of WOMP, then don't register with sleep proxy.
6758 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6759 // We might find sleep proxy servers in the cache and start a resolve on them.
6760 // But then if the interface goes away, we won't stop these questions because
6761 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6762 // to stop both the browse and resolve questions.
6765 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf
->ifname
);
6766 intf
->SendGoodbyes
= 1;
6767 skippedRegistrations
++;
6771 // Check if we have already registered with a sleep proxy for this subnet.
6772 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6773 // to the interface.
6774 if (skipSameSubnetRegistration(m
, registeredIntfIDS
, registeredCount
, intf
->InterfaceID
))
6776 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__
, intf
->ifname
);
6777 skipFullSleepProxyRegistration
= mDNStrue
;
6780 #if APPLE_OSX_mDNSResponder
6781 if (SupportsInNICProxy(intf
))
6783 mDNSBool keepaliveOnly
= mDNSfalse
;
6784 const mStatus err
= ActivateLocalProxy(intf
, skipFullSleepProxyRegistration
, &keepaliveOnly
);
6785 if (!skipFullSleepProxyRegistration
&& !err
)
6787 SendGoodbyesForWakeOnlyService(m
, &WakeOnlyService
);
6789 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6790 SendGoodbyes
= (keepaliveOnly
) ? mDNStrue
: mDNSfalse
;
6791 invokeKACallback
= mDNSfalse
;
6792 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf
->ifname
);
6793 // This will leave m->SleepState set to SleepState_Transferring,
6794 // which is okay because with no outstanding resolves, or updates in flight,
6795 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6797 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6802 #endif // APPLE_OSX_mDNSResponder
6803 if (!skipFullSleepProxyRegistration
)
6805 #if APPLE_OSX_mDNSResponder
6806 // If on battery, do not attempt to offload to external sleep proxies
6807 if (m
->SystemWakeOnLANEnabled
== mDNS_WakeOnBattery
)
6809 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6812 #endif // APPLE_OSX_mDNSResponder
6813 FindSPSInCache(m
, &intf
->NetWakeBrowse
, sps
);
6814 if (!sps
[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6815 intf
->ifname
, &intf
->ip
, NextQSendTime(&intf
->NetWakeBrowse
) - m
->timenow
, intf
->NetWakeBrowse
.ThisQInterval
);
6820 SendGoodbyes
= mDNSfalse
;
6821 intf
->NextSPSAttempt
= 0;
6822 intf
->NextSPSAttemptTime
= m
->timenow
+ mDNSPlatformOneSecond
;
6824 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, intf
->InterfaceID
, mDNStrue
);
6825 // Now we know for sure that we have to wait for registration to complete on this interface.
6826 if (scopeid
< (sizeof(updateIntID
) * mDNSNBBY
))
6827 bit_set_opaque64(updateIntID
, scopeid
);
6829 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6833 if (intf
->SPSAddr
[i
].type
)
6834 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf
->ifname
, i
, intf
->SPSAddr
[i
].type
);
6835 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0)
6836 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf
->ifname
, i
, intf
->NetWakeResolve
[i
].ThisQInterval
);
6838 intf
->SPSAddr
[i
].type
= mDNSAddrType_None
;
6839 if (intf
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery(m
, &intf
->NetWakeResolve
[i
]);
6840 intf
->NetWakeResolve
[i
].ThisQInterval
= -1;
6843 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf
->ifname
, i
, sps
[i
]->resrec
.rroriginalttl
, CRDisplayString(m
, sps
[i
]));
6844 mDNS_SetupQuestion(&intf
->NetWakeResolve
[i
], intf
->InterfaceID
, &sps
[i
]->resrec
.rdata
->u
.name
, kDNSType_SRV
, NetWakeResolve
, intf
);
6845 intf
->NetWakeResolve
[i
].ReturnIntermed
= mDNStrue
;
6846 mDNS_StartQuery_internal(m
, &intf
->NetWakeResolve
[i
]);
6848 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6849 registeredIntfIDS
[registeredCount
] = intf
->InterfaceID
;
6858 // If we have at least one interface on which we are registering with an external sleep proxy,
6859 // initialize all the records appropriately.
6860 if (!mDNSOpaque64IsZero(&updateIntID
))
6861 SPSInitRecordsBeforeUpdate(m
, updateIntID
, &WakeOnlyService
);
6863 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6864 // the records to a sleep proxy.
6865 if (invokeKACallback
)
6867 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6868 DoKeepaliveCallbacks(m
);
6871 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6872 // interfaces and also deregister unicast registrations.
6874 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6875 // for both multicast and unicast.
6877 // - If we skipped registrations on some interfaces, then we have already marked
6878 // them appropriately above. We don't need to send goodbyes for unicast as
6879 // we have registered with at least one sleep proxy.
6881 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6883 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6884 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6885 // at WakeOnlyServices first.
6888 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6889 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
6891 else if (skippedRegistrations
)
6893 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6894 SendSleepGoodbyes(m
, mDNSfalse
, mDNSfalse
);
6896 else if (WakeOnlyService
)
6898 // If we saw WakeOnly service above, send the goodbyes now.
6899 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6904 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6905 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6906 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6907 mDNSexport
void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool sleep
)
6911 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_INFO
,
6912 PUB_S
" (old state %d) at %d", sleep
? "Sleeping" : "Waking", m
->SleepState
, m
->timenow
);
6914 if (sleep
&& !m
->SleepState
) // Going to sleep
6917 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6920 mDNSu8 oldstate
= m
->SPSState
;
6921 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6923 #ifndef SPC_DISABLED
6924 if (oldstate
== 1) mDNS_DeregisterService(m
, &m
->SPSRecords
);
6928 mDNS_ReclaimLockAfterCallback();
6930 #ifdef _LEGACY_NAT_TRAVERSAL_
6933 mDNSPlatformUDPClose(m
->SSDPSocket
);
6934 m
->SSDPSocket
= mDNSNULL
;
6937 m
->SleepState
= SleepState_Transferring
;
6938 if (m
->SystemWakeOnLANEnabled
&& m
->DelaySleep
)
6940 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6941 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
6942 "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m
->DelaySleep
- m
->timenow
);
6943 m
->SleepLimit
= NonZeroTime(m
->DelaySleep
+ mDNSPlatformOneSecond
* 10);
6948 m
->SleepLimit
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 10);
6949 m
->mDNSStats
.Sleeps
++;
6950 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
6951 Querier_HandleSleep();
6953 BeginSleepProcessing(m
);
6956 #ifndef UNICAST_DISABLED
6959 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S
") seq %d",
6961 m
->SleepState
== SleepState_Transferring
? "Transferring" :
6962 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?", m
->SleepSeqNum
);
6965 else if (!sleep
) // Waking up
6970 NetworkInterfaceInfo
*intf
;
6971 mDNSs32 currtime
, diff
;
6974 // Reset SleepLimit back to 0 now that we're awake again.
6977 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6978 if (m
->SleepState
!= SleepState_Awake
)
6980 m
->SleepState
= SleepState_Awake
;
6982 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6983 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6984 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6985 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6986 m
->DelaySleep
= NonZeroTime(m
->timenow
+ kDarkWakeDelaySleep
);
6989 if (m
->SPSState
== 3)
6992 mDNSCoreBeSleepProxyServer_internal(m
, m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
);
6994 m
->mDNSStats
.Wakes
++;
6995 // ... and the same for NextSPSAttempt
6996 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
)) intf
->NextSPSAttempt
= -1;
6998 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
6999 Querier_HandleWake();
7001 // Restart unicast and multicast queries
7002 mDNSCoreRestartQueries(m
);
7004 // and reactivtate service registrations
7005 m
->NextSRVUpdate
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
7006 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7007 "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m
->NextSRVUpdate
- m
->timenow
, m
->timenow
);
7009 // 2. Re-validate our cache records
7010 currtime
= mDNSPlatformUTC();
7012 diff
= currtime
- m
->TimeSlept
;
7013 FORALL_CACHERECORDS(slot
, cg
, cr
)
7015 // Temporary fix: For unicast cache records, look at how much time we slept.
7016 // Adjust the RecvTime by the amount of time we slept so that we age the
7017 // cache record appropriately. If it is expired already, purge. If there
7018 // is a network change that happens after the wakeup, we might purge the
7019 // cache anyways and this helps only in the case where there are no network
7020 // changes across sleep/wakeup transition.
7022 // Note: If there is a network/DNS server change that already happened and
7023 // these cache entries are already refreshed and we are getting a delayed
7024 // wake up notification, we might adjust the TimeRcvd based on the time slept
7025 // now which can cause the cache to purge pre-maturely. As this is not a very
7026 // common case, this should happen rarely.
7027 if (!cr
->resrec
.InterfaceID
)
7031 mDNSu32 uTTL
= RRUnadjustedTTL(cr
->resrec
.rroriginalttl
);
7032 const mDNSs32 remain
= uTTL
- (m
->timenow
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
7034 // -if we have slept longer than the remaining TTL, purge and start fresh.
7035 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
7036 // a sufficiently big value which could cause the value to go into the future
7037 // because of the signed comparison of time. For this to happen, we should have been
7038 // sleeping really long (~24 days). For now, we want to be conservative and flush even
7039 // if we have slept for more than two days.
7041 if (diff
>= remain
|| diff
> (2 * 24 * 3600))
7043 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7044 "mDNSCoreMachineSleep: " PRI_S
": Purging cache entry SleptTime %d, Remaining TTL %d",
7045 CRDisplayString(m
, cr
), diff
, remain
);
7046 mDNS_PurgeCacheResourceRecord(m
, cr
);
7049 cr
->TimeRcvd
-= (diff
* mDNSPlatformOneSecond
);
7050 if (m
->timenow
- (cr
->TimeRcvd
+ ((mDNSs32
)uTTL
* mDNSPlatformOneSecond
)) >= 0)
7052 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7053 "mDNSCoreMachineSleep: " PRI_S
": Purging after adjusting the remaining TTL %d by %d seconds",
7054 CRDisplayString(m
, cr
), remain
, diff
);
7055 mDNS_PurgeCacheResourceRecord(m
, cr
);
7059 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
,
7060 "mDNSCoreMachineSleep: " PRI_S
": Adjusted the remain ttl %u by %d seconds",
7061 CRDisplayString(m
, cr
), remain
, diff
);
7067 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForWake
);
7071 // 3. Retrigger probing and announcing for all our authoritative records
7072 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7074 if (AuthRecord_uDNS(rr
))
7076 ActivateUnicastRegistration(m
, rr
);
7080 mDNSCoreRestartRegistration(m
, rr
, -1);
7084 // 4. Refresh NAT mappings
7085 // We don't want to have to assume that all hardware can necessarily keep accurate
7086 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7087 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7088 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7089 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7090 // than five seconds from now.
7091 LogRedact(MDNS_LOG_CATEGORY_SPS
, MDNS_LOG_DEBUG
, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7092 RecreateNATMappings(m
, mDNSPlatformOneSecond
* 5);
7097 mDNSexport mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
)
7101 NetworkInterfaceInfo
*intf
;
7105 if (m
->DelaySleep
) goto notready
;
7107 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7108 if (m
->SleepLimit
- now
> 0 && m
->NextScheduledSPRetry
- now
> 0) goto notready
;
7110 m
->NextScheduledSPRetry
= now
+ 0x40000000UL
;
7112 // See if we might need to retransmit any lost Sleep Proxy Registrations
7113 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7114 if (intf
->NextSPSAttempt
>= 0)
7116 if (now
- intf
->NextSPSAttemptTime
>= 0)
7118 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7119 intf
->ifname
, intf
->NextSPSAttempt
/3, intf
->NextSPSAttempt
);
7120 SendSPSRegistration(m
, intf
, zeroID
);
7121 // Don't need to "goto notready" here, because if we do still have record registrations
7122 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7125 if (m
->NextScheduledSPRetry
- intf
->NextSPSAttemptTime
> 0)
7126 m
->NextScheduledSPRetry
= intf
->NextSPSAttemptTime
;
7129 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7130 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7132 int sps
= (intf
->NextSPSAttempt
== 0) ? 0 : (intf
->NextSPSAttempt
-1)/3;
7133 if (intf
->NetWakeResolve
[sps
].ThisQInterval
>= 0)
7135 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7136 intf
->ifname
, intf
->NetWakeResolve
[sps
].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[sps
].qtype
));
7141 // Scan list of registered records
7142 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7143 if (!AuthRecord_uDNS(rr
))
7144 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7145 { 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
; }
7147 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7148 for (q
= m
->Questions
; q
; q
= q
->next
)
7149 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
&& q
->ReqLease
== 0 && q
->tcp
)
7151 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
7155 // Scan list of registered records
7156 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7157 if (AuthRecord_uDNS(rr
))
7159 if (rr
->state
== regState_Refresh
&& rr
->tcp
)
7160 { 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
; }
7168 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7169 // and allow up to ten seconds more to complete wide-area deregistration instead
7170 if (now
- m
->SleepLimit
>= 0)
7172 LogMsg("Failed to register with SPS, now sending goodbyes");
7174 for (intf
= GetFirstActiveInterface(m
->HostInterfaces
); intf
; intf
= GetFirstActiveInterface(intf
->next
))
7175 if (intf
->NetWakeBrowse
.ThisQInterval
>= 0)
7177 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7178 intf
->ifname
, intf
->NetWakeResolve
[0].qname
.c
, DNSTypeName(intf
->NetWakeResolve
[0].qtype
));
7179 mDNS_DeactivateNetWake_internal(m
, intf
);
7182 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
7183 if (!AuthRecord_uDNS(rr
))
7184 if (!mDNSOpaque64IsZero(&rr
->updateIntID
))
7186 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
));
7187 rr
->updateIntID
= zeroOpaque64
;
7190 // We'd really like to allow up to ten seconds more here,
7191 // but if we don't respond to the sleep notification within 30 seconds
7192 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7193 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7194 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7195 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7196 m
->SleepLimit
= now
+ mDNSPlatformOneSecond
* 1;
7198 SendSleepGoodbyes(m
, mDNStrue
, mDNStrue
);
7206 mDNSexport mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
, mDNSNextWakeReason
*outReason
)
7210 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7211 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7212 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7213 // and if that happens we don't want to just give up and go back to sleep and never try again.
7214 mDNSs32 e
= now
+ (120 * 60 * mDNSPlatformOneSecond
); // Sleep for at most 120 minutes
7215 mDNSNextWakeReason reason
= mDNSNextWakeReason_UpkeepWake
;
7217 NATTraversalInfo
*nat
;
7218 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
7220 if (nat
->Protocol
&& nat
->ExpiryTime
&& nat
->ExpiryTime
- now
> mDNSPlatformOneSecond
*4)
7222 mDNSs32 t
= nat
->ExpiryTime
- (nat
->ExpiryTime
- now
) / 10; // Wake up when 90% of the way to the expiry time
7226 reason
= mDNSNextWakeReason_NATPortMappingRenewal
;
7228 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7229 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
7230 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
7231 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
7232 nat
->retryInterval
/ mDNSPlatformOneSecond
,
7233 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
7234 (t
- now
) / mDNSPlatformOneSecond
);
7237 // This loop checks both the time we need to renew wide-area registrations,
7238 // and the time we need to renew Sleep Proxy registrations
7239 for (ar
= m
->ResourceRecords
; ar
; ar
= ar
->next
)
7241 if (ar
->expire
&& ar
->expire
- now
> mDNSPlatformOneSecond
*4)
7243 mDNSs32 t
= ar
->expire
- (ar
->expire
- now
) / 10; // Wake up when 90% of the way to the expiry time
7247 reason
= mDNSNextWakeReason_RecordRegistrationRenewal
;
7249 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7250 ar
, ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
7251 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
7252 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
7253 (t
- now
) / mDNSPlatformOneSecond
, ARDisplayString(m
, ar
));
7258 *outReason
= reason
;
7263 // ***************************************************************************
7264 #if COMPILER_LIKES_PRAGMA_MARK
7266 #pragma mark - Packet Reception Functions
7269 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7271 mDNSlocal mDNSu8
*GenerateUnicastResponse(const DNSMessage
*const query
, const mDNSu8
*const end
,
7272 const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, DNSMessage
*const response
, AuthRecord
*ResponseRecords
)
7274 mDNSu8
*responseptr
= response
->data
;
7275 const mDNSu8
*const limit
= response
->data
+ sizeof(response
->data
);
7276 const mDNSu8
*ptr
= query
->data
;
7278 mDNSu32 maxttl
= (!InterfaceID
) ? mDNSMaximumUnicastTTLSeconds
: mDNSMaximumMulticastTTLSeconds
;
7281 // Initialize the response fields so we can answer the questions
7282 InitializeDNSMessage(&response
->h
, query
->h
.id
, ResponseFlags
);
7285 // *** 1. Write out the list of questions we are actually going to answer with this packet
7289 maxttl
= kStaticCacheTTL
;
7290 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7293 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &q
); // get the question...
7294 if (!ptr
) return(mDNSNULL
);
7296 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
) // and search our list of proposed answers
7298 if (rr
->NR_AnswerTo
== ptr
) // If we're going to generate a record answering this question
7299 { // then put the question in the question section
7300 responseptr
= putQuestion(response
, responseptr
, limit
, &q
.qname
, q
.qtype
, q
.qclass
);
7301 if (!responseptr
) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL
); }
7302 break; // break out of the ResponseRecords loop, and go on to the next question
7307 if (response
->h
.numQuestions
== 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL
); }
7311 // *** 2. Write Answers
7313 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7314 if (rr
->NR_AnswerTo
)
7316 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAnswers
, &rr
->resrec
,
7317 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7318 if (p
) responseptr
= p
;
7319 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response
->h
.flags
.b
[0] |= kDNSFlag0_TC
; }
7323 // *** 3. Write Additionals
7325 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7326 if (rr
->NR_AdditionalTo
&& !rr
->NR_AnswerTo
)
7328 mDNSu8
*p
= PutResourceRecordTTL(response
, responseptr
, &response
->h
.numAdditionals
, &rr
->resrec
,
7329 maxttl
< rr
->resrec
.rroriginalttl
? maxttl
: rr
->resrec
.rroriginalttl
);
7330 if (p
) responseptr
= p
;
7331 else debugf("GenerateUnicastResponse: No more space for additionals");
7334 return(responseptr
);
7337 // AuthRecord *our is our Resource Record
7338 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7339 // Returns 0 if there is no conflict
7340 // Returns +1 if there was a conflict and we won
7341 // Returns -1 if there was a conflict and we lost and have to rename
7342 mDNSlocal
int CompareRData(const AuthRecord
*const our
, const CacheRecord
*const pkt
)
7344 mDNSu8 ourdata
[256], *ourptr
= ourdata
, *ourend
;
7345 mDNSu8 pktdata
[256], *pktptr
= pktdata
, *pktend
;
7346 if (!our
) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7347 if (!pkt
) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7349 #if defined(__clang_analyzer__)
7350 // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7351 // There are no clear indications from the analyzer of the cause of the supposed problem.
7352 mDNSPlatformMemZero(ourdata
, 1);
7353 mDNSPlatformMemZero(pktdata
, 1);
7355 ourend
= putRData(mDNSNULL
, ourdata
, ourdata
+ sizeof(ourdata
), &our
->resrec
);
7356 pktend
= putRData(mDNSNULL
, pktdata
, pktdata
+ sizeof(pktdata
), &pkt
->resrec
);
7357 while (ourptr
< ourend
&& pktptr
< pktend
&& *ourptr
== *pktptr
) { ourptr
++; pktptr
++; }
7358 if (ourptr
>= ourend
&& pktptr
>= pktend
) return(0); // If data identical, not a conflict
7360 if (ourptr
>= ourend
) return(-1); // Our data ran out first; We lost
7361 if (pktptr
>= pktend
) return(+1); // Packet data ran out first; We won
7362 if (*pktptr
> *ourptr
) return(-1); // Our data is numerically lower; We lost
7363 if (*pktptr
< *ourptr
) return(+1); // Packet data is numerically lower; We won
7365 LogMsg("CompareRData ERROR: Invalid state");
7369 mDNSlocal mDNSBool
PacketRecordMatches(const AuthRecord
*const rr
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7371 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7373 const AuthRecord
*r2
= rr
;
7374 while (r2
->DependentOn
) r2
= r2
->DependentOn
;
7375 if (r2
== master
) return(mDNStrue
);
7380 // See if we have an authoritative record that's identical to this packet record,
7381 // whose canonical DependentOn record is the specified master record.
7382 // The DependentOn pointer is typically used for the TXT record of service registrations
7383 // It indicates that there is no inherent conflict detection for the TXT record
7384 // -- it depends on the SRV record to resolve name conflicts
7385 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7386 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7387 // If the record has no DependentOn, then just return that record's pointer
7388 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7389 mDNSlocal mDNSBool
MatchDependentOn(const mDNS
*const m
, const CacheRecord
*const pktrr
, const AuthRecord
*const master
)
7391 const AuthRecord
*r1
;
7392 for (r1
= m
->ResourceRecords
; r1
; r1
=r1
->next
)
7394 if (PacketRecordMatches(r1
, pktrr
, master
)) return(mDNStrue
);
7396 for (r1
= m
->DuplicateRecords
; r1
; r1
=r1
->next
)
7398 if (PacketRecordMatches(r1
, pktrr
, master
)) return(mDNStrue
);
7403 // Find the canonical RRSet pointer for this RR received in a packet.
7404 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7405 // pointers (if any) to make sure we return the canonical member of this name/type/class
7406 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7407 mDNSlocal
const AuthRecord
*FindRRSet(const mDNS
*const m
, const CacheRecord
*const pktrr
)
7409 const AuthRecord
*rr
;
7410 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
7412 if (IdenticalResourceRecord(&rr
->resrec
, &pktrr
->resrec
))
7414 return(rr
->RRSet
? rr
->RRSet
: rr
);
7420 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7421 // as one of our records (our) but different rdata.
7422 // 1. If our record is not a type that's supposed to be unique, we don't care.
7423 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7424 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7425 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7426 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7427 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7428 // are members of the same RRSet, then this is not a conflict.
7429 mDNSlocal mDNSBool
PacketRRConflict(const mDNS
*const m
, const AuthRecord
*const our
, const CacheRecord
*const pktrr
)
7431 // If not supposed to be unique, not a conflict
7432 if (!(our
->resrec
.RecordType
& kDNSRecordTypeUniqueMask
)) return(mDNSfalse
);
7434 // If a dependent record, not a conflict
7435 if (our
->DependentOn
|| MatchDependentOn(m
, pktrr
, our
)) return(mDNSfalse
);
7438 // If the pktrr matches a member of ourset, not a conflict
7439 const AuthRecord
*ourset
= our
->RRSet
? our
->RRSet
: our
;
7440 const AuthRecord
*pktset
= FindRRSet(m
, pktrr
);
7441 if (pktset
== ourset
) return(mDNSfalse
);
7443 // For records we're proxying, where we don't know the full
7444 // relationship between the records, having any matching record
7445 // in our AuthRecords list is sufficient evidence of non-conflict
7446 if (our
->WakeUp
.HMAC
.l
[0] && pktset
) return(mDNSfalse
);
7449 // Okay, this is a conflict
7453 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7454 // the record list and/or question list.
7455 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7456 mDNSlocal
void ResolveSimultaneousProbe(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7457 DNSQuestion
*q
, AuthRecord
*our
)
7460 const mDNSu8
*ptr
= LocateAuthorities(query
, end
);
7461 mDNSBool FoundUpdate
= mDNSfalse
;
7463 for (i
= 0; i
< query
->h
.numAuthorities
; i
++)
7465 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, q
->InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
7467 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& CacheRecordAnswersQuestion(&m
->rec
.r
, q
))
7469 FoundUpdate
= mDNStrue
;
7470 if (PacketRRConflict(m
, our
, &m
->rec
.r
))
7472 int result
= (int)our
->resrec
.rrclass
- (int)m
->rec
.r
.resrec
.rrclass
;
7473 if (!result
) result
= (int)our
->resrec
.rrtype
- (int)m
->rec
.r
.resrec
.rrtype
;
7474 if (!result
) result
= CompareRData(our
, &m
->rec
.r
);
7477 const char *const msg
= (result
< 0) ? "lost:" : (result
> 0) ? "won: " : "tie: ";
7478 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7479 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, msg
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7481 // 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.
7482 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7483 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7486 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
7487 our
->ProbeCount
= DefaultProbeCountForTypeUnique
;
7488 our
->AnnounceCount
= InitialAnnounceCount
;
7489 InitializeLastAPTime(m
, our
);
7496 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q
->InterfaceID
, m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
));
7497 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our
->resrec
.InterfaceID
, our
->ProbeCount
, our
->resrec
.rdatahash
, ARDisplayString(m
, our
));
7501 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7504 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our
->resrec
.name
->c
, DNSTypeName(our
->resrec
.rrtype
));
7506 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7509 mDNSlocal CacheRecord
*FindIdenticalRecordInCache(const mDNS
*const m
, const ResourceRecord
*const pktrr
)
7511 CacheGroup
*cg
= CacheGroupForRecord(m
, pktrr
);
7514 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
7516 if (!pktrr
->InterfaceID
)
7518 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7519 match
= (pktrr
->dnsservice
== rr
->resrec
.dnsservice
) ? mDNStrue
: mDNSfalse
;
7521 const mDNSu32 id1
= (pktrr
->rDNSServer
? pktrr
->rDNSServer
->resGroupID
: 0);
7522 const mDNSu32 id2
= (rr
->resrec
.rDNSServer
? rr
->resrec
.rDNSServer
->resGroupID
: 0);
7523 match
= (id1
== id2
);
7526 else match
= (pktrr
->InterfaceID
== rr
->resrec
.InterfaceID
);
7528 if (match
&& IdenticalSameNameRecord(pktrr
, &rr
->resrec
)) break;
7532 mDNSlocal
void DeregisterProxyRecord(mDNS
*const m
, AuthRecord
*const rr
)
7534 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7535 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
7536 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7537 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7540 mDNSlocal
void ClearKeepaliveProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
, const mDNSInterfaceID InterfaceID
)
7542 if (m
->CurrentRecord
)
7543 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7544 m
->CurrentRecord
= thelist
;
7546 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7547 // clean up the keepalive record.
7548 while (m
->CurrentRecord
)
7550 AuthRecord
*const rr
= m
->CurrentRecord
;
7551 if (InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7553 if (mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
7555 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7556 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7557 DeregisterProxyRecord(m
, rr
);
7560 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7561 // new records could have been added to the end of the list as a result of that call.
7562 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7563 m
->CurrentRecord
= rr
->next
;
7567 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7568 // to check our lists and discard any stale duplicates of this record we already have
7569 mDNSlocal
void ClearIdenticalProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7571 if (m
->CurrentRecord
)
7572 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7573 m
->CurrentRecord
= thelist
;
7574 while (m
->CurrentRecord
)
7576 AuthRecord
*const rr
= m
->CurrentRecord
;
7577 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7578 if (IdenticalResourceRecord(&rr
->resrec
, &m
->rec
.r
.resrec
))
7580 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7581 m
->ProxyRecords
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7582 DeregisterProxyRecord(m
, rr
);
7584 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7585 // new records could have been added to the end of the list as a result of that call.
7586 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7587 m
->CurrentRecord
= rr
->next
;
7591 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7592 mDNSlocal
void ClearProxyRecords(mDNS
*const m
, const OwnerOptData
*const owner
, AuthRecord
*const thelist
)
7594 if (m
->CurrentRecord
)
7595 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7596 m
->CurrentRecord
= thelist
;
7597 while (m
->CurrentRecord
)
7599 AuthRecord
*const rr
= m
->CurrentRecord
;
7600 if (m
->rec
.r
.resrec
.InterfaceID
== rr
->resrec
.InterfaceID
&& mDNSSameEthAddress(&owner
->HMAC
, &rr
->WakeUp
.HMAC
))
7601 if (owner
->seq
!= rr
->WakeUp
.seq
|| m
->timenow
- rr
->TimeRcvd
> mDNSPlatformOneSecond
* 60)
7603 if (rr
->AddressProxy
.type
== mDNSAddrType_IPv6
)
7605 // We don't do this here because we know that the host is waking up at this point, so we don't send
7606 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7607 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7608 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7609 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7610 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
,rr
));
7611 SendNDP(m
, NDP_Adv
, NDP_Override
, rr
, &rr
->AddressProxy
.ip
.v6
, &rr
->WakeUp
.IMAC
, &AllHosts_v6
, &AllHosts_v6_Eth
);
7614 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7615 m
->ProxyRecords
, rr
->AnnounceCount
, rr
->resrec
.RecordType
,
7616 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, rr
->WakeUp
.seq
, owner
->seq
, ARDisplayString(m
, rr
));
7617 if (rr
->resrec
.RecordType
== kDNSRecordTypeDeregistering
) rr
->resrec
.RecordType
= kDNSRecordTypeShared
;
7618 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7619 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it, since real host is now back and functional
7620 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
7621 SetSPSProxyListChanged(m
->rec
.r
.resrec
.InterfaceID
);
7623 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7624 // new records could have been added to the end of the list as a result of that call.
7625 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
7626 m
->CurrentRecord
= rr
->next
;
7630 // ProcessQuery examines a received query to see if we have any answers to give
7631 mDNSlocal mDNSu8
*ProcessQuery(mDNS
*const m
, const DNSMessage
*const query
, const mDNSu8
*const end
,
7632 const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
, mDNSBool LegacyQuery
, mDNSBool QueryWasMulticast
,
7633 mDNSBool QueryWasLocalUnicast
, DNSMessage
*const response
)
7635 const mDNSBool FromLocalSubnet
= mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
7636 AuthRecord
*ResponseRecords
= mDNSNULL
;
7637 AuthRecord
**nrp
= &ResponseRecords
;
7640 mDNSBool notD2D
= !mDNSPlatformInterfaceIsD2D(InterfaceID
); // We don't run the POOF algorithm on D2D interfaces.
7641 CacheRecord
*ExpectedAnswers
= mDNSNULL
; // Records in our cache we expect to see updated
7642 CacheRecord
**eap
= &ExpectedAnswers
;
7643 #endif // POOF_ENABLED
7645 DNSQuestion
*DupQuestions
= mDNSNULL
; // Our questions that are identical to questions in this packet
7646 DNSQuestion
**dqp
= &DupQuestions
;
7647 mDNSs32 delayresponse
= 0;
7648 mDNSBool SendLegacyResponse
= mDNSfalse
;
7650 mDNSu8
*responseptr
= mDNSNULL
;
7655 // *** 1. Look in Additional Section for an OPT record
7657 ptr
= LocateOptRR(query
, end
, DNSOpt_OwnerData_ID_Space
);
7660 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAdd
, &m
->rec
);
7661 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
7663 const rdataOPT
*opt
;
7664 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
7665 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7666 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7667 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
7668 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
7670 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
7671 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
7674 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7678 // *** 2. Parse Question Section and mark potential answers
7681 for (i
=0; i
<query
->h
.numQuestions
; i
++) // For each question...
7683 mDNSBool QuestionNeedsMulticastResponse
;
7684 int NumAnswersForThisQuestion
= 0;
7685 AuthRecord
*NSECAnswer
= mDNSNULL
;
7686 DNSQuestion pktq
, *q
;
7687 ptr
= getQuestion(query
, ptr
, end
, InterfaceID
, &pktq
); // get the question...
7688 if (!ptr
) goto exit
;
7690 // The only queries that *need* a multicast response are:
7691 // * Queries sent via multicast
7693 // * that don't have the kDNSQClass_UnicastResponse bit set
7694 // These queries need multicast responses because other clients will:
7695 // * suppress their own identical questions when they see these questions, and
7696 // * expire their cache records if they don't see the expected responses
7697 // For other queries, we may still choose to send the occasional multicast response anyway,
7698 // to keep our neighbours caches warm, and for ongoing conflict detection.
7699 QuestionNeedsMulticastResponse
= QueryWasMulticast
&& !LegacyQuery
&& !(pktq
.qclass
& kDNSQClass_UnicastResponse
);
7701 if (pktq
.qclass
& kDNSQClass_UnicastResponse
)
7702 m
->mDNSStats
.UnicastBitInQueries
++;
7704 m
->mDNSStats
.NormalQueries
++;
7706 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7707 pktq
.qclass
&= ~kDNSQClass_UnicastResponse
;
7709 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7710 // can result in user callbacks which may change the record list and/or question list.
7711 // Also note: we just mark potential answer records here, without trying to build the
7712 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7713 // from that list while we're in the middle of trying to build it.
7714 if (m
->CurrentRecord
)
7715 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
7716 m
->CurrentRecord
= m
->ResourceRecords
;
7717 while (m
->CurrentRecord
)
7719 rr
= m
->CurrentRecord
;
7720 m
->CurrentRecord
= rr
->next
;
7721 if (AnyTypeRecordAnswersQuestion(rr
, &pktq
) && (QueryWasMulticast
|| QueryWasLocalUnicast
|| rr
->AllowRemoteQuery
))
7723 m
->mDNSStats
.MatchingAnswersForQueries
++;
7724 if (RRTypeAnswersQuestionType(&rr
->resrec
, pktq
.qtype
))
7726 if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
7727 ResolveSimultaneousProbe(m
, query
, end
, &pktq
, rr
);
7728 else if (ResourceRecordIsValidAnswer(rr
))
7730 NumAnswersForThisQuestion
++;
7732 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7733 // unicast answer back to the source, because timeliness in answering probes is important.
7736 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7737 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7738 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7739 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7740 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7741 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7742 if (QuestionNeedsMulticastResponse
|| (!FromLocalSubnet
&& QueryWasMulticast
&& !LegacyQuery
))
7744 // We only mark this question for sending if it is at least one second since the last time we multicast it
7745 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7746 // This is to guard against the case where someone blasts us with queries as fast as they can.
7747 if ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) >= (mDNSu32
)mDNSPlatformOneSecond
||
7748 (rr
->LastMCInterface
!= mDNSInterfaceMark
&& rr
->LastMCInterface
!= InterfaceID
))
7749 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7751 else if (!rr
->NR_AnswerTo
) rr
->NR_AnswerTo
= LegacyQuery
? ptr
: NR_AnswerUnicast
;
7754 else if ((rr
->resrec
.RecordType
& kDNSRecordTypeActiveUniqueMask
) && ResourceRecordIsValidAnswer(rr
))
7756 // If we don't have any answers for this question, but we do own another record with the same name,
7757 // then we'll want to mark it to generate an NSEC record on this interface
7758 if (!NSECAnswer
) NSECAnswer
= rr
;
7763 if (NumAnswersForThisQuestion
== 0 && NSECAnswer
)
7765 NumAnswersForThisQuestion
++;
7766 NSECAnswer
->SendNSECNow
= InterfaceID
;
7767 m
->NextScheduledResponse
= m
->timenow
;
7770 // If we couldn't answer this question, someone else might be able to,
7771 // so use random delay on response to reduce collisions
7772 if (NumAnswersForThisQuestion
== 0) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
7774 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
)
7775 m
->mDNSStats
.KnownAnswerMultiplePkts
++;
7776 // We only do the following accelerated cache expiration and duplicate question suppression processing
7777 // for non-truncated multicast queries with multicast responses.
7778 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7779 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7780 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7781 if (QuestionNeedsMulticastResponse
&& !(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
7786 CacheGroup
*cg
= CacheGroupForName(m
, pktq
.qnamehash
, &pktq
.qname
);
7789 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7790 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7791 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
7793 if (SameNameCacheRecordAnswersQuestion(cr
, &pktq
) && cr
->resrec
.rdlength
<= SmallRecordLimit
)
7795 if (!cr
->NextInKAList
&& eap
!= &cr
->NextInKAList
)
7798 eap
= &cr
->NextInKAList
;
7803 #endif // POOF_ENABLED
7805 // Check if this question is the same as any of mine.
7806 // We only do this for non-truncated queries. Right now it would be too complicated to try
7807 // to keep track of duplicate suppression state between multiple packets, especially when we
7808 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7809 for (q
= m
->Questions
; q
; q
=q
->next
)
7811 if (ActiveQuestion(q
) && m
->timenow
- q
->LastQTxTime
> mDNSPlatformOneSecond
/ 4)
7813 if (!q
->InterfaceID
|| q
->InterfaceID
== InterfaceID
)
7815 if (q
->NextInDQList
== mDNSNULL
&& dqp
!= &q
->NextInDQList
)
7817 if (q
->qtype
== pktq
.qtype
&&
7818 q
->qclass
== pktq
.qclass
&&
7819 q
->qnamehash
== pktq
.qnamehash
&& SameDomainName(&q
->qname
, &pktq
.qname
))
7820 { *dqp
= q
; dqp
= &q
->NextInDQList
; }
7829 // *** 3. Now we can safely build the list of marked answers
7831 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) // Now build our list of potential answers
7832 if (rr
->NR_AnswerTo
) // If we marked the record...
7833 AddRecordToResponseList(&nrp
, rr
, mDNSNULL
); // ... add it to the list
7836 // *** 4. Add additional records
7838 AddAdditionalsToResponseList(m
, ResponseRecords
, &nrp
, InterfaceID
);
7841 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7843 for (i
=0; i
<query
->h
.numAnswers
; i
++) // For each record in the query's answer section...
7845 // Get the record...
7846 CacheRecord
*ourcacherr
;
7847 ptr
= GetLargeResourceRecord(m
, query
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAns
, &m
->rec
);
7848 if (!ptr
) goto exit
;
7849 if (m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
7851 // See if this Known-Answer suppresses any of our currently planned answers
7852 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7854 if (MustSendRecord(rr
) && ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7856 m
->mDNSStats
.KnownAnswerSuppressions
++;
7857 rr
->NR_AnswerTo
= mDNSNULL
;
7858 rr
->NR_AdditionalTo
= mDNSNULL
;
7862 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7863 for (rr
=m
->ResourceRecords
; rr
; rr
=rr
->next
)
7865 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7866 if (rr
->ImmedAnswer
== InterfaceID
&& ShouldSuppressKnownAnswer(&m
->rec
.r
, rr
))
7868 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7870 if (mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= zerov4Addr
;
7872 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7874 if (mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= zerov6Addr
;
7876 if (mDNSIPv4AddressIsZero(rr
->v4Requester
) && mDNSIPv6AddressIsZero(rr
->v6Requester
))
7878 m
->mDNSStats
.KnownAnswerSuppressions
++;
7879 rr
->ImmedAnswer
= mDNSNULL
;
7880 rr
->ImmedUnicast
= mDNSfalse
;
7881 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7882 LogMsg("Suppressed after%4d: %s", m
->timenow
- rr
->ImmedAnswerMarkTime
, ARDisplayString(m
, rr
));
7888 ourcacherr
= FindIdenticalRecordInCache(m
, &m
->rec
.r
.resrec
);
7893 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7894 // any records that are suppressed by the Known Answer list in this packet.
7895 eap
= &ExpectedAnswers
;
7898 CacheRecord
*cr
= *eap
;
7899 if (cr
->resrec
.InterfaceID
== InterfaceID
&& IdenticalResourceRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
7900 { *eap
= cr
->NextInKAList
; cr
->NextInKAList
= mDNSNULL
; }
7901 else eap
= &cr
->NextInKAList
;
7904 #endif // POOF_ENABLED
7906 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7909 dqp
= &DupQuestions
;
7912 DNSQuestion
*q
= *dqp
;
7913 if (CacheRecordAnswersQuestion(&m
->rec
.r
, q
))
7914 { *dqp
= q
->NextInDQList
; q
->NextInDQList
= mDNSNULL
; }
7915 else dqp
= &q
->NextInDQList
;
7919 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
7923 // *** 6. Cancel any additionals that were added because of now-deleted records
7925 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7926 if (rr
->NR_AdditionalTo
&& !MustSendRecord(rr
->NR_AdditionalTo
))
7927 { rr
->NR_AnswerTo
= mDNSNULL
; rr
->NR_AdditionalTo
= mDNSNULL
; }
7930 // *** 7. Mark the send flags on the records we plan to send
7932 for (rr
=ResponseRecords
; rr
; rr
=rr
->NextResponse
)
7934 if (rr
->NR_AnswerTo
)
7936 mDNSBool SendMulticastResponse
= mDNSfalse
; // Send modern multicast response
7937 mDNSBool SendUnicastResponse
= mDNSfalse
; // Send modern unicast response (not legacy unicast response)
7939 // If it's been one TTL/4 since we multicast this, then send a multicast response
7940 // for conflict detection, etc.
7941 if ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) >= (mDNSu32
)TicksTTL(rr
)/4)
7943 SendMulticastResponse
= mDNStrue
;
7944 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7945 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7946 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7947 if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7949 m
->mDNSStats
.UnicastDemotedToMulticast
++;
7950 rr
->NR_AnswerTo
= NR_AnswerMulticast
;
7954 // If the client insists on a multicast response, then we'd better send one
7955 if (rr
->NR_AnswerTo
== NR_AnswerMulticast
)
7957 m
->mDNSStats
.MulticastResponses
++;
7958 SendMulticastResponse
= mDNStrue
;
7960 else if (rr
->NR_AnswerTo
== NR_AnswerUnicast
)
7962 m
->mDNSStats
.UnicastResponses
++;
7963 SendUnicastResponse
= mDNStrue
;
7965 else if (rr
->NR_AnswerTo
)
7967 SendLegacyResponse
= mDNStrue
;
7970 if (SendMulticastResponse
|| SendUnicastResponse
)
7972 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7973 rr
->ImmedAnswerMarkTime
= m
->timenow
;
7975 m
->NextScheduledResponse
= m
->timenow
;
7976 // If we're already planning to send this on another interface, just send it on all interfaces
7977 if (rr
->ImmedAnswer
&& rr
->ImmedAnswer
!= InterfaceID
)
7978 rr
->ImmedAnswer
= mDNSInterfaceMark
;
7981 rr
->ImmedAnswer
= InterfaceID
; // Record interface to send it on
7982 if (SendUnicastResponse
) rr
->ImmedUnicast
= mDNStrue
;
7983 if (srcaddr
->type
== mDNSAddrType_IPv4
)
7985 if (mDNSIPv4AddressIsZero(rr
->v4Requester
)) rr
->v4Requester
= srcaddr
->ip
.v4
;
7986 else if (!mDNSSameIPv4Address(rr
->v4Requester
, srcaddr
->ip
.v4
)) rr
->v4Requester
= onesIPv4Addr
;
7988 else if (srcaddr
->type
== mDNSAddrType_IPv6
)
7990 if (mDNSIPv6AddressIsZero(rr
->v6Requester
)) rr
->v6Requester
= srcaddr
->ip
.v6
;
7991 else if (!mDNSSameIPv6Address(rr
->v6Requester
, srcaddr
->ip
.v6
)) rr
->v6Requester
= onesIPv6Addr
;
7995 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7996 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7997 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7998 // else, for a simple unique record reply, we can reply immediately; no need for delay
7999 if (query
->h
.flags
.b
[0] & kDNSFlag0_TC
) delayresponse
= mDNSPlatformOneSecond
* 20; // Divided by 50 = 400ms
8000 else if (rr
->resrec
.RecordType
== kDNSRecordTypeShared
) delayresponse
= mDNSPlatformOneSecond
; // Divided by 50 = 20ms
8002 else if (rr
->NR_AdditionalTo
&& rr
->NR_AdditionalTo
->NR_AnswerTo
== NR_AnswerMulticast
)
8004 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
8005 // If two clients on different interfaces do queries that invoke the same optional additional answer,
8006 // then the earlier client is out of luck
8007 rr
->ImmedAdditional
= InterfaceID
;
8008 // No need to set m->NextScheduledResponse here
8009 // We'll send these additional records when we send them, or not, as the case may be
8014 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
8016 if (delayresponse
&& (!m
->SuppressSending
|| (m
->SuppressSending
- m
->timenow
) < (delayresponse
+ 49) / 50))
8018 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8019 mDNSs32 oldss
= m
->SuppressSending
;
8020 if (oldss
&& delayresponse
)
8021 LogMsg("Current SuppressSending delay%5ld; require%5ld", m
->SuppressSending
- m
->timenow
, (delayresponse
+ 49) / 50);
8023 // Pick a random delay:
8024 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
8025 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
8026 // This is an integer value, with resolution determined by the platform clock rate.
8027 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
8028 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
8029 // The +49 before dividing is to ensure we round up, not down, to ensure that even
8030 // on platforms where the native clock rate is less than fifty ticks per second,
8031 // we still guarantee that the final calculated delay is at least one platform tick.
8032 // We want to make sure we don't ever allow the delay to be zero ticks,
8033 // because if that happens we'll fail the Bonjour Conformance Test.
8034 // Our final computed delay is 20-120ms for normal delayed replies,
8035 // or 400-500ms in the case of multi-packet known-answer lists.
8036 m
->SuppressSending
= m
->timenow
+ (delayresponse
+ (mDNSs32
)mDNSRandom((mDNSu32
)mDNSPlatformOneSecond
*5) + 49) / 50;
8037 if (m
->SuppressSending
== 0) m
->SuppressSending
= 1;
8038 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8039 if (oldss
&& delayresponse
)
8040 LogMsg("Set SuppressSending to %5ld", m
->SuppressSending
- m
->timenow
);
8045 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
8047 if (SendLegacyResponse
)
8048 responseptr
= GenerateUnicastResponse(query
, end
, InterfaceID
, LegacyQuery
, response
, ResponseRecords
);
8051 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8054 // *** 10. Finally, clear our link chains ready for use next time
8056 while (ResponseRecords
)
8058 rr
= ResponseRecords
;
8059 ResponseRecords
= rr
->NextResponse
;
8060 rr
->NextResponse
= mDNSNULL
;
8061 rr
->NR_AnswerTo
= mDNSNULL
;
8062 rr
->NR_AdditionalTo
= mDNSNULL
;
8066 while (ExpectedAnswers
&& notD2D
)
8068 CacheRecord
*cr
= ExpectedAnswers
;
8069 ExpectedAnswers
= cr
->NextInKAList
;
8070 cr
->NextInKAList
= mDNSNULL
;
8072 // For non-truncated queries, we can definitively say that we should expect
8073 // to be seeing a response for any records still left in the ExpectedAnswers list
8074 if (!(query
->h
.flags
.b
[0] & kDNSFlag0_TC
))
8075 if (cr
->UnansweredQueries
== 0 || m
->timenow
- cr
->LastUnansweredTime
>= mDNSPlatformOneSecond
* 3/4)
8077 cr
->UnansweredQueries
++;
8078 cr
->LastUnansweredTime
= m
->timenow
;
8079 if (cr
->UnansweredQueries
> 1)
8080 debugf("ProcessQuery: UnansweredQueries %lu %s", cr
->UnansweredQueries
, CRDisplayString(m
, cr
));
8081 SetNextCacheCheckTimeForRecord(m
, cr
);
8084 // If we've seen multiple unanswered queries for this record,
8085 // then mark it to expire in five seconds if we don't get a response by then.
8086 if (cr
->UnansweredQueries
>= MaxUnansweredQueries
)
8088 // Only show debugging message if this record was not about to expire anyway
8089 if (RRExpireTime(cr
) - m
->timenow
> (mDNSs32
) kDefaultReconfirmTimeForNoAnswer
* 4 / 3 + mDNSPlatformOneSecond
)
8090 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8091 cr
->UnansweredQueries
, InterfaceID
, (RRExpireTime(cr
) - m
->timenow
+ mDNSPlatformOneSecond
-1) / mDNSPlatformOneSecond
, CRDisplayString(m
, cr
));
8093 m
->mDNSStats
.PoofCacheDeletions
++;
8094 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
8097 #endif // POOF_ENABLED
8099 while (DupQuestions
)
8101 DNSQuestion
*q
= DupQuestions
;
8102 DupQuestions
= q
->NextInDQList
;
8103 q
->NextInDQList
= mDNSNULL
;
8104 RecordDupSuppressInfo(q
->DupSuppress
, m
->timenow
, InterfaceID
, srcaddr
->type
);
8105 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q
->qname
.c
, DNSTypeName(q
->qtype
), InterfaceID
,
8106 srcaddr
->type
== mDNSAddrType_IPv4
? "v4" : "v6");
8108 return(responseptr
);
8111 mDNSlocal
void mDNSCoreReceiveQuery(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
8112 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8113 const mDNSInterfaceID InterfaceID
)
8115 mDNSu8
*responseend
= mDNSNULL
;
8116 mDNSBool QueryWasLocalUnicast
= srcaddr
&& dstaddr
&&
8117 !mDNSAddrIsDNSMulticast(dstaddr
) && mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8119 if (!dstaddr
|| (!InterfaceID
&& mDNSAddrIsDNSMulticast(dstaddr
)))
8121 const char *const reason
= !dstaddr
? "Received over TCP connection" : "Multicast, but no InterfaceID";
8122 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8123 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8124 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8125 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8126 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8127 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8128 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
, reason
);
8132 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8133 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8134 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
8135 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
8136 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
8137 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8138 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
8140 responseend
= ProcessQuery(m
, msg
, end
, srcaddr
, InterfaceID
,
8141 !mDNSSameIPPort(srcport
, MulticastDNSPort
), mDNSAddrIsDNSMulticast(dstaddr
), QueryWasLocalUnicast
, &m
->omsg
);
8143 if (responseend
) // If responseend is non-null, that means we built a unicast response packet
8145 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8146 m
->omsg
.h
.numQuestions
, m
->omsg
.h
.numQuestions
== 1 ? "" : "s",
8147 m
->omsg
.h
.numAnswers
, m
->omsg
.h
.numAnswers
== 1 ? "" : "s",
8148 m
->omsg
.h
.numAdditionals
, m
->omsg
.h
.numAdditionals
== 1 ? "" : "s",
8149 srcaddr
, mDNSVal16(srcport
), InterfaceID
, srcaddr
->type
);
8150 mDNSSendDNSMessage(m
, &m
->omsg
, responseend
, InterfaceID
, mDNSNULL
, mDNSNULL
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
8155 mDNSlocal mDNSBool
TrustedSource(const mDNS
*const m
, const mDNSAddr
*const srcaddr
)
8159 (void)srcaddr
; // Unused
8160 for (s
= m
->DNSServers
; s
; s
= s
->next
)
8161 if (mDNSSameAddress(srcaddr
, &s
->addr
)) return(mDNStrue
);
8166 struct UDPSocket_struct
8168 mDNSIPPort port
; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8171 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForQuestion(const mDNS
*const m
, const mDNSIPPort port
,
8172 const mDNSOpaque16 id
, const DNSQuestion
*const question
, mDNSBool tcp
)
8175 for (q
= m
->Questions
; q
; q
=q
->next
)
8177 if (!tcp
&& !q
->LocalSocket
) continue;
8178 if (mDNSSameIPPort(tcp
? q
->tcpSrcPort
: q
->LocalSocket
->port
, port
) &&
8179 q
->qtype
== question
->qtype
&&
8180 q
->qclass
== question
->qclass
&&
8181 q
->qnamehash
== question
->qnamehash
&&
8182 SameDomainName(&q
->qname
, &question
->qname
))
8184 if (mDNSSameOpaque16(q
->TargetQID
, id
)) return(q
);
8194 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8195 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8196 mDNSlocal DNSQuestion
*ExpectingUnicastResponseForRecord(mDNS
*const m
,
8197 const mDNSAddr
*const srcaddr
, const mDNSBool SrcLocal
, const mDNSIPPort port
, const mDNSOpaque16 id
, const CacheRecord
*const rr
, mDNSBool tcp
)
8202 for (q
= m
->Questions
; q
; q
=q
->next
)
8204 if (!q
->DuplicateOf
&& ResourceRecordAnswersUnicastResponse(&rr
->resrec
, q
))
8206 if (!mDNSOpaque16IsZero(q
->TargetQID
))
8208 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id
), mDNSVal16(q
->TargetQID
), CRDisplayString(m
, rr
));
8210 if (mDNSSameOpaque16(q
->TargetQID
, id
))
8215 srcp
= q
->LocalSocket
? q
->LocalSocket
->port
: zeroIPPort
;
8219 srcp
= q
->tcpSrcPort
;
8221 if (mDNSSameIPPort(srcp
, port
)) return(q
);
8223 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8224 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8225 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8226 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8227 q
->qname
.c
, DNSTypeName(q
->qtype
), srcaddr
, mDNSVal16(port
), CRDisplayString(m
, rr
));
8233 if (SrcLocal
&& q
->ExpectUnicastResp
&& (mDNSu32
)(m
->timenow
- q
->ExpectUnicastResp
) < (mDNSu32
)(mDNSPlatformOneSecond
*2))
8241 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8242 // Currently this applies only to rdata types containing more than one domainname,
8243 // or types where the domainname is not the last item in the structure.
8244 mDNSlocal mDNSu16
GetRDLengthMem(const ResourceRecord
*const rr
)
8248 case kDNSType_SOA
: return sizeof(rdataSOA
);
8249 case kDNSType_RP
: return sizeof(rdataRP
);
8250 case kDNSType_PX
: return sizeof(rdataPX
);
8251 default: return rr
->rdlength
;
8255 mDNSexport CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
, mDNSs32 delay
, mDNSBool Add
, const mDNSAddr
*sourceAddress
)
8257 CacheRecord
*rr
= mDNSNULL
;
8258 mDNSu16 RDLength
= GetRDLengthMem(&m
->rec
.r
.resrec
);
8260 if (!m
->rec
.r
.resrec
.InterfaceID
) debugf("CreateNewCacheEntry %s", CRDisplayString(m
, &m
->rec
.r
));
8262 //if (RDLength > InlineCacheRDSize)
8263 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8265 if (!cg
) cg
= GetCacheGroup(m
, slot
, &m
->rec
.r
.resrec
); // If we don't have a CacheGroup for this name, make one now
8266 if (cg
) rr
= GetCacheRecord(m
, cg
, RDLength
); // Make a cache record, being careful not to recycle cg
8267 if (!rr
) NoCacheAnswer(m
, &m
->rec
.r
);
8270 RData
*saveptr
= rr
->resrec
.rdata
; // Save the rr->resrec.rdata pointer
8271 *rr
= m
->rec
.r
; // Block copy the CacheRecord object
8272 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8273 mdns_retain_null_safe(rr
->resrec
.dnsservice
);
8275 rr
->resrec
.rdata
= saveptr
; // Restore rr->resrec.rdata after the structure assignment
8276 rr
->resrec
.name
= cg
->name
; // And set rr->resrec.name to point into our CacheGroup header
8277 rr
->resrec
.mortality
= Mortality_Mortal
;
8278 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8279 rr
->resrec
.dnssec_result
= dnssec_indeterminate
; // Set the DNSSEC validation result of a record as "indeterminate" by default.
8282 rr
->DelayDelivery
= delay
;
8284 // If this is an oversized record with external storage allocated, copy rdata to external storage
8285 if (rr
->resrec
.rdata
== (RData
*)&rr
->smallrdatastorage
&& RDLength
> InlineCacheRDSize
)
8286 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8287 else if (rr
->resrec
.rdata
!= (RData
*)&rr
->smallrdatastorage
&& RDLength
<= InlineCacheRDSize
)
8288 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m
->rec
.r
.resrec
.name
->c
);
8289 if (RDLength
> InlineCacheRDSize
)
8290 mDNSPlatformMemCopy(rr
->resrec
.rdata
, m
->rec
.r
.resrec
.rdata
, sizeofRDataHeader
+ RDLength
);
8292 rr
->next
= mDNSNULL
; // Clear 'next' pointer
8296 rr
->sourceAddress
= *sourceAddress
;
8298 if (!rr
->resrec
.InterfaceID
)
8300 m
->rrcache_totalused_unicast
+= rr
->resrec
.rdlength
;
8303 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8306 rr
->denial_of_existence_records
= mDNSNULL
;
8308 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8312 *(cg
->rrcache_tail
) = rr
; // Append this record to tail of cache slot list
8313 cg
->rrcache_tail
= &(rr
->next
); // Advance tail pointer
8314 CacheRecordAdd(m
, rr
); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8318 // Can't use the "cg->name" if we are not adding to the cache as the
8319 // CacheGroup may be released anytime if it is empty
8320 domainname
*name
= (domainname
*) mDNSPlatformMemAllocate(DomainNameLength(cg
->name
));
8323 AssignDomainName(name
, cg
->name
);
8324 rr
->resrec
.name
= name
;
8328 ReleaseCacheRecord(m
, rr
);
8329 NoCacheAnswer(m
, &m
->rec
.r
);
8337 mDNSlocal
void RefreshCacheRecordCacheGroupOrder(CacheGroup
*cg
, CacheRecord
*cr
)
8338 { // Move the cache record to the tail of the cache group to maintain a fresh ordering
8339 if (cg
->rrcache_tail
!= &cr
->next
) // If not already at the tail
8342 for (rp
= &cg
->members
; *rp
; rp
= &(*rp
)->next
)
8344 if (*rp
== cr
) // This item points to this record
8346 *rp
= cr
->next
; // Remove this record
8350 cr
->next
= mDNSNULL
; // This record is now last
8351 *(cg
->rrcache_tail
) = cr
; // Append this record to tail of cache group
8352 cg
->rrcache_tail
= &(cr
->next
); // Advance tail pointer
8356 mDNSlocal
void RefreshCacheRecord(mDNS
*const m
, CacheRecord
*rr
, mDNSu32 ttl
)
8358 rr
->TimeRcvd
= m
->timenow
;
8359 rr
->resrec
.rroriginalttl
= ttl
;
8360 rr
->UnansweredQueries
= 0;
8361 if (rr
->resrec
.mortality
!= Mortality_Mortal
) rr
->resrec
.mortality
= Mortality_Immortal
;
8362 SetNextCacheCheckTimeForRecord(m
, rr
);
8365 mDNSexport
void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
)
8368 CacheGroup
*cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
8369 for (rr
= cg
? cg
->members
: mDNSNULL
; rr
; rr
=rr
->next
)
8370 if (rr
->CRActiveQuestion
== q
)
8372 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8373 RefreshCacheRecord(m
, rr
, lease
);
8377 mDNSlocal mDNSu32
GetEffectiveTTL(const uDNS_LLQType LLQType
, mDNSu32 ttl
) // TTL in seconds
8379 if (LLQType
== uDNS_LLQ_Entire
) ttl
= kLLQ_DefLease
;
8380 else if (LLQType
== uDNS_LLQ_Events
)
8382 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8383 if (ttl
== 0xFFFFFFFF) ttl
= 0;
8384 else ttl
= kLLQ_DefLease
;
8386 else // else not LLQ (standard uDNS response)
8388 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8389 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8390 if (ttl
> 0x60000000UL
/ mDNSPlatformOneSecond
) ttl
= 0x60000000UL
/ mDNSPlatformOneSecond
;
8392 ttl
= RRAdjustTTL(ttl
);
8394 // For mDNS, TTL zero means "delete this record"
8395 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8396 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8397 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8398 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8399 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8400 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8401 // (with the current code) result in the server having even less than three seconds to respond
8402 // before we deleted the record and reported a "remove" event to any active questions.
8403 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8404 // then things really break (e.g. we end up making a negative cache entry).
8405 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8406 if (ttl
< 15) ttl
= 15;
8412 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8414 mDNSlocal mDNSBool
IsResponseAcceptable(mDNS
*const m
, const CacheRecord
*crlist
)
8416 CacheRecord
*const newcr
= &m
->rec
.r
;
8417 ResourceRecord
*rr
= &newcr
->resrec
;
8418 const CacheRecord
*cr
;
8420 for (cr
= crlist
; cr
!= (CacheRecord
*)1; cr
= cr
->NextInCFList
)
8422 domainname
*target
= GetRRDomainNameTarget(&cr
->resrec
);
8423 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8424 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8425 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8426 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8427 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8429 if (target
&& cr
->resrec
.rdatahash
== rr
->namehash
&& SameDomainName(target
, rr
->name
))
8431 LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr
->name
->c
, CRDisplayString(m
, cr
));
8438 mDNSlocal
void mDNSCoreReceiveNoUnicastAnswers(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
8439 const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
,
8440 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8441 const mdns_querier_t querier
, const mdns_dns_service_t uDNSService
,
8443 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8444 denial_of_existence_records_t
**denial_of_existence_records_ptr
,
8446 const uDNS_LLQType LLQType
)
8449 const mDNSu8
*ptr
= response
->data
;
8450 CacheRecord
*SOARecord
= mDNSNULL
;
8452 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
8455 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
8459 CacheRecord
*cr
, *neg
= mDNSNULL
;
8461 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8464 qptr
= Querier_GetDNSQuestion(querier
);
8469 qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
);
8475 cg
= CacheGroupForName(m
, q
.qnamehash
, &q
.qname
);
8476 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
8479 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8482 isAnswer
= (cr
->resrec
.dnsservice
== uDNSService
) && Querier_SameNameCacheRecordIsAnswer(cr
, querier
);
8487 isAnswer
= SameNameCacheRecordAnswersQuestion(cr
, qptr
);
8491 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8492 if (RRExpireTime(cr
) - m
->timenow
> 0) break;
8493 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8494 if (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) neg
= cr
;
8495 else if (cr
->resrec
.mortality
== Mortality_Ghost
)
8497 // 3. If the existing entry is expired, mark it to be purged
8498 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8499 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Removing expired record" PRI_S
,
8500 q
.request_id
, mDNSVal16(q
.TargetQID
), CRDisplayString(m
, cr
));
8501 mDNS_PurgeCacheResourceRecord(m
, cr
);
8505 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8506 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8507 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8508 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8509 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8510 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8511 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8512 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8513 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8514 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8516 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8517 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8518 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8519 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8520 // do the appropriate thing. This negative response is also needed for appending new search domains.
8521 if (!InterfaceID
&& q
.qtype
!= kDNSType_SOA
&& IsLocalDomain(&q
.qname
))
8527 const mDNSBool noData
= ((response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
) == kDNSFlag1_RC_NoErr
) ? mDNStrue
: mDNSfalse
;
8528 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8529 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME
" (" PUB_S
")",
8530 q
.request_id
, mDNSVal16(q
.TargetQID
), DM_NAME_PARAM(&q
.qname
), DNSTypeName(q
.qtype
));
8531 m
->CurrentQuestion
= qptr
;
8532 // We are not creating a cache record in this case, we need to pass back
8533 // the error we got so that the proxy code can return the right one to
8535 if (qptr
->ProxyQuestion
)
8536 qptr
->responseFlags
= response
->h
.flags
;
8537 GenerateNegativeResponseEx(m
, mDNSInterface_Any
, QC_forceresponse
, noData
);
8538 m
->CurrentQuestion
= mDNSNULL
;
8543 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8544 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME
" (" PUB_S
")",
8545 q
.request_id
, mDNSVal16(q
.TargetQID
), DM_NAME_PARAM(&q
.qname
), DNSTypeName(q
.qtype
));
8552 // We start off assuming a negative caching TTL of 60 seconds
8553 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8554 mDNSu32 negttl
= 60;
8556 const domainname
*name
= &q
.qname
;
8557 mDNSu32 hash
= q
.qnamehash
;
8559 // Special case for our special Microsoft Active Directory "local SOA" check.
8560 // Some cheap home gateways don't include an SOA record in the authority section when
8561 // they send negative responses, so we don't know how long to cache the negative result.
8562 // Because we don't want to keep hitting the root name servers with our query to find
8563 // if we're on a network using Microsoft Active Directory using "local" as a private
8564 // internal top-level domain, we make sure to cache the negative result for at least one day.
8565 if (q
.qtype
== kDNSType_SOA
&& SameDomainName(&q
.qname
, &localdomain
)) negttl
= 60 * 60 * 24;
8567 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8568 if (response
->h
.numAuthorities
&& (ptr
= LocateAuthorities(response
, end
)) != mDNSNULL
)
8570 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
8571 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_SOA
)
8573 CacheGroup
*cgSOA
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
8574 const rdataSOA
*const soa
= (const rdataSOA
*)m
->rec
.r
.resrec
.rdata
->u
.data
;
8575 mDNSu32 ttl_s
= soa
->min
;
8576 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8577 // for the SOA record for ".", where the record is reported as non-cacheable
8578 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8579 if (ttl_s
> m
->rec
.r
.resrec
.rroriginalttl
&& m
->rec
.r
.resrec
.name
->c
[0])
8580 ttl_s
= m
->rec
.r
.resrec
.rroriginalttl
;
8581 if (negttl
< ttl_s
) negttl
= ttl_s
;
8583 // Create the SOA record as we may have to return this to the questions
8584 // that we are acting as a proxy for currently or in the future.
8585 SOARecord
= CreateNewCacheEntry(m
, HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
), cgSOA
, 1, mDNSfalse
, mDNSNULL
);
8587 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8588 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8589 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8590 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8592 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8593 // along with the negative cache record. For simplicity, we don't create the additional records.
8594 if ((!qptr
|| !qptr
->ProxyQuestion
) && (q
.qtype
== kDNSType_SOA
))
8596 int qcount
= CountLabels(&q
.qname
);
8597 int scount
= CountLabels(m
->rec
.r
.resrec
.name
);
8598 if (qcount
- 1 > scount
)
8599 if (SameDomainName(SkipLeadingLabels(&q
.qname
, qcount
- scount
), m
->rec
.r
.resrec
.name
))
8600 repeat
= qcount
- 1 - scount
;
8603 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8606 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8607 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8608 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8609 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8610 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8611 // so that we back off our polling rate and don't keep hitting the server continually.
8614 if (negttl
< neg
->resrec
.rroriginalttl
* 2)
8615 negttl
= neg
->resrec
.rroriginalttl
* 2;
8620 negttl
= GetEffectiveTTL(LLQType
, negttl
); // Add 25% grace period if necessary
8622 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8625 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
8626 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S
,
8627 q
.request_id
, mDNSVal16(q
.TargetQID
), neg
->resrec
.rroriginalttl
, negttl
, CRDisplayString(m
, neg
));
8628 RefreshCacheRecord(m
, neg
, negttl
);
8629 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8630 // replace the old records with the new ones
8631 // If qptr is NULL, it means the question is no longer active, and we do not process the record
8633 if ((qptr
!= mDNSNULL
) && qptr
->DNSSECStatus
.enable_dnssec
)
8635 update_denial_records_in_cache_record(neg
, denial_of_existence_records_ptr
);
8637 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8638 // When we created the cache for the first time and answered the question, the question's
8639 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8640 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8641 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8642 // we should reset its question interval here to MaxQuestionInterval.
8645 ResetQuestionState(m
, qptr
);
8650 ReleaseCacheRecord(m
, neg
->soa
);
8651 neg
->soa
= SOARecord
;
8652 SOARecord
= mDNSNULL
;
8658 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl
, name
->c
, DNSTypeName(q
.qtype
));
8659 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8660 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, uDNSService
);
8662 MakeNegativeCacheRecord(m
, &m
->rec
.r
, name
, hash
, q
.qtype
, q
.qclass
, negttl
, mDNSInterface_Any
, qptr
->qDNSServer
);
8664 m
->rec
.r
.responseFlags
= response
->h
.flags
;
8665 // We create SOA records above which might create new cache groups. Earlier
8666 // in the function we looked up the cache group for the name and it could have
8667 // been NULL. If we pass NULL cg to new cache entries that we create below,
8668 // it will create additional cache groups for the same name. To avoid that,
8669 // look up the cache group again to re-initialize cg again.
8670 cg
= CacheGroupForName(m
, hash
, name
);
8671 // Need to add with a delay so that we can tag the SOA record
8672 negcr
= CreateNewCacheEntry(m
, HashSlotFromNameHash(hash
), cg
, 1, mDNStrue
, mDNSNULL
);
8676 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8677 // If qptr is NULL, it means the question is no longer active, and we do not process the
8678 // record for DNSSEC.
8679 if (qptr
!= mDNSNULL
&& qptr
->DNSSECStatus
.enable_dnssec
)
8681 update_denial_records_in_cache_record(negcr
, denial_of_existence_records_ptr
);
8684 negcr
->DelayDelivery
= 0;
8689 ReleaseCacheRecord(m
, negcr
->soa
);
8690 negcr
->soa
= SOARecord
;
8691 SOARecord
= mDNSNULL
;
8693 CacheRecordDeferredAdd(m
, negcr
);
8695 m
->rec
.r
.responseFlags
= zeroID
;
8696 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8699 name
= (const domainname
*)(name
->c
+ 1 + name
->c
[0]);
8700 hash
= DomainNameHashValue(name
);
8708 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8709 ReleaseCacheRecord(m
, SOARecord
);
8713 mDNSlocal
void mDNSCorePrintStoredProxyRecords(mDNS
*const m
)
8715 AuthRecord
*rrPtr
= mDNSNULL
;
8716 if (!m
->SPSRRSet
) return;
8717 LogSPS("Stored Proxy records :");
8718 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8720 LogSPS("%s", ARDisplayString(m
, rrPtr
));
8724 mDNSlocal mDNSBool
mDNSCoreRegisteredProxyRecord(mDNS
*const m
, AuthRecord
*rr
)
8726 AuthRecord
*rrPtr
= mDNSNULL
;
8728 for (rrPtr
= m
->SPSRRSet
; rrPtr
; rrPtr
= rrPtr
->next
)
8730 if (IdenticalResourceRecord(&rrPtr
->resrec
, &rr
->resrec
))
8732 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m
, rr
));
8736 mDNSCorePrintStoredProxyRecords(m
);
8740 mDNSexport CacheRecord
* mDNSCoreReceiveCacheCheck(mDNS
*const m
, const DNSMessage
*const response
, uDNS_LLQType LLQType
,
8741 const mDNSu32 slot
, CacheGroup
*cg
, CacheRecord
***cfp
, mDNSInterfaceID InterfaceID
)
8744 CacheRecord
**cflocal
= *cfp
;
8746 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
8749 // Resource record received via unicast, the resGroupID should match ?
8752 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8753 match
= (cr
->resrec
.dnsservice
== m
->rec
.r
.resrec
.dnsservice
) ? mDNStrue
: mDNSfalse
;
8755 const mDNSu32 id1
= (cr
->resrec
.rDNSServer
? cr
->resrec
.rDNSServer
->resGroupID
: 0);
8756 const mDNSu32 id2
= (m
->rec
.r
.resrec
.rDNSServer
? m
->rec
.r
.resrec
.rDNSServer
->resGroupID
: 0);
8757 match
= (id1
== id2
);
8761 match
= (cr
->resrec
.InterfaceID
== InterfaceID
);
8762 // If we found this exact resource record, refresh its TTL
8765 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &cr
->resrec
))
8767 if (m
->rec
.r
.resrec
.rdlength
> InlineCacheRDSize
)
8768 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8769 m
->rec
.r
.resrec
.rdlength
, InterfaceID
, CRDisplayString(m
, &m
->rec
.r
));
8771 if (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8773 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8774 if (cr
->NextInCFList
== mDNSNULL
&& *cfp
!= &cr
->NextInCFList
&& LLQType
!= uDNS_LLQ_Events
)
8777 cflocal
= &cr
->NextInCFList
;
8778 *cflocal
= (CacheRecord
*)1;
8779 *cfp
= &cr
->NextInCFList
;
8782 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8783 if (!(cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
))
8786 for (q
= m
->Questions
; q
; q
=q
->next
)
8788 if (CacheRecordAnswersQuestion(cr
, q
))
8791 cr
->resrec
.RecordType
= m
->rec
.r
.resrec
.RecordType
;
8795 if (!SameRDataBody(&m
->rec
.r
.resrec
, &cr
->resrec
.rdata
->u
, SameDomainNameCS
))
8797 // If the rdata of the packet record differs in name capitalization from the record in our cache
8798 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8799 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8800 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8801 cr
->resrec
.rroriginalttl
= 0;
8802 cr
->TimeRcvd
= m
->timenow
;
8803 cr
->UnansweredQueries
= MaxUnansweredQueries
;
8804 SetNextCacheCheckTimeForRecord(m
, cr
);
8805 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S
, CRDisplayString(m
, cr
));
8806 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S
, CRDisplayString(m
, &m
->rec
.r
));
8807 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8808 NextCacheCheckEvent(cr
) - m
->timenow
, slot
, m
->rrcache_nextcheck
[slot
] - m
->timenow
, m
->NextCacheCheck
- m
->timenow
);
8809 // DO NOT break out here -- we want to continue as if we never found it
8811 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0)
8815 m
->mDNSStats
.CacheRefreshed
++;
8817 if ((cr
->resrec
.mortality
== Mortality_Ghost
) && !cr
->DelayDelivery
)
8819 cr
->DelayDelivery
= NonZeroTime(m
->timenow
);
8820 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m
->timenow
- RRExpireTime(cr
), CRDisplayString(m
, cr
));
8823 if (cr
->resrec
.rroriginalttl
== 0) debugf("uDNS rescuing %s", CRDisplayString(m
, cr
));
8824 RefreshCacheRecord(m
, cr
, m
->rec
.r
.resrec
.rroriginalttl
);
8825 // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop.
8826 // 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.
8827 RefreshCacheRecordCacheGroupOrder(cg
, cr
);
8828 cr
->responseFlags
= response
->h
.flags
;
8830 // If we may have NSEC records returned with the answer (which we don't know yet as it
8831 // has not been processed), we need to cache them along with the first cache
8832 // record in the list that answers the question so that it can be used for validation
8833 // later. The "type" check below is to make sure that we cache on the cache record
8834 // that would answer the question. It is possible that we might cache additional things
8835 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8836 // the record that answers the question.
8839 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S
, CRDisplayString(m
, cr
));
8841 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8842 // polling the network once we get a valid response back. For the first time when a new
8843 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8844 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8845 // configuration changed, without flushing the cache, we reset the question interval here.
8846 // Currently, we do this for for both multicast and unicast questions as long as the record
8847 // type is unique. For unicast, resource record is always unique and for multicast it is
8848 // true for records like A etc. but not for PTR.
8849 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
)
8851 for (q
= m
->Questions
; q
; q
=q
->next
)
8853 if (!q
->DuplicateOf
&& !q
->LongLived
&&
8854 ActiveQuestion(q
) && CacheRecordAnswersQuestion(cr
, q
))
8856 ResetQuestionState(m
, q
);
8857 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
8858 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8862 break; // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above)
8866 // If the packet TTL is zero, that means we're deleting this record.
8867 // To give other hosts on the network a chance to protest, we push the deletion
8868 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8869 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8870 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8871 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8872 // If the record is already going to expire in less than one second anyway, we leave it alone --
8873 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8874 debugf("DE for %s", CRDisplayString(m
, cr
));
8875 if (RRExpireTime(cr
) - m
->timenow
> mDNSPlatformOneSecond
)
8877 cr
->resrec
.rroriginalttl
= 1;
8878 cr
->TimeRcvd
= m
->timenow
;
8879 cr
->UnansweredQueries
= MaxUnansweredQueries
;
8880 SetNextCacheCheckTimeForRecord(m
, cr
);
8885 else if (cr
->resrec
.rroriginalttl
!= 0 && // Not already marked for discarding
8886 m
->rec
.r
.resrec
.rrclass
== cr
->resrec
.rrclass
&&
8887 (m
->rec
.r
.resrec
.rrtype
!= cr
->resrec
.rrtype
&&
8888 (m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
|| cr
->resrec
.rrtype
== kDNSType_CNAME
)))
8890 // If the cache record rrtype doesn't match and one is a CNAME, then flush this record
8891 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "mDNSCoreReceiveCacheCheck: Discarding (%s) " PRI_S
" rrtype change from (%s) to (%s)",
8892 MortalityDisplayString(cr
->resrec
.mortality
), CRDisplayString(m
, cr
), DNSTypeName(cr
->resrec
.rrtype
), DNSTypeName(m
->rec
.r
.resrec
.rrtype
));
8893 mDNS_PurgeCacheResourceRecord(m
, cr
);
8894 // DO NOT break out here -- we want to continue iterating the cache entries
8901 mDNSlocal
void mDNSCoreResetRecord(mDNS
*const m
)
8903 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
8906 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8907 // the record list and/or question list.
8908 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8909 // InterfaceID non-NULL tells us the interface this multicast response was received on
8910 // InterfaceID NULL tells us this was a unicast response
8911 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8912 mDNSlocal
void mDNSCoreReceiveResponse(mDNS
*const m
, const DNSMessage
*const response
, const mDNSu8
*end
,
8913 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
8914 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8915 mdns_querier_t querier
, mdns_dns_service_t uDNSService
,
8917 const mDNSInterfaceID InterfaceID
)
8920 const mDNSBool ResponseMCast
= dstaddr
&& mDNSAddrIsDNSMulticast(dstaddr
);
8921 const mDNSBool ResponseSrcLocal
= !srcaddr
|| mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
);
8922 DNSQuestion
*llqMatch
= mDNSNULL
;
8923 uDNS_LLQType LLQType
= uDNS_recvLLQResponse(m
, response
, end
, srcaddr
, srcport
, &llqMatch
);
8925 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8926 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8927 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8928 CacheRecord
*CacheFlushRecords
= (CacheRecord
*)1;
8929 CacheRecord
**cfp
= &CacheFlushRecords
;
8930 NetworkInterfaceInfo
*llintf
= FirstIPv4LLInterfaceForID(m
, InterfaceID
);
8931 mDNSBool recordAcceptedInResponse
= mDNSfalse
; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8933 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8934 // to guard against spoof responses, then the only credible protection against that is cryptographic
8935 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8936 int firstauthority
= response
->h
.numAnswers
;
8937 int firstadditional
= firstauthority
+ response
->h
.numAuthorities
;
8938 int totalrecords
= firstadditional
+ response
->h
.numAdditionals
;
8939 const mDNSu8
*ptr
= response
->data
;
8940 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8941 DNSServer
*uDNSServer
= mDNSNULL
;
8943 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8944 denial_of_existence_records_t
*denial_of_existence_records
= mDNSNULL
;
8945 mDNSBool not_answer_but_required_for_dnssec
= mDNSfalse
;
8947 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8948 // Determine whether the response is mDNS, as opposed to DNS.
8949 // Thus far, the code has assumed that responses with IDs set to zero are mDNS responses. However, this condition
8950 // isn't sufficient because queriers, which are used exclusively for DNS queries, may set the IDs of their queries
8951 // to zero. And consequently, their responses may have their IDs set to zero. Specifically, zero-valued IDs are used
8952 // for DNS over HTTPs, as specified by <https://tools.ietf.org/html/rfc8484#section-4.1>.
8953 const mDNSBool ResponseIsMDNS
= mDNSOpaque16IsZero(response
->h
.id
) && !querier
;
8955 const mDNSBool ResponseIsMDNS
= mDNSOpaque16IsZero(response
->h
.id
);
8958 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8959 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8960 srcaddr
, dstaddr
, InterfaceID
,
8961 response
->h
.numQuestions
, response
->h
.numQuestions
== 1 ? ", " : "s,",
8962 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
8963 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
8964 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? " " : "s", end
- response
->data
, LLQType
);
8966 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8967 if (mDNSSameIPPort(srcport
, UnicastDNSPort
))
8969 MetricsUpdateDNSResponseSize((mDNSu32
)(end
- (mDNSu8
*)response
));
8973 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8974 // When a DNS client receives a reply with TC
8975 // set, it should ignore that response, and query again, using a
8976 // mechanism, such as a TCP connection, that will permit larger replies.
8977 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8978 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8979 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8980 // <rdar://problem/6690034> Can't bind to Active Directory
8981 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8982 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8983 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
8984 // and not even do the TCP query.
8985 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
8986 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
8987 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
8988 // section, and the answer section is therefore assumed to be complete.
8990 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
8991 // When a response is so long that truncation is required, the truncation
8992 // should start at the end of the response and work forward in the
8993 // datagram. Thus if there is any data for the authority section, the
8994 // answer section is guaranteed to be unique.
8995 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8996 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
) && !querier
&&
8998 if (!InterfaceID
&& (response
->h
.flags
.b
[0] & kDNSFlag0_TC
) &&
9000 ((response
->h
.numAnswers
== 0) || ((response
->h
.numAuthorities
== 0) && (response
->h
.numAdditionals
== 0)))) return;
9002 if (LLQType
== uDNS_LLQ_Ignore
) return;
9004 // 1. We ignore questions (if any) in mDNS response packets
9005 // 2. If this is an LLQ response, we handle it much the same
9006 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9007 if (ResponseMCast
|| LLQType
== uDNS_LLQ_Events
)
9008 ptr
= LocateAnswers(response
, end
);
9009 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9010 // in this response packet are immediately deemed to be invalid.
9013 mDNSBool failure
, returnEarly
;
9014 const int rcode
= response
->h
.flags
.b
[1] & kDNSFlag1_RC_Mask
;
9015 failure
= !(rcode
== kDNSFlag1_RC_NoErr
|| rcode
== kDNSFlag1_RC_NXDomain
|| rcode
== kDNSFlag1_RC_NotAuth
);
9016 returnEarly
= mDNSfalse
;
9017 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9018 // When the QUERIER functionality is enabled, DNS transport is handled exclusively by querier objects. If this
9019 // response was provided by a querier, but the RCODE is considered a failure, then set failure to false so that
9020 // we don't return early. The logic of returning early was so that uDNS_CheckCurrentQuestion() could handle
9021 // resending the query and generate a negative cache record if all servers were tried. If the querier provides a
9022 // response, then it's the best response that it could provide. If the RCODE is considered a failure,
9023 // mDNSCoreReceiveResponse() needs to create negative cache entries for the unanwered question, so totalrecords
9024 // is set to 0 to ignore any records that the response may contain.
9025 if (querier
&& failure
)
9028 failure
= mDNSfalse
;
9031 // We could possibly combine this with the similar loop at the end of this function --
9032 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9033 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9034 // which it was received (or refreshed), and then at the end if we find any cache records which
9035 // answer questions in this packet's question section, but which aren't tagged with this packet's
9036 // packet number, then we deduce they are old and delete them
9037 for (i
= 0; i
< response
->h
.numQuestions
&& ptr
&& ptr
< end
; i
++)
9041 mDNSBool expectingResponse
;
9042 ptr
= getQuestion(response
, ptr
, end
, InterfaceID
, &q
);
9047 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9050 expectingResponse
= mDNStrue
;
9056 qptr
= ExpectingUnicastResponseForQuestion(m
, dstport
, response
->h
.id
, &q
, !dstaddr
);
9057 expectingResponse
= qptr
? mDNStrue
: mDNSfalse
;
9059 if (!expectingResponse
)
9066 CacheGroup
*cg
= CacheGroupForName(m
, q
.qnamehash
, &q
.qname
);
9067 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
9070 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9073 isAnswer
= (cr
->resrec
.dnsservice
== uDNSService
) && Querier_SameNameCacheRecordIsAnswer(cr
, querier
);
9078 isAnswer
= SameNameCacheRecordAnswersQuestion(cr
, qptr
);
9082 debugf("uDNS marking %p %##s (%s) %p %s", q
.InterfaceID
, q
.qname
.c
, DNSTypeName(q
.qtype
),
9083 cr
->resrec
.InterfaceID
, CRDisplayString(m
, cr
));
9084 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9085 cr
->TimeRcvd
= m
->timenow
- TicksTTL(cr
) - 1;
9086 cr
->UnansweredQueries
= MaxUnansweredQueries
;
9092 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9093 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9094 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME
" (" PUB_S
")",
9095 qptr
->request_id
, mDNSVal16(qptr
->TargetQID
), qptr
->qDNSServer
, rcode
,
9096 DM_NAME_PARAM(&q
.qname
), DNSTypeName(q
.qtype
));
9097 PenalizeDNSServer(m
, qptr
, response
->h
.flags
);
9099 returnEarly
= mDNStrue
;
9104 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9105 "[Q%d] Ignoring %2d Answer" PUB_S
" %2d Authorit" PUB_S
" %2d Additional" PUB_S
,
9106 mDNSVal16(response
->h
.id
),
9107 response
->h
.numAnswers
, response
->h
.numAnswers
== 1 ? ", " : "s,",
9108 response
->h
.numAuthorities
, response
->h
.numAuthorities
== 1 ? "y, " : "ies,",
9109 response
->h
.numAdditionals
, response
->h
.numAdditionals
== 1 ? "" : "s");
9110 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9111 // generate negative cache entries (we want to query the next server)
9116 for (i
= 0; i
< totalrecords
&& ptr
&& ptr
< end
; i
++)
9118 // All responses sent via LL multicast are acceptable for caching
9119 // All responses received over our outbound TCP connections are acceptable for caching
9120 // We accept all records in a unicast response to a multicast query once we find one that
9121 // answers an active question.
9122 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9123 mDNSBool AcceptableResponse
= ResponseMCast
|| (!querier
&& !dstaddr
) || LLQType
|| recordAcceptedInResponse
;
9125 mDNSBool AcceptableResponse
= ResponseMCast
|| !dstaddr
|| LLQType
|| recordAcceptedInResponse
;
9127 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9128 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9130 const mDNSu8 RecordType
=
9131 (i
< firstauthority
) ? (mDNSu8
)kDNSRecordTypePacketAns
:
9132 (i
< firstadditional
) ? (mDNSu8
)kDNSRecordTypePacketAuth
: (mDNSu8
)kDNSRecordTypePacketAdd
;
9133 ptr
= GetLargeResourceRecord(m
, response
, ptr
, end
, InterfaceID
, RecordType
, &m
->rec
);
9134 if (!ptr
) goto exit
; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9136 if (m
->rec
.r
.resrec
.RecordType
== kDNSRecordTypePacketNegative
)
9138 mDNSCoreResetRecord(m
);
9142 // Don't want to cache OPT or TSIG pseudo-RRs
9143 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_TSIG
)
9145 mDNSCoreResetRecord(m
);
9148 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
9150 const rdataOPT
*opt
;
9151 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
9152 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9153 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9154 for (opt
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; opt
< e
; opt
++)
9155 if (opt
->opt
== kDNSOpt_Owner
&& opt
->u
.owner
.vers
== 0 && opt
->u
.owner
.HMAC
.l
[0])
9157 ClearProxyRecords(m
, &opt
->u
.owner
, m
->DuplicateRecords
);
9158 ClearProxyRecords(m
, &opt
->u
.owner
, m
->ResourceRecords
);
9160 mDNSCoreResetRecord(m
);
9163 // if a CNAME record points to itself, then don't add it to the cache
9164 if ((m
->rec
.r
.resrec
.rrtype
== kDNSType_CNAME
) && SameDomainName(m
->rec
.r
.resrec
.name
, &m
->rec
.r
.resrec
.rdata
->u
.name
))
9166 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m
->rec
.r
.resrec
.name
->c
);
9167 mDNSCoreResetRecord(m
);
9171 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9172 // In the case of active LLQs, we'll get remove events when the records actually do go away
9173 // In the case of polling LLQs, we assume the record remains valid until the next poll
9174 if (!ResponseIsMDNS
)
9176 m
->rec
.r
.resrec
.rroriginalttl
= GetEffectiveTTL(LLQType
, m
->rec
.r
.resrec
.rroriginalttl
);
9179 // If response was not sent via LL multicast,
9180 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9185 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9186 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9187 // queries to get ADD/RMV events. To lookup the question, we can't use
9188 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9189 // has already matched the question using the 64 bit Id in the packet and we use that here.
9191 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9194 mdns_replace(&m
->rec
.r
.resrec
.dnsservice
, uDNSService
);
9197 if (llqMatch
!= mDNSNULL
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= llqMatch
->qDNSServer
;
9200 else if (!AcceptableResponse
|| !dstaddr
)
9202 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9203 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9204 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9206 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9209 ResourceRecord
*const rr
= &m
->rec
.r
.resrec
;
9210 if (Querier_ResourceRecordIsAnswer(rr
, querier
))
9212 const mdns_resolver_type_t resolver_type
= mdns_querier_get_resolver_type(querier
);
9213 if ((resolver_type
== mdns_resolver_type_normal
) &&
9214 (mdns_querier_get_over_tcp_reason(querier
) != mdns_query_over_tcp_reason_null
))
9216 rr
->protocol
= mdns_resolver_type_tcp
;
9220 rr
->protocol
= resolver_type
;
9222 mdns_replace(&rr
->dnsservice
, uDNSService
);
9223 AcceptableResponse
= mDNStrue
;
9229 const DNSQuestion
*q
;
9230 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9233 // We could potentially lookup the DNS server based on the source address, but that may not work always
9234 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9235 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9236 // on the "id" and "source port", then this response answers the question and assume the response
9237 // came from the same DNS server that we sent the query to.
9238 q
= ExpectingUnicastResponseForRecord(m
, srcaddr
, ResponseSrcLocal
, dstport
, response
->h
.id
, &m
->rec
.r
, !dstaddr
);
9241 AcceptableResponse
= mDNStrue
;
9244 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q
->InterfaceID
, q
->qname
.c
, DNSTypeName(q
->qtype
));
9245 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9246 m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
= q
->qDNSServer
;
9251 // Accept all remaining records in this unicast response to an mDNS query.
9252 recordAcceptedInResponse
= mDNStrue
;
9253 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
9254 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME
" (" PUB_S
")",
9255 q
->request_id
, mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
9260 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9261 // the question. The code below does that. So, make this record unacceptable for now
9264 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m
->rec
.r
.resrec
.name
->c
);
9265 AcceptableResponse
= mDNSfalse
;
9271 else if (llintf
&& llintf
->IgnoreIPv4LL
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_A
)
9273 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9274 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9275 // To work with these broken routers, client devices need to blacklist these broken
9276 // routers and ignore their bogus ARP responses. Some devices implement a technique
9277 // such as the one described in US Patent 7436783, which lets clients detect and
9278 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9280 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9281 // approach of just detecting these broken routers and completely disabling IPv4
9282 // link-local communication on interfaces where a broken router is detected.
9283 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9284 // that are deemed “safe” for IPv4 link-local communication;
9285 // the flag is cleared on interfaces where a broken router is detected.
9287 // OS X and iOS will not even try to communicate with an IPv4
9288 // link-local destination on an interface without the IFEF_ARPLL flag set.
9289 // This can cause some badly written applications to freeze for a long time if they
9290 // attempt to connect to an IPv4 link-local destination address and then wait for
9291 // that connection attempt to time out before trying other candidate addresses.
9293 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9294 // records on interfaces where we know the OS will be unwilling even to attempt
9295 // communication with those IPv4 link-local destination addresses.
9296 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9298 const CacheRecord
*const rr
= &m
->rec
.r
;
9299 const RDataBody2
*const rdb
= (RDataBody2
*)rr
->smallrdatastorage
.data
;
9300 if (mDNSv4AddressIsLinkLocal(&rdb
->ipv4
))
9302 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m
, &m
->rec
.r
));
9303 mDNSCoreResetRecord(m
);
9308 // 1. Check that this packet resource record does not conflict with any of ours
9309 if (ResponseIsMDNS
&& m
->rec
.r
.resrec
.rrtype
!= kDNSType_NSEC
)
9311 if (m
->CurrentRecord
)
9312 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
9313 m
->CurrentRecord
= m
->ResourceRecords
;
9314 while (m
->CurrentRecord
)
9316 AuthRecord
*rr
= m
->CurrentRecord
;
9317 m
->CurrentRecord
= rr
->next
;
9318 // We accept all multicast responses, and unicast responses resulting from queries we issued
9319 // For other unicast responses, this code accepts them only for responses with an
9320 // (apparently) local source address that pertain to a record of our own that's in probing state
9321 if (!AcceptableResponse
&& !(ResponseSrcLocal
&& rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)) continue;
9323 if (PacketRRMatchesSignature(&m
->rec
.r
, rr
)) // If interface, name, type (if shared record) and class match...
9325 // ... check to see if type and rdata are identical
9326 if (IdenticalSameNameRecord(&m
->rec
.r
.resrec
, &rr
->resrec
))
9328 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9329 if (m
->rec
.r
.resrec
.rroriginalttl
>= rr
->resrec
.rroriginalttl
/2 || m
->SleepState
)
9331 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9332 if (rr
->ImmedAnswer
== InterfaceID
) { rr
->ImmedAnswer
= mDNSNULL
; rr
->ImmedUnicast
= mDNSfalse
; }
9336 if (rr
->ImmedAnswer
== mDNSNULL
) { rr
->ImmedAnswer
= InterfaceID
; m
->NextScheduledResponse
= m
->timenow
; }
9337 else if (rr
->ImmedAnswer
!= InterfaceID
) { rr
->ImmedAnswer
= mDNSInterfaceMark
; m
->NextScheduledResponse
= m
->timenow
; }
9340 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9341 else if (m
->rec
.r
.resrec
.rroriginalttl
> 0 && PacketRRConflict(m
, rr
, &m
->rec
.r
))
9343 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9344 m
->rec
.r
.resrec
.rdatahash
, CRDisplayString(m
, &m
->rec
.r
), IIDPrintable(InterfaceID
));
9345 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9347 // If this record is marked DependentOn another record for conflict detection purposes,
9348 // then *that* record has to be bumped back to probing state to resolve the conflict
9349 if (rr
->DependentOn
)
9351 while (rr
->DependentOn
) rr
= rr
->DependentOn
;
9352 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr
->resrec
.rdatahash
, ARDisplayString(m
, rr
));
9355 // If we've just whacked this record's ProbeCount, don't need to do it again
9356 if (rr
->ProbeCount
> DefaultProbeCountForTypeUnique
)
9357 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m
, rr
));
9358 else if (rr
->ProbeCount
== DefaultProbeCountForTypeUnique
)
9359 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m
, rr
));
9362 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr
, mDNSVal16(srcport
), CRDisplayString(m
, &m
->rec
.r
));
9363 // If we'd previously verified this record, put it back to probing state and try again
9364 if (rr
->resrec
.RecordType
== kDNSRecordTypeVerified
)
9366 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m
, rr
));
9367 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
9368 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9369 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9370 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9371 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9372 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
+ 1;
9373 rr
->AnnounceCount
= InitialAnnounceCount
;
9374 InitializeLastAPTime(m
, rr
);
9375 RecordProbeFailure(m
, rr
); // Repeated late conflicts also cause us to back off to the slower probing rate
9377 // If we're probing for this record, we just failed
9378 else if (rr
->resrec
.RecordType
== kDNSRecordTypeUnique
)
9380 // At this point in the code, we're probing for uniqueness.
9381 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9382 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9383 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9384 if (!mDNSCoreRegisteredProxyRecord(m
, rr
))
9386 if ((rr
->ProbingConflictCount
== 0) || (m
->MPktNum
!= rr
->LastConflictPktNum
))
9388 const NetworkInterfaceInfo
*const intf
= FirstInterfaceForID(m
, InterfaceID
);
9389 rr
->ProbingConflictCount
++;
9390 rr
->LastConflictPktNum
= m
->MPktNum
;
9391 if (ResponseMCast
&& (!intf
|| intf
->SupportsUnicastMDNSResponse
) &&
9392 (rr
->ProbingConflictCount
<= kMaxAllowedMCastProbingConflicts
))
9394 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9395 "spurious multicast conflict (%d/%d) via interface %d for %s",
9396 rr
->ProbeCount
, kProbingConflictPauseDuration
, rr
->ProbingConflictCount
,
9397 kMaxAllowedMCastProbingConflicts
, IIDPrintable(InterfaceID
), ARDisplayString(m
, rr
));
9398 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
9399 rr
->LastAPTime
= m
->timenow
+ kProbingConflictPauseDuration
- rr
->ThisAPInterval
;
9400 SetNextAnnounceProbeTime(m
, rr
);
9404 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9405 rr
->ProbeCount
, ARDisplayString(m
, rr
), ResponseMCast
? "multi" : "uni", IIDPrintable(InterfaceID
));
9406 m
->mDNSStats
.NameConflicts
++;
9407 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9408 // See if this record was also registered with any D2D plugins.
9409 D2D_stop_advertising_record(rr
);
9411 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9416 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9417 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9418 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9419 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9420 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9421 else if (rr
->resrec
.RecordType
== kDNSRecordTypeKnownUnique
)
9423 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m
, rr
));
9424 m
->mDNSStats
.KnownUniqueNameConflicts
++;
9425 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9426 D2D_stop_advertising_record(rr
);
9428 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_conflict
);
9431 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
9434 // Else, matching signature, different type or rdata, but not a considered a conflict.
9435 // If the packet record has the cache-flush bit set, then we check to see if we
9436 // have any record(s) of the same type that we should re-assert to rescue them
9437 // (see note about "multi-homing and bridged networks" at the end of this function).
9438 else if ((m
->rec
.r
.resrec
.rrtype
== rr
->resrec
.rrtype
) &&
9439 (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) &&
9440 ((mDNSu32
)(m
->timenow
- rr
->LastMCTime
) > (mDNSu32
)mDNSPlatformOneSecond
/2) &&
9441 ResourceRecordIsValidAnswer(rr
))
9443 rr
->ImmedAnswer
= mDNSInterfaceMark
;
9444 m
->NextScheduledResponse
= m
->timenow
;
9450 if (!AcceptableResponse
)
9452 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9453 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9454 not_answer_but_required_for_dnssec
= adds_denial_records_in_cache_record(&m
->rec
.r
.resrec
,
9455 querier
!= mDNSNULL
&& mdns_querier_get_dnssec_ok(querier
), &denial_of_existence_records
);
9457 not_answer_but_required_for_dnssec
= mDNSfalse
;
9459 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9460 AcceptableResponse
= IsResponseAcceptable(m
, CacheFlushRecords
);
9462 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9463 if (AcceptableResponse
) mdns_replace(&m
->rec
.r
.resrec
.dnsservice
, uDNSService
);
9465 if (AcceptableResponse
) m
->rec
.r
.resrec
.rDNSServer
= uDNSServer
;
9469 // 2. See if we want to add this packet resource record to our cache
9470 // We only try to cache answers if we have a cache to put them in
9471 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9472 if (!AcceptableResponse
) {
9473 const char* savedString
= "";
9474 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9475 savedString
= (not_answer_but_required_for_dnssec
? "Saved for DNSSEC" : "");
9477 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S
" %s",
9478 mDNSVal16(response
->h
.id
), CRDisplayString(m
, &m
->rec
.r
), savedString
);
9481 if (m
->rrcache_size
&& AcceptableResponse
)
9483 const mDNSu32 slot
= HashSlotFromNameHash(m
->rec
.r
.resrec
.namehash
);
9484 CacheGroup
*cg
= CacheGroupForRecord(m
, &m
->rec
.r
.resrec
);
9485 CacheRecord
*rr
= mDNSNULL
;
9487 // 2a. Check if this packet resource record is already in our cache.
9488 rr
= mDNSCoreReceiveCacheCheck(m
, response
, LLQType
, slot
, cg
, &cfp
, InterfaceID
);
9490 // If packet resource record not in our cache, add it now
9491 // (unless it is just a deletion of a record we never had, in which case we don't care)
9492 if (!rr
&& m
->rec
.r
.resrec
.rroriginalttl
> 0)
9494 const mDNSBool AddToCFList
= (m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) && (LLQType
!= uDNS_LLQ_Events
);
9498 delay
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
);
9500 delay
= CheckForSoonToExpireRecords(m
, m
->rec
.r
.resrec
.name
, m
->rec
.r
.resrec
.namehash
);
9502 // If unique, assume we may have to delay delivery of this 'add' event.
9503 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9504 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9505 // to schedule an mDNS_Execute task at the appropriate time.
9506 rr
= CreateNewCacheEntry(m
, slot
, cg
, delay
, mDNStrue
, srcaddr
);
9509 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9510 set_denial_records_in_cache_record(rr
, &denial_of_existence_records
);
9511 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9513 rr
->responseFlags
= response
->h
.flags
;
9518 cfp
= &rr
->NextInCFList
;
9519 *cfp
= (CacheRecord
*)1;
9521 else if (rr
->DelayDelivery
)
9523 ScheduleNextCacheCheckTime(m
, slot
, rr
->DelayDelivery
);
9528 mDNSCoreResetRecord(m
);
9532 mDNSCoreResetRecord(m
);
9534 // If we've just received one or more records with their cache flush bits set,
9535 // then scan that cache slot to see if there are any old stale records we need to flush
9536 while (CacheFlushRecords
!= (CacheRecord
*)1)
9538 CacheRecord
*r1
= CacheFlushRecords
, *r2
;
9539 const mDNSu32 slot
= HashSlotFromNameHash(r1
->resrec
.namehash
);
9540 const CacheGroup
*cg
= CacheGroupForRecord(m
, &r1
->resrec
);
9541 mDNSBool purgedRecords
= mDNSfalse
;
9542 CacheFlushRecords
= CacheFlushRecords
->NextInCFList
;
9543 r1
->NextInCFList
= mDNSNULL
;
9545 // Look for records in the cache with the same signature as this new one with the cache flush
9546 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9547 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9548 // We make these TTL adjustments *only* for records that still have *more* than one second
9549 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9550 // (and now has half a second remaining) could inadvertently get its life extended, by either
9551 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9552 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9553 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9554 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9555 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9556 // To avoid this, we need to ensure that the cache flushing operation will only act to
9557 // *decrease* a record's remaining lifetime, never *increase* it.
9558 for (r2
= cg
? cg
->members
: mDNSNULL
; r2
; r2
=r2
->next
)
9560 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9566 if (!r1
->resrec
.InterfaceID
)
9568 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9569 match
= (r1
->resrec
.dnsservice
== r2
->resrec
.dnsservice
) ? mDNStrue
: mDNSfalse
;
9571 id1
= (r1
->resrec
.rDNSServer
? r1
->resrec
.rDNSServer
->resGroupID
: 0);
9572 id2
= (r2
->resrec
.rDNSServer
? r2
->resrec
.rDNSServer
->resGroupID
: 0);
9577 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9583 // For Unicast (null InterfaceID) the resolver IDs should also match
9584 if ((r1
->resrec
.InterfaceID
== r2
->resrec
.InterfaceID
) &&
9585 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9586 (r1
->resrec
.InterfaceID
|| match
) &&
9588 (r1
->resrec
.InterfaceID
|| (id1
== id2
)) &&
9590 r1
->resrec
.rrtype
== r2
->resrec
.rrtype
&&
9591 r1
->resrec
.rrclass
== r2
->resrec
.rrclass
9592 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9593 // 2 RRSIGs need to cover the same DNS type to be identified as one RRSET, and have the same TTL
9594 && are_records_in_the_same_cache_set_for_dnssec(&r1
->resrec
, &r2
->resrec
)
9598 if (r1
->resrec
.mortality
== Mortality_Mortal
&& r2
->resrec
.mortality
!= Mortality_Mortal
)
9600 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1
, r2
);
9601 r1
->resrec
.mortality
= Mortality_Immortal
; // Immortalize the replacement record
9604 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9605 // else, if record is old, mark it to be flushed
9606 if (m
->timenow
- r2
->TimeRcvd
< mDNSPlatformOneSecond
&& RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9608 // If we find mismatched TTLs in an RRSet, correct them.
9609 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9610 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9611 // which we treat as a goodbye followed by an addition) and in that case it would be
9612 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9614 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9615 // because certain early Bonjour devices are known to have this specific mismatch, and
9616 // there's no point filling syslog with messages about something we already know about.
9617 // We also don't log this for uDNS responses, since a caching name server is obliged
9618 // to give us an aged TTL to correct for how long it has held the record,
9619 // so our received TTLs are expected to vary in that case
9621 // We also suppress log message in the case of SRV records that are received
9622 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9623 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9625 if (r2
->resrec
.rroriginalttl
!= r1
->resrec
.rroriginalttl
&& r1
->resrec
.rroriginalttl
> 1)
9627 if (!(r2
->resrec
.rroriginalttl
== 240 && r1
->resrec
.rroriginalttl
== 60 && r2
->resrec
.rrtype
== kDNSType_TXT
) &&
9628 !(r2
->resrec
.rroriginalttl
== 120 && r1
->resrec
.rroriginalttl
== 4500 && r2
->resrec
.rrtype
== kDNSType_SRV
) &&
9630 LogInfo("Correcting TTL from %4d to %4d for %s",
9631 r2
->resrec
.rroriginalttl
, r1
->resrec
.rroriginalttl
, CRDisplayString(m
, r2
));
9632 r2
->resrec
.rroriginalttl
= r1
->resrec
.rroriginalttl
;
9634 r2
->TimeRcvd
= m
->timenow
;
9635 SetNextCacheCheckTimeForRecord(m
, r2
);
9637 else if (r2
->resrec
.InterfaceID
) // else, if record is old, mark it to be flushed
9639 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1
, m
->timenow
- r1
->TimeRcvd
, RRExpireTime(r1
) - m
->timenow
, CRDisplayString(m
, r1
));
9640 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2
, m
->timenow
- r2
->TimeRcvd
, RRExpireTime(r2
) - m
->timenow
, CRDisplayString(m
, r2
));
9641 // We set stale records to expire in one second.
9642 // This gives the owner a chance to rescue it if necessary.
9643 // This is important in the case of multi-homing and bridged networks:
9644 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9645 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9646 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9647 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9648 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9649 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9651 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9652 // final expiration queries for this record.
9654 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9655 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9656 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9657 // <rdar://problem/5636422> Updating TXT records is too slow
9658 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9659 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9660 if (r2
->TimeRcvd
== m
->timenow
&& r2
->resrec
.rroriginalttl
== 1 && r2
->UnansweredQueries
== MaxUnansweredQueries
)
9662 LogInfo("Cache flush for DE record %s", CRDisplayString(m
, r2
));
9663 r2
->resrec
.rroriginalttl
= 0;
9665 else if (RRExpireTime(r2
) - m
->timenow
> mDNSPlatformOneSecond
)
9667 // We only set a record to expire in one second if it currently has *more* than a second to live
9668 // If it's already due to expire in a second or less, we just leave it alone
9669 r2
->resrec
.rroriginalttl
= 1;
9670 r2
->UnansweredQueries
= MaxUnansweredQueries
;
9671 r2
->TimeRcvd
= m
->timenow
- 1;
9672 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9673 // that we marked for deletion via an explicit DE record
9675 SetNextCacheCheckTimeForRecord(m
, r2
);
9679 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9680 if (r2
->resrec
.mortality
== Mortality_Ghost
)
9683 for (q
= m
->Questions
; q
; q
=q
->next
)
9685 if (!q
->LongLived
&& ActiveQuestion(q
) &&
9686 CacheRecordAnswersQuestion(r2
, q
) &&
9687 q
->metrics
.expiredAnswerState
== ExpiredAnswer_AnsweredWithExpired
)
9689 q
->metrics
.expiredAnswerState
= ExpiredAnswer_ExpiredAnswerChanged
;
9694 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9695 mDNS_PurgeCacheResourceRecord(m
, r2
);
9696 purgedRecords
= mDNStrue
;
9701 if (r1
->DelayDelivery
) // If we were planning to delay delivery of this record, see if we still need to
9703 if (r1
->resrec
.InterfaceID
)
9705 r1
->DelayDelivery
= CheckForSoonToExpireRecords(m
, r1
->resrec
.name
, r1
->resrec
.namehash
);
9709 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9710 // them to be deleted before any ADD events for this record.
9711 r1
->DelayDelivery
= purgedRecords
? NonZeroTime(m
->timenow
) : 0;
9713 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9714 if (!r1
->DelayDelivery
) CacheRecordDeferredAdd(m
, r1
);
9715 else ScheduleNextCacheCheckTime(m
, slot
, r1
->DelayDelivery
);
9719 // See if we need to generate negative cache entries for unanswered unicast questions
9720 mDNSCoreReceiveNoUnicastAnswers(m
, response
, end
, dstaddr
, dstport
, InterfaceID
,
9721 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9722 querier
, uDNSService
,
9724 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9725 &denial_of_existence_records
,
9729 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9730 destroy_denial_of_existence_records_t_if_nonnull(denial_of_existence_records
);
9731 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9734 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9735 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9736 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9737 // that warrants waking the sleeping host.
9738 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9740 mDNSlocal
void ScheduleWakeupForList(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
, AuthRecord
*const thelist
)
9742 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9743 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9744 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9745 // simple, we use the same mechanism for both lists.
9748 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9751 m
->CurrentRecord
= thelist
;
9752 while (m
->CurrentRecord
)
9754 AuthRecord
*const rr
= m
->CurrentRecord
;
9755 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&& mDNSSameEthAddress(&rr
->WakeUp
.HMAC
, e
))
9757 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m
, rr
));
9758 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
9760 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
9761 m
->CurrentRecord
= rr
->next
;
9765 mDNSlocal
void ScheduleWakeup(mDNS
*const m
, mDNSInterfaceID InterfaceID
, mDNSEthAddr
*e
)
9767 if (!e
->l
[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9768 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->DuplicateRecords
);
9769 ScheduleWakeupForList(m
, InterfaceID
, e
, m
->ResourceRecords
);
9772 mDNSlocal
void SPSRecordCallback(mDNS
*const m
, AuthRecord
*const ar
, mStatus result
)
9774 if (result
&& result
!= mStatus_MemFree
)
9775 LogInfo("SPS Callback %d %s", result
, ARDisplayString(m
, ar
));
9777 if (result
== mStatus_NameConflict
)
9780 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m
, ar
->resrec
.InterfaceID
), &ar
->WakeUp
.HMAC
, ARDisplayString(m
, ar
));
9781 if (ar
->WakeUp
.HMAC
.l
[0])
9783 SendWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.IMAC
, &ar
->WakeUp
.password
, mDNSfalse
); // Send one wakeup magic packet
9784 ScheduleWakeup(m
, ar
->resrec
.InterfaceID
, &ar
->WakeUp
.HMAC
); // Schedule all other records with the same owner to be woken
9789 if (result
== mStatus_NameConflict
|| result
== mStatus_MemFree
)
9792 mDNSPlatformMemFree(ar
);
9793 mDNS_UpdateAllowSleep(m
);
9797 mDNSlocal mDNSu8
*GetValueForMACAddr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSEthAddr
*eth
)
9804 for (i
= 0; ptr
< limit
&& *ptr
!= ' ' && i
< 17; i
++, ptr
++)
9806 hval
= HexVal(*ptr
);
9812 else if (*ptr
== ':')
9816 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons
, val
);
9819 eth
->b
[colons
] = val
;
9826 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons
);
9829 eth
->b
[colons
] = val
;
9833 mDNSlocal mDNSu8
*GetValueForIPv6Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv6Addr
*v6
)
9838 int digitsProcessed
;
9843 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9844 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9846 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9847 // the result in "v6"
9849 numColons
= numBytes
= value
= digitsProcessed
= zeroFillStart
= 0;
9850 while (ptr
< limit
&& *ptr
!= ' ')
9852 hval
= HexVal(*ptr
);
9857 digitsProcessed
= 1;
9859 else if (*ptr
== ':')
9861 if (!digitsProcessed
)
9863 // If we have already seen a "::", we should not see one more. Handle the special
9867 // if we never filled any bytes and the next character is space (we have reached the end)
9869 if (!numBytes
&& (ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
9871 mDNSPlatformMemZero(v6
->b
, 16);
9874 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart
);
9878 // We processed "::". We need to fill zeroes later. For now, mark the
9879 // point where we will start filling zeroes from.
9880 zeroFillStart
= numBytes
;
9883 else if ((ptr
+ 1) < limit
&& *(ptr
+ 1) == ' ')
9885 // We have a trailing ":" i.e., no more characters after ":"
9886 LogMsg("GetValueForIPv6Addr: Trailing colon");
9891 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9892 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9893 // filled here is 12 and 13.
9894 if (numBytes
> 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes
); return mDNSNULL
; }
9896 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
9897 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
9898 digitsProcessed
= value
= 0;
9900 // Make sure that we did not fill the 13th and 14th byte above
9901 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes
); return mDNSNULL
; }
9907 // We should be processing the last set of bytes following the last ":" here
9908 if (!digitsProcessed
)
9910 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes
);
9914 if (numBytes
> 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes
); return mDNSNULL
; }
9915 v6addr
[numBytes
++] = (mDNSu8
) ((value
>> 8) & 0xFF);
9916 v6addr
[numBytes
++] = (mDNSu8
) (value
& 0xFF);
9921 for (i
= 0; i
< zeroFillStart
; i
++)
9922 v6
->b
[i
] = v6addr
[i
];
9923 for (j
= i
, n
= 0; n
< 16 - numBytes
; j
++, n
++)
9925 for (; j
< 16; i
++, j
++)
9926 v6
->b
[j
] = v6addr
[i
];
9928 else if (numBytes
== 16)
9929 mDNSPlatformMemCopy(v6
->b
, v6addr
, 16);
9932 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes
);
9938 mDNSlocal mDNSu8
*GetValueForIPv4Addr(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSv4Addr
*v4
)
9944 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
9946 if (*ptr
>= '0' && *ptr
<= '9')
9947 val
= val
* 10 + *ptr
- '0';
9948 else if (*ptr
== '.')
9950 if (val
> 255 || dots
>= 3)
9952 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
);
9955 v4
->b
[dots
++] = val
;
9960 // We have a zero at the end and if we reached that, then we are done.
9961 if (*ptr
== 0 && ptr
== limit
- 1 && dots
== 3)
9966 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr
, *ptr
, limit
, dots
); return mDNSNULL
; }
9969 if (dots
!= 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots
); return mDNSNULL
; }
9974 mDNSlocal mDNSu8
*GetValueForKeepalive(mDNSu8
*ptr
, mDNSu8
*limit
, mDNSu32
*value
)
9979 for ( ; ptr
< limit
&& *ptr
!= ' '; ptr
++)
9981 if (*ptr
< '0' || *ptr
> '9')
9983 // We have a zero at the end and if we reached that, then we are done.
9984 if (*ptr
== 0 && ptr
== limit
- 1)
9989 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr
, ptr
, limit
, *(ptr
+ 1)); return mDNSNULL
; }
9991 val
= val
* 10 + *ptr
- '0';
9997 mDNSexport mDNSBool
mDNSValidKeepAliveRecord(AuthRecord
*rr
)
9999 mDNSAddr laddr
, raddr
;
10001 mDNSIPPort lport
, rport
;
10002 mDNSu32 timeout
, seq
, ack
;
10005 if (!mDNS_KeepaliveRecord(&rr
->resrec
))
10010 timeout
= seq
= ack
= 0;
10012 laddr
= raddr
= zeroAddr
;
10013 lport
= rport
= zeroIPPort
;
10016 mDNS_ExtractKeepaliveInfo(rr
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10018 if (mDNSAddressIsZero(&laddr
) || mDNSIPPortIsZero(lport
) ||
10019 mDNSAddressIsZero(&raddr
) || mDNSIPPortIsZero(rport
) ||
10020 mDNSEthAddressIsZero(eth
))
10029 mDNSlocal
void mDNS_ExtractKeepaliveInfo(AuthRecord
*ar
, mDNSu32
*timeout
, mDNSAddr
*laddr
, mDNSAddr
*raddr
, mDNSEthAddr
*eth
, mDNSu32
*seq
,
10030 mDNSu32
*ack
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu16
*win
)
10032 if (ar
->resrec
.rrtype
!= kDNSType_NULL
)
10035 if (mDNS_KeepaliveRecord(&ar
->resrec
))
10037 int len
= ar
->resrec
.rdlength
;
10038 mDNSu8
*ptr
= &ar
->resrec
.rdata
->u
.txt
.c
[1];
10039 mDNSu8
*limit
= ptr
+ len
- 1; // Exclude the first byte that is the length
10042 while (ptr
< limit
)
10044 mDNSu8 param
= *ptr
;
10045 ptr
+= 2; // Skip the letter and the "="
10048 laddr
->type
= mDNSAddrType_IPv4
;
10049 ptr
= GetValueForIPv4Addr(ptr
, limit
, &laddr
->ip
.v4
);
10051 else if (param
== 'd')
10053 raddr
->type
= mDNSAddrType_IPv4
;
10054 ptr
= GetValueForIPv4Addr(ptr
, limit
, &raddr
->ip
.v4
);
10056 else if (param
== 'H')
10058 laddr
->type
= mDNSAddrType_IPv6
;
10059 ptr
= GetValueForIPv6Addr(ptr
, limit
, &laddr
->ip
.v6
);
10061 else if (param
== 'D')
10063 raddr
->type
= mDNSAddrType_IPv6
;
10064 ptr
= GetValueForIPv6Addr(ptr
, limit
, &raddr
->ip
.v6
);
10066 else if (param
== 'm')
10068 ptr
= GetValueForMACAddr(ptr
, limit
, eth
);
10072 ptr
= GetValueForKeepalive(ptr
, limit
, &value
);
10074 if (!ptr
) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10076 // Extract everything in network order so that it is easy for sending a keepalive and also
10077 // for matching incoming TCP packets
10082 //if (*timeout < 120) *timeout = 120;
10093 lport
->NotAnInteger
= swap16((mDNSu16
)value
);
10096 rport
->NotAnInteger
= swap16((mDNSu16
)value
);
10099 *seq
= swap32(value
);
10102 *ack
= swap32(value
);
10105 *win
= swap16((mDNSu16
)value
);
10108 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param
);
10112 ptr
++; // skip the space
10117 // 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
10118 // the clients need not retrieve this information from the auth record again.
10119 mDNSlocal AuthRecord
* mDNS_MatchKeepaliveInfo(mDNS
*const m
, const mDNSAddr
* pladdr
, const mDNSAddr
* praddr
, const mDNSIPPort plport
,
10120 const mDNSIPPort prport
, mDNSu32
*rseq
, mDNSu32
*rack
)
10123 mDNSAddr laddr
, raddr
;
10125 mDNSIPPort lport
, rport
;
10126 mDNSu32 timeout
, seq
, ack
;
10129 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10131 timeout
= seq
= ack
= 0;
10133 laddr
= raddr
= zeroAddr
;
10134 lport
= rport
= zeroIPPort
;
10136 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10138 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10140 // Did we parse correctly ?
10141 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10143 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10147 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10148 &laddr
, pladdr
, &raddr
, praddr
, mDNSVal16(lport
), mDNSVal16(plport
), mDNSVal16(rport
), mDNSVal16(prport
));
10150 // Does it match the incoming TCP packet ?
10151 if (mDNSSameAddress(&laddr
, pladdr
) && mDNSSameAddress(&raddr
, praddr
) && mDNSSameIPPort(lport
, plport
) && mDNSSameIPPort(rport
, prport
))
10153 // returning in network order
10162 mDNSlocal
void mDNS_SendKeepalives(mDNS
*const m
)
10166 for (ar
= m
->ResourceRecords
; ar
; ar
=ar
->next
)
10168 mDNSu32 timeout
, seq
, ack
;
10170 mDNSAddr laddr
, raddr
;
10172 mDNSIPPort lport
, rport
;
10174 timeout
= seq
= ack
= 0;
10177 laddr
= raddr
= zeroAddr
;
10178 lport
= rport
= zeroIPPort
;
10180 if (!ar
->WakeUp
.HMAC
.l
[0]) continue;
10182 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10184 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10186 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10189 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10191 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10192 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10193 if (!ar
->KATimeExpire
|| (m
->timenow
- ar
->KATimeExpire
>= 0))
10195 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10196 ar
->KATimeExpire
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
10198 if (m
->NextScheduledKA
- ar
->KATimeExpire
> 0)
10199 m
->NextScheduledKA
= ar
->KATimeExpire
;
10203 mDNSlocal
void mDNS_SendKeepaliveACK(mDNS
*const m
, AuthRecord
*ar
)
10205 mDNSu32 timeout
, seq
, ack
, seqInc
;
10207 mDNSAddr laddr
, raddr
;
10209 mDNSIPPort lport
, rport
;
10212 if (ar
== mDNSNULL
)
10214 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10218 timeout
= seq
= ack
= 0;
10221 laddr
= raddr
= zeroAddr
;
10222 lport
= rport
= zeroIPPort
;
10224 mDNS_ExtractKeepaliveInfo(ar
, &timeout
, &laddr
, &raddr
, ð
, &seq
, &ack
, &lport
, &rport
, &win
);
10226 if (!timeout
|| mDNSAddressIsZero(&laddr
) || mDNSAddressIsZero(&raddr
) || !seq
|| !ack
|| mDNSIPPortIsZero(lport
) || mDNSIPPortIsZero(rport
) || !win
)
10228 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m
, ar
));
10232 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10233 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10234 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10235 // it's converted to host byte order before incrementing it by one.
10236 ptr
= (mDNSu8
*)&seq
;
10237 seqInc
= (mDNSu32
)((ptr
[0] << 24) | (ptr
[1] << 16) | (ptr
[2] << 8) | ptr
[3]) + 1;
10238 ptr
[0] = (mDNSu8
)((seqInc
>> 24) & 0xFF);
10239 ptr
[1] = (mDNSu8
)((seqInc
>> 16) & 0xFF);
10240 ptr
[2] = (mDNSu8
)((seqInc
>> 8) & 0xFF);
10241 ptr
[3] = (mDNSu8
)((seqInc
) & 0xFF);
10242 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr
, &raddr
, mDNSVal16(lport
), mDNSVal16(rport
));
10243 mDNSPlatformSendKeepalive(&laddr
, &raddr
, &lport
, &rport
, seq
, ack
, win
);
10246 mDNSlocal
void mDNSCoreReceiveUpdate(mDNS
*const m
,
10247 const DNSMessage
*const msg
, const mDNSu8
*end
,
10248 const mDNSAddr
*srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, mDNSIPPort dstport
,
10249 const mDNSInterfaceID InterfaceID
)
10253 mDNSu8
*p
= m
->omsg
.data
;
10254 OwnerOptData owner
= zeroOwner
; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10255 mDNSu32 updatelease
= 0;
10258 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10259 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10260 srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), InterfaceID
,
10261 msg
->h
.numQuestions
, msg
->h
.numQuestions
== 1 ? ", " : "s,",
10262 msg
->h
.numAnswers
, msg
->h
.numAnswers
== 1 ? ", " : "s,",
10263 msg
->h
.numAuthorities
, msg
->h
.numAuthorities
== 1 ? "y, " : "ies,",
10264 msg
->h
.numAdditionals
, msg
->h
.numAdditionals
== 1 ? " " : "s", end
- msg
->data
);
10266 if (!InterfaceID
|| !m
->SPSSocket
|| !mDNSSameIPPort(dstport
, m
->SPSSocket
->port
)) return;
10268 if (mDNS_PacketLoggingEnabled
)
10269 DumpPacket(mStatus_NoError
, mDNSfalse
, "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
, InterfaceID
);
10271 ptr
= LocateOptRR(msg
, end
, DNSOpt_LeaseData_Space
+ DNSOpt_OwnerData_ID_Space
);
10274 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, 0, kDNSRecordTypePacketAdd
, &m
->rec
);
10275 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& m
->rec
.r
.resrec
.rrtype
== kDNSType_OPT
)
10278 const rdataOPT
*const e
= (const rdataOPT
*)&m
->rec
.r
.resrec
.rdata
->u
.data
[m
->rec
.r
.resrec
.rdlength
];
10279 for (o
= &m
->rec
.r
.resrec
.rdata
->u
.opt
[0]; o
< e
; o
++)
10281 if (o
->opt
== kDNSOpt_Lease
) updatelease
= o
->u
.updatelease
;
10282 else if (o
->opt
== kDNSOpt_Owner
&& o
->u
.owner
.vers
== 0) owner
= o
->u
.owner
;
10285 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10288 InitializeDNSMessage(&m
->omsg
.h
, msg
->h
.id
, UpdateRespFlags
);
10290 if (!updatelease
|| !owner
.HMAC
.l
[0])
10292 static int msgs
= 0;
10296 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr
, mDNSVal16(srcport
),
10297 !updatelease
? " No lease" : "", !owner
.HMAC
.l
[0] ? " No owner" : "");
10299 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_FormErr
;
10301 else if (m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
> MAX_PROXY_RECORDS
)
10303 static int msgs
= 0;
10307 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr
, mDNSVal16(srcport
),
10308 m
->ProxyRecords
, msg
->h
.mDNS_numUpdates
, m
->ProxyRecords
+ msg
->h
.mDNS_numUpdates
, MAX_PROXY_RECORDS
);
10310 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10314 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
10316 if (updatelease
> 24 * 60 * 60)
10317 updatelease
= 24 * 60 * 60;
10319 if (updatelease
> 0x40000000UL
/ mDNSPlatformOneSecond
)
10320 updatelease
= 0x40000000UL
/ mDNSPlatformOneSecond
;
10322 ptr
= LocateAuthorities(msg
, end
);
10324 // Clear any stale TCP keepalive records that may exist
10325 ClearKeepaliveProxyRecords(m
, &owner
, m
->DuplicateRecords
, InterfaceID
);
10326 ClearKeepaliveProxyRecords(m
, &owner
, m
->ResourceRecords
, InterfaceID
);
10328 for (i
= 0; i
< msg
->h
.mDNS_numUpdates
&& ptr
&& ptr
< end
; i
++)
10330 ptr
= GetLargeResourceRecord(m
, msg
, ptr
, end
, InterfaceID
, kDNSRecordTypePacketAuth
, &m
->rec
);
10331 if (ptr
&& m
->rec
.r
.resrec
.RecordType
!= kDNSRecordTypePacketNegative
)
10333 mDNSu16 RDLengthMem
= GetRDLengthMem(&m
->rec
.r
.resrec
);
10334 AuthRecord
*ar
= (AuthRecord
*) mDNSPlatformMemAllocateClear(sizeof(AuthRecord
) - sizeof(RDataBody
) + RDLengthMem
);
10337 m
->omsg
.h
.flags
.b
[1] |= kDNSFlag1_RC_Refused
;
10342 mDNSu8 RecordType
= m
->rec
.r
.resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
? kDNSRecordTypeUnique
: kDNSRecordTypeShared
;
10343 m
->rec
.r
.resrec
.rrclass
&= ~kDNSClass_UniqueRRSet
;
10344 // All stale keepalive records have been flushed prior to this loop.
10345 if (!mDNS_KeepaliveRecord(&m
->rec
.r
.resrec
))
10347 ClearIdenticalProxyRecords(m
, &owner
, m
->DuplicateRecords
); // Make sure we don't have any old stale duplicates of this record
10348 ClearIdenticalProxyRecords(m
, &owner
, m
->ResourceRecords
);
10350 mDNS_SetupResourceRecord(ar
, mDNSNULL
, InterfaceID
, m
->rec
.r
.resrec
.rrtype
, m
->rec
.r
.resrec
.rroriginalttl
, RecordType
, AuthRecordAny
, SPSRecordCallback
, ar
);
10351 AssignDomainName(&ar
->namestorage
, m
->rec
.r
.resrec
.name
);
10352 ar
->resrec
.rdlength
= GetRDLength(&m
->rec
.r
.resrec
, mDNSfalse
);
10353 ar
->resrec
.rdata
->MaxRDLength
= RDLengthMem
;
10354 mDNSPlatformMemCopy(ar
->resrec
.rdata
->u
.data
, m
->rec
.r
.resrec
.rdata
->u
.data
, RDLengthMem
);
10355 ar
->ForceMCast
= mDNStrue
;
10356 ar
->WakeUp
= owner
;
10357 if (m
->rec
.r
.resrec
.rrtype
== kDNSType_PTR
)
10359 mDNSs32 t
= ReverseMapDomainType(m
->rec
.r
.resrec
.name
);
10360 if (t
== mDNSAddrType_IPv4
) GetIPv4FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10361 else if (t
== mDNSAddrType_IPv6
) GetIPv6FromName(&ar
->AddressProxy
, m
->rec
.r
.resrec
.name
);
10362 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t
, ar
->AddressProxy
.type
, &ar
->AddressProxy
, ARDisplayString(m
, ar
));
10363 if (ar
->AddressProxy
.type
) SetSPSProxyListChanged(InterfaceID
);
10365 ar
->TimeRcvd
= m
->timenow
;
10366 ar
->TimeExpire
= m
->timenow
+ updatelease
* mDNSPlatformOneSecond
;
10367 if (m
->NextScheduledSPS
- ar
->TimeExpire
> 0)
10368 m
->NextScheduledSPS
= ar
->TimeExpire
;
10369 ar
->KATimeExpire
= 0;
10370 mDNS_Register_internal(m
, ar
);
10373 mDNS_UpdateAllowSleep(m
);
10374 LogSPS("SPS Registered %4d %X %s", m
->ProxyRecords
, RecordType
, ARDisplayString(m
,ar
));
10377 m
->rec
.r
.resrec
.RecordType
= 0; // Clear RecordType to show we're not still using it
10380 if (m
->omsg
.h
.flags
.b
[1] & kDNSFlag1_RC_Mask
)
10382 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr
, mDNSVal16(srcport
));
10383 ClearProxyRecords(m
, &owner
, m
->DuplicateRecords
);
10384 ClearProxyRecords(m
, &owner
, m
->ResourceRecords
);
10388 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10389 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10390 opt
.resrec
.rdlength
= sizeof(rdataOPT
); // One option in this OPT record
10391 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10392 opt
.resrec
.rdata
->u
.opt
[0].opt
= kDNSOpt_Lease
;
10393 opt
.resrec
.rdata
->u
.opt
[0].u
.updatelease
= updatelease
;
10394 p
= PutResourceRecordTTLWithLimit(&m
->omsg
, p
, &m
->omsg
.h
.numAdditionals
, &opt
.resrec
, opt
.resrec
.rroriginalttl
, m
->omsg
.data
+ AbsoluteMaxDNSMessageData
);
10398 if (p
) mDNSSendDNSMessage(m
, &m
->omsg
, p
, InterfaceID
, mDNSNULL
, m
->SPSSocket
, srcaddr
, srcport
, mDNSNULL
, mDNSfalse
);
10399 mDNS_SendKeepalives(m
);
10402 mDNSlocal mDNSu32
mDNSGenerateOwnerOptForInterface(mDNS
*const m
, const mDNSInterfaceID InterfaceID
, DNSMessage
*msg
)
10404 mDNSu8
*ptr
= msg
->data
;
10405 mDNSu8
*end
= mDNSNULL
;
10406 mDNSu32 length
= 0;
10408 NetworkInterfaceInfo
*intf
;
10410 mDNS_SetupResourceRecord(&opt
, mDNSNULL
, mDNSInterface_Any
, kDNSType_OPT
, kStandardTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
10411 opt
.resrec
.rrclass
= NormalMaxDNSMessageData
;
10412 opt
.resrec
.rdlength
= sizeof(rdataOPT
);
10413 opt
.resrec
.rdestimate
= sizeof(rdataOPT
);
10415 intf
= FirstInterfaceForID(m
, InterfaceID
);
10416 SetupOwnerOpt(m
, intf
, &opt
.resrec
.rdata
->u
.opt
[0]);
10418 LogSPS("Generated OPT record : %s", ARDisplayString(m
, &opt
));
10419 end
= PutResourceRecord(msg
, ptr
, &msg
->h
.numAdditionals
, &opt
.resrec
);
10420 if (end
!= mDNSNULL
)
10422 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10423 SwapDNSHeaderBytes(msg
);
10424 length
= (mDNSu32
)(end
- msg
->data
);
10427 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10432 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10433 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10434 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10435 // Really, both should be unified and handled in one place.
10436 mDNSlocal
void mDNSCoreReceiveUpdateR(mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*end
, const mDNSAddr
*srcaddr
, const mDNSInterfaceID InterfaceID
)
10440 mDNSu32 pktlease
= 0, spsupdates
= 0;
10441 const mDNSBool gotlease
= GetPktLease(m
, msg
, end
, &pktlease
);
10442 const mDNSu32 updatelease
= gotlease
? pktlease
: 60 * 60; // If SPS fails to indicate lease time, assume one hour
10443 if (gotlease
) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease
, mDNSVal16(msg
->h
.id
), InterfaceID
);
10445 if (m
->CurrentRecord
)
10446 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m
, m
->CurrentRecord
));
10447 m
->CurrentRecord
= m
->ResourceRecords
;
10448 while (m
->CurrentRecord
)
10450 AuthRecord
*const rr
= m
->CurrentRecord
;
10451 if (rr
->resrec
.InterfaceID
== InterfaceID
|| (!rr
->resrec
.InterfaceID
&& (rr
->ForceMCast
|| IsLocalDomain(rr
->resrec
.name
))))
10452 if (mDNSSameOpaque16(rr
->updateid
, msg
->h
.id
))
10454 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10455 // Clear the updateid when we are done sending on all interfaces.
10456 mDNSu32 scopeid
= mDNSPlatformInterfaceIndexfromInterfaceID(m
, InterfaceID
, mDNStrue
);
10457 if (scopeid
< (sizeof(rr
->updateIntID
) * mDNSNBBY
))
10458 bit_clr_opaque64(rr
->updateIntID
, scopeid
);
10459 if (mDNSOpaque64IsZero(&rr
->updateIntID
))
10460 rr
->updateid
= zeroID
;
10461 rr
->expire
= NonZeroTime(m
->timenow
+ updatelease
* mDNSPlatformOneSecond
);
10463 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
));
10464 if (rr
->WakeUp
.HMAC
.l
[0])
10466 rr
->WakeUp
.HMAC
= zeroEthAddr
; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10467 rr
->RequireGoodbye
= mDNSfalse
; // and we don't want to send goodbye for it
10468 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
10471 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10472 // new records could have been added to the end of the list as a result of that call.
10473 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
10474 m
->CurrentRecord
= rr
->next
;
10476 if (spsupdates
) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10482 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10483 ifname
= InterfaceNameForID(m
, InterfaceID
);
10484 mDNSPlatformMemCopy(&spsaddr
, srcaddr
, sizeof (mDNSAddr
));
10485 mDNSPlatformStoreSPSMACAddr(&spsaddr
, ifname
);
10487 // Store the Owner OPT record for this interface.
10488 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10489 InitializeDNSMessage(&optMsg
.h
, zeroID
, ResponseFlags
);
10490 length
= mDNSGenerateOwnerOptForInterface(m
, InterfaceID
, &optMsg
);
10493 length
+= sizeof(DNSMessageHeader
);
10494 mDNSPlatformStoreOwnerOptRecord(ifname
, &optMsg
, length
);
10498 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10499 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10500 if (m
->SleepLimit
) m
->NextScheduledSPRetry
= m
->timenow
;
10503 mDNSexport
void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
, const domainname
*const name
,
10504 const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
,
10505 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10506 mdns_dns_service_t service
)
10508 DNSServer
*dnsserver
)
10511 if (cr
== &m
->rec
.r
&& m
->rec
.r
.resrec
.RecordType
)
10512 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m
, &m
->rec
.r
));
10514 // Create empty resource record
10515 cr
->resrec
.RecordType
= kDNSRecordTypePacketNegative
;
10516 cr
->resrec
.InterfaceID
= InterfaceID
;
10517 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10518 mdns_replace(&cr
->resrec
.dnsservice
, service
);
10520 cr
->resrec
.rDNSServer
= dnsserver
;
10522 cr
->resrec
.name
= name
; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10523 cr
->resrec
.rrtype
= rrtype
;
10524 cr
->resrec
.rrclass
= rrclass
;
10525 cr
->resrec
.rroriginalttl
= ttl_seconds
;
10526 cr
->resrec
.rdlength
= 0;
10527 cr
->resrec
.rdestimate
= 0;
10528 cr
->resrec
.namehash
= namehash
;
10529 cr
->resrec
.rdatahash
= 0;
10530 cr
->resrec
.rdata
= (RData
*)&cr
->smallrdatastorage
;
10531 cr
->resrec
.rdata
->MaxRDLength
= 0;
10533 cr
->NextInKAList
= mDNSNULL
;
10534 cr
->TimeRcvd
= m
->timenow
;
10535 cr
->DelayDelivery
= 0;
10536 cr
->NextRequiredQuery
= m
->timenow
;
10537 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
10538 cr
->LastCachedAnswerTime
= 0;
10540 cr
->CRActiveQuestion
= mDNSNULL
;
10541 cr
->UnansweredQueries
= 0;
10542 cr
->LastUnansweredTime
= 0;
10543 cr
->NextInCFList
= mDNSNULL
;
10544 cr
->soa
= mDNSNULL
;
10545 // Initialize to the basic one and the caller can set it to more
10546 // specific based on the response if any
10547 cr
->responseFlags
= ResponseFlags
;
10550 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10551 mDNSexport
void mDNSCoreReceiveForQuerier(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
10552 mdns_querier_t querier
, mdns_dns_service_t dnsservice
)
10554 SwapDNSHeaderBytes(msg
);
10556 mDNSCoreReceiveResponse(m
, msg
, end
, mDNSNULL
, zeroIPPort
, mDNSNULL
, zeroIPPort
, querier
, dnsservice
, mDNSNULL
);
10561 mDNSexport
void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
10562 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
, const mDNSAddr
*dstaddr
, const mDNSIPPort dstport
,
10563 const mDNSInterfaceID InterfaceID
)
10565 mDNSInterfaceID ifid
= InterfaceID
;
10566 const mDNSu8
*const pkt
= (mDNSu8
*)msg
;
10567 const mDNSu8 StdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_StdQuery
;
10568 const mDNSu8 StdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_StdQuery
;
10569 const mDNSu8 UpdQ
= kDNSFlag0_QR_Query
| kDNSFlag0_OP_Update
;
10570 const mDNSu8 UpdR
= kDNSFlag0_QR_Response
| kDNSFlag0_OP_Update
;
10572 mDNSu8
*ptr
= mDNSNULL
;
10573 mDNSBool TLS
= (dstaddr
== (mDNSAddr
*)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10574 if (TLS
) dstaddr
= mDNSNULL
;
10576 #ifndef UNICAST_DISABLED
10577 if (mDNSSameAddress(srcaddr
, &m
->Router
))
10579 #ifdef _LEGACY_NAT_TRAVERSAL_
10580 if (mDNSSameIPPort(srcport
, SSDPPort
) || (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)))
10583 LNT_ConfigureRouterInfo(m
, InterfaceID
, (mDNSu8
*)msg
, (mDNSu16
)(end
- pkt
));
10588 if (mDNSSameIPPort(srcport
, NATPMPPort
))
10591 uDNS_ReceiveNATPacket(m
, InterfaceID
, (mDNSu8
*)msg
, (mDNSu16
)(end
- pkt
));
10596 #ifdef _LEGACY_NAT_TRAVERSAL_
10597 else if (m
->SSDPSocket
&& mDNSSameIPPort(dstport
, m
->SSDPSocket
->port
)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr
, mDNSVal16(srcport
)); return; }
10601 if ((unsigned)(end
- pkt
) < sizeof(DNSMessageHeader
))
10603 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), (int)(end
- pkt
));
10606 QR_OP
= (mDNSu8
)(msg
->h
.flags
.b
[0] & kDNSFlag0_QROP_Mask
);
10607 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10608 ptr
= (mDNSu8
*)&msg
->h
.numQuestions
;
10609 msg
->h
.numQuestions
= (mDNSu16
)((mDNSu16
)ptr
[0] << 8 | ptr
[1]);
10610 msg
->h
.numAnswers
= (mDNSu16
)((mDNSu16
)ptr
[2] << 8 | ptr
[3]);
10611 msg
->h
.numAuthorities
= (mDNSu16
)((mDNSu16
)ptr
[4] << 8 | ptr
[5]);
10612 msg
->h
.numAdditionals
= (mDNSu16
)((mDNSu16
)ptr
[6] << 8 | ptr
[7]);
10614 if (!m
) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10616 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10617 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10618 if (!mDNSAddressIsValid(srcaddr
)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr
); return; }
10622 if (mDNSOpaque16IsZero(msg
->h
.id
))
10625 #if APPLE_OSX_mDNSResponder
10626 // Track the number of multicast packets received from a source outside our subnet.
10627 // Check the destination address to avoid accounting for spurious packets that
10628 // comes in with message id zero.
10629 if (!mDNS_AddressIsLocalSubnet(m
, InterfaceID
, srcaddr
) && dstaddr
&&
10630 mDNSAddressIsAllDNSLinkGroup(dstaddr
))
10634 #endif // #if APPLE_OSX_mDNSResponder
10637 #ifndef UNICAST_DISABLED
10638 if (!dstaddr
|| (!mDNSAddressIsAllDNSLinkGroup(dstaddr
) && (QR_OP
== StdR
|| QR_OP
== UpdR
)))
10639 if (!mDNSOpaque16IsZero(msg
->h
.id
)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10641 ifid
= mDNSInterface_Any
;
10642 if (mDNS_PacketLoggingEnabled
)
10643 DumpPacket(mStatus_NoError
, mDNSfalse
, TLS
? "TLS" : !dstaddr
? "TCP" : "UDP", srcaddr
, srcport
, dstaddr
, dstport
, msg
, end
, InterfaceID
);
10644 uDNS_ReceiveMsg(m
, msg
, end
, srcaddr
, srcport
);
10645 // Note: mDNSCore also needs to get access to received unicast responses
10648 if (QR_OP
== StdQ
) mDNSCoreReceiveQuery (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10649 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10650 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, mDNSNULL
, mDNSNULL
, ifid
);
10652 else if (QR_OP
== StdR
) mDNSCoreReceiveResponse(m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, ifid
);
10654 else if (QR_OP
== UpdQ
) mDNSCoreReceiveUpdate (m
, msg
, end
, srcaddr
, srcport
, dstaddr
, dstport
, InterfaceID
);
10655 else if (QR_OP
== UpdR
) mDNSCoreReceiveUpdateR (m
, msg
, end
, srcaddr
, InterfaceID
);
10658 if (mDNS_LoggingEnabled
)
10660 static int msgCount
= 0;
10661 if (msgCount
< 1000) {
10664 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10665 msg
->h
.flags
.b
[0], msg
->h
.flags
.b
[1], srcaddr
, mDNSVal16(srcport
), dstaddr
, mDNSVal16(dstport
), (int)(end
- pkt
), InterfaceID
);
10666 while (i
< (int)(end
- pkt
))
10669 char *p
= buffer
+ mDNS_snprintf(buffer
, sizeof(buffer
), "%04X", i
);
10670 do if (i
< (int)(end
- pkt
)) p
+= mDNS_snprintf(p
, sizeof(buffer
), " %02X", pkt
[i
]);while (++i
& 15);
10671 LogInfo("%s", buffer
);
10676 // Packet reception often causes a change to the task list:
10677 // 1. Inbound queries can cause us to need to send responses
10678 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10679 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10680 // 4. Response packets that answer questions may cause our client to issue new questions
10684 // ***************************************************************************
10685 #if COMPILER_LIKES_PRAGMA_MARK
10687 #pragma mark - Searcher Functions
10690 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10691 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10692 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10693 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10694 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10696 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10697 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10698 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10699 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10700 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10701 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10702 // breaks this design principle.
10705 // If IsLLQ(Q) is true, it means the question is both:
10706 // (a) long-lived and
10707 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10708 // for multicast questions, we don't want to treat LongLived as anything special
10709 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10710 #define AWDLIsIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10711 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10713 mDNSlocal DNSQuestion
*FindDuplicateQuestion(const mDNS
*const m
, const DNSQuestion
*const question
)
10716 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10717 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10718 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10719 // further in the list.
10720 for (q
= m
->Questions
; q
&& (q
!= question
); q
= q
->next
)
10722 if (!SameQuestionKind(q
, question
)) continue;
10723 if (q
->qnamehash
!= question
->qnamehash
) continue;
10724 if (q
->InterfaceID
!= question
->InterfaceID
) continue;
10725 if (q
->qtype
!= question
->qtype
) continue;
10726 if (q
->qclass
!= question
->qclass
) continue;
10727 if (IsLLQ(q
) != IsLLQ(question
)) continue;
10728 if (q
->AuthInfo
&& !question
->AuthInfo
) continue;
10729 if (!q
->Suppressed
!= !question
->Suppressed
) continue;
10730 if (q
->BrowseThreshold
!= question
->BrowseThreshold
) continue;
10731 if (AWDLIsIncluded(q
) != AWDLIsIncluded(question
)) continue;
10732 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10733 if (q
->dnsservice
!= question
->dnsservice
) continue;
10735 if (!SameDomainName(&q
->qname
, &question
->qname
)) continue;
10741 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10742 mDNSlocal
void UpdateQuestionDuplicates(mDNS
*const m
, DNSQuestion
*const question
)
10745 DNSQuestion
*first
= mDNSNULL
;
10747 // This is referring to some other question as duplicate. No other question can refer to this
10748 // question as a duplicate.
10749 if (question
->DuplicateOf
)
10751 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
10752 "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME
" (" PUB_S
") duplicate of %p " PRI_DM_NAME
" (" PUB_S
")",
10753 question
->request_id
, mDNSVal16(question
->TargetQID
), mDNSVal16(question
->DuplicateOf
->TargetQID
),
10754 question
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
), question
->DuplicateOf
,
10755 DM_NAME_PARAM(&question
->DuplicateOf
->qname
), DNSTypeName(question
->DuplicateOf
->qtype
));
10759 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
10760 if (q
->DuplicateOf
== question
) // To see if any questions were referencing this as their duplicate
10762 q
->DuplicateOf
= first
;
10766 // If q used to be a duplicate, but now is not,
10767 // then inherit the state from the question that's going away
10768 q
->LastQTime
= question
->LastQTime
;
10769 q
->ThisQInterval
= question
->ThisQInterval
;
10770 q
->ExpectUnicastResp
= question
->ExpectUnicastResp
;
10771 q
->LastAnswerPktNum
= question
->LastAnswerPktNum
;
10772 q
->RecentAnswerPkts
= question
->RecentAnswerPkts
;
10773 q
->RequestUnicast
= question
->RequestUnicast
;
10774 q
->LastQTxTime
= question
->LastQTxTime
;
10775 q
->CNAMEReferrals
= question
->CNAMEReferrals
;
10776 q
->nta
= question
->nta
;
10777 q
->servAddr
= question
->servAddr
;
10778 q
->servPort
= question
->servPort
;
10779 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10780 mdns_replace(&q
->dnsservice
, question
->dnsservice
);
10781 mdns_forget(&question
->dnsservice
);
10782 mdns_querier_forget(&q
->querier
);
10783 mdns_replace(&q
->querier
, question
->querier
);
10784 mdns_forget(&question
->querier
);
10786 q
->qDNSServer
= question
->qDNSServer
;
10787 q
->validDNSServers
= question
->validDNSServers
;
10788 q
->unansweredQueries
= question
->unansweredQueries
;
10789 q
->noServerResponse
= question
->noServerResponse
;
10790 q
->triedAllServersOnce
= question
->triedAllServersOnce
;
10793 q
->TargetQID
= question
->TargetQID
;
10794 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10795 q
->LocalSocket
= question
->LocalSocket
;
10796 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10799 q
->state
= question
->state
;
10800 // q->tcp = question->tcp;
10801 q
->ReqLease
= question
->ReqLease
;
10802 q
->expire
= question
->expire
;
10803 q
->ntries
= question
->ntries
;
10804 q
->id
= question
->id
;
10806 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10807 question
->LocalSocket
= mDNSNULL
;
10809 question
->nta
= mDNSNULL
; // If we've got a GetZoneData in progress, transfer it to the newly active question
10810 // question->tcp = mDNSNULL;
10812 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10813 if (q
->LocalSocket
)
10814 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10818 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10819 q
->nta
->ZoneDataContext
= q
;
10822 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10823 if (question
->tcp
) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10825 if (question
->state
== LLQ_Established
)
10827 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
10828 question
->state
= 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10831 SetNextQueryTime(m
,q
);
10836 mDNSexport McastResolver
*mDNS_AddMcastResolver(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, mDNSu32 timeout
)
10838 McastResolver
**p
= &m
->McastResolvers
;
10839 McastResolver
*tmp
= mDNSNULL
;
10841 if (!d
) d
= (const domainname
*)"";
10843 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
10844 "mDNS_AddMcastResolver: Adding " PUB_DM_NAME
", InterfaceID %p, timeout %u", DM_NAME_PARAM(d
), interface
, timeout
);
10848 while (*p
) // Check if we already have this {interface, domain} tuple registered
10850 if ((*p
)->interface
== interface
&& SameDomainName(&(*p
)->domain
, d
))
10852 if (!((*p
)->flags
& McastResolver_FlagDelete
)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d
->c
, interface
);
10853 (*p
)->flags
&= ~McastResolver_FlagDelete
;
10856 tmp
->next
= mDNSNULL
;
10862 if (tmp
) *p
= tmp
; // move to end of list, to ensure ordering from platform layer
10865 // allocate, add to list
10866 *p
= (McastResolver
*) mDNSPlatformMemAllocateClear(sizeof(**p
));
10867 if (!*p
) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10870 (*p
)->interface
= interface
;
10871 (*p
)->flags
= McastResolver_FlagNew
;
10872 (*p
)->timeout
= timeout
;
10873 AssignDomainName(&(*p
)->domain
, d
);
10874 (*p
)->next
= mDNSNULL
;
10880 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10881 mDNSinline mDNSs32
PenaltyTimeForServer(mDNS
*m
, DNSServer
*server
)
10884 if (server
->penaltyTime
!= 0)
10886 ptime
= server
->penaltyTime
- m
->timenow
;
10889 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10890 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10892 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10893 ptime
, server
->penaltyTime
, m
->timenow
);
10894 server
->penaltyTime
= 0;
10902 //Checks to see whether the newname is a better match for the name, given the best one we have
10903 //seen so far (given in bestcount).
10904 //Returns -1 if the newname is not a better match
10905 //Returns 0 if the newname is the same as the old match
10906 //Returns 1 if the newname is a better match
10907 mDNSlocal
int BetterMatchForName(const domainname
*name
, int namecount
, const domainname
*newname
, int newcount
,
10910 // If the name contains fewer labels than the new server's domain or the new name
10911 // contains fewer labels than the current best, then it can't possibly be a better match
10912 if (namecount
< newcount
|| newcount
< bestcount
) return -1;
10914 // If there is no match, return -1 and the caller will skip this newname for
10917 // If we find a match and the number of labels is the same as bestcount, then
10918 // we return 0 so that the caller can do additional logic to pick one of
10919 // the best based on some other factors e.g., penaltyTime
10921 // If we find a match and the number of labels is more than bestcount, then we
10922 // return 1 so that the caller can pick this over the old one.
10924 // Note: newcount can either be equal or greater than bestcount beause of the
10927 if (SameDomainName(SkipLeadingLabels(name
, namecount
- newcount
), newname
))
10928 return bestcount
== newcount
? 0 : 1;
10933 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10934 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10935 // names. In that case, we give a default timeout of 5 seconds
10936 #define DEFAULT_MCAST_TIMEOUT 5
10937 mDNSlocal mDNSu32
GetTimeoutForMcastQuestion(mDNS
*m
, DNSQuestion
*question
)
10939 McastResolver
*curmatch
= mDNSNULL
;
10940 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
10941 McastResolver
*curr
;
10942 int bettermatch
, currcount
;
10943 for (curr
= m
->McastResolvers
; curr
; curr
= curr
->next
)
10945 currcount
= CountLabels(&curr
->domain
);
10946 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
10947 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10948 // the timeout value from the first one
10949 if (bettermatch
== 1)
10952 bestmatchlen
= currcount
;
10955 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question
->qname
.c
, curmatch
,
10956 curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
10957 return ( curmatch
? curmatch
->timeout
: DEFAULT_MCAST_TIMEOUT
);
10960 // Returns true if it is a Domain Enumeration Query
10961 mDNSexport mDNSBool
DomainEnumQuery(const domainname
*qname
)
10963 const mDNSu8
*mDNS_DEQLabels
[] = { (const mDNSu8
*)"\001b", (const mDNSu8
*)"\002db", (const mDNSu8
*)"\002lb",
10964 (const mDNSu8
*)"\001r", (const mDNSu8
*)"\002dr", (const mDNSu8
*)mDNSNULL
, };
10965 const domainname
*d
= qname
;
10966 const mDNSu8
*label
;
10969 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10970 if (CountLabels(qname
) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname
->c
); return mDNSfalse
; }
10972 label
= (const mDNSu8
*)d
;
10973 while (mDNS_DEQLabels
[i
] != (const mDNSu8
*)mDNSNULL
)
10975 if (SameDomainLabel(mDNS_DEQLabels
[i
], label
)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
); break;}
10978 if (mDNS_DEQLabels
[i
] == (const mDNSu8
*)mDNSNULL
)
10980 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname
->c
);
10983 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname
->c
);
10985 // CountLabels already verified the number of labels
10986 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Second Label
10987 label
= (const mDNSu8
*)d
;
10988 if (!SameDomainLabel(label
, (const mDNSu8
*)"\007_dns-sd"))
10990 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname
->c
);
10993 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname
->c
);
10995 d
= (const domainname
*)(d
->c
+ 1 + d
->c
[0]); // Third Label
10996 label
= (const mDNSu8
*)d
;
10997 if (!SameDomainLabel(label
, (const mDNSu8
*)"\004_udp"))
10999 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname
->c
);
11002 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname
->c
);
11004 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname
->c
);
11009 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11010 // Note: InterfaceID is the InterfaceID of the question
11011 mDNSlocal mDNSBool
DNSServerMatch(DNSServer
*d
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11013 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11014 // with scopeType set to kScopeNone)
11016 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11017 // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11019 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11020 // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11022 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11023 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11025 // If the first condition fails, following are the possible cases (the notes below are using
11026 // InterfaceID for discussion and the same holds good for ServiceID):
11028 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11029 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11031 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11032 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11033 // would fail in this case.
11035 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11036 // should match (Refer to (2) above).
11038 if (((d
->scopeType
== kScopeNone
) && (!InterfaceID
&& ServiceID
== -1)) ||
11039 ((d
->scopeType
== kScopeInterfaceID
) && d
->interface
== InterfaceID
) ||
11040 ((d
->scopeType
== kScopeServiceID
) && d
->serviceID
== ServiceID
))
11047 // Sets all the Valid DNS servers for a question
11048 mDNSexport mDNSu32
SetValidDNSServers(mDNS
*m
, DNSQuestion
*question
)
11050 int bestmatchlen
= -1, namecount
= CountLabels(&question
->qname
);
11052 int bettermatch
, currcount
;
11054 mDNSu32 timeout
= 0;
11057 question
->validDNSServers
= zeroOpaque128
;
11058 DEQuery
= DomainEnumQuery(&question
->qname
);
11059 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11061 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11062 // skip servers that will soon be deleted
11063 if (curr
->flags
& DNSServerFlag_Delete
)
11065 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11069 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11070 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11071 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11072 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11073 // match the scoped entries by mistake.
11075 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11077 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11078 if (((curr
->scopeType
== kScopeInterfaceID
) && (curr
->interface
== mDNSInterface_Any
)) ||
11079 ((curr
->scopeType
== kScopeServiceID
) && (curr
->serviceID
<= 0)))
11081 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11082 (int)curr
->scopeType
, &curr
->addr
, curr
->domain
.c
, curr
->interface
, curr
->serviceID
);
11086 currcount
= CountLabels(&curr
->domain
);
11087 if ((!DEQuery
|| !curr
->isCell
) && DNSServerMatch(curr
, question
->InterfaceID
, question
->ServiceID
))
11089 bettermatch
= BetterMatchForName(&question
->qname
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11091 // If we found a better match (bettermatch == 1) then clear all the bits
11092 // corresponding to the old DNSServers that we have may set before and start fresh.
11093 // If we find an equal match, then include that DNSServer also by setting the corresponding
11095 if ((bettermatch
== 1) || (bettermatch
== 0))
11097 bestmatchlen
= currcount
;
11100 debugf("SetValidDNSServers: Resetting all the bits");
11101 question
->validDNSServers
= zeroOpaque128
;
11104 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11105 " Timeout %d, interface %p", question
->qname
.c
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
, index
, curr
->timeout
,
11107 timeout
+= curr
->timeout
;
11109 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question
->qname
.c
, &curr
->addr
, curr
->isCell
);
11110 bit_set_opaque128(question
->validDNSServers
, index
);
11115 question
->noServerResponse
= 0;
11117 debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11118 question
->validDNSServers
.l
[3], question
->validDNSServers
.l
[2], question
->validDNSServers
.l
[1], question
->validDNSServers
.l
[0], question
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11119 // If there are no matching resolvers, then use the default timeout value.
11120 return (timeout
? timeout
: DEFAULT_UDNS_TIMEOUT
);
11123 // Get the Best server that matches a name. If you find penalized servers, look for the one
11124 // that will come out of the penalty box soon
11125 mDNSlocal DNSServer
*GetBestServer(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
, mDNSOpaque128 validBits
,
11126 int *selected
, mDNSBool nameMatch
)
11128 DNSServer
*curmatch
= mDNSNULL
;
11129 int bestmatchlen
= -1, namecount
= name
? CountLabels(name
) : 0;
11131 mDNSs32 bestPenaltyTime
, currPenaltyTime
;
11132 int bettermatch
, currcount
;
11134 int currindex
= -1;
11136 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits
.l
[1], validBits
.l
[0]);
11137 bestPenaltyTime
= DNSSERVER_PENALTY_TIME
+ 1;
11138 for (curr
= m
->DNSServers
; curr
; curr
= curr
->next
)
11140 // skip servers that will soon be deleted
11141 if (curr
->flags
& DNSServerFlag_Delete
)
11143 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index
, &curr
->addr
, curr
->domain
.c
, curr
->scopeType
);
11147 // Check if this is a valid DNSServer
11148 if (!bit_get_opaque64(validBits
, index
))
11150 debugf("GetBestServer: continuing for index %d", index
);
11155 currcount
= CountLabels(&curr
->domain
);
11156 currPenaltyTime
= PenaltyTimeForServer(m
, curr
);
11158 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11159 &curr
->addr
, curr
->domain
.c
, curr
->penaltyTime
, currPenaltyTime
);
11161 // If there are multiple best servers for a given question, we will pick the first one
11162 // if none of them are penalized. If some of them are penalized in that list, we pick
11163 // the least penalized one. BetterMatchForName walks through all best matches and
11164 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11165 // in the list when there are no penalized servers and least one among them
11166 // when there are some penalized servers.
11168 if (DNSServerMatch(curr
, InterfaceID
, ServiceID
))
11171 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11172 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11173 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11174 // part and still do some redundant steps e.g., InterfaceID match
11177 bettermatch
= BetterMatchForName(name
, namecount
, &curr
->domain
, currcount
, bestmatchlen
);
11181 // If we found a better match (bettermatch == 1) then we don't need to
11182 // compare penalty times. But if we found an equal match, then we compare
11183 // the penalty times to pick a better match
11185 if ((bettermatch
== 1) || ((bettermatch
== 0) && currPenaltyTime
< bestPenaltyTime
))
11189 bestmatchlen
= currcount
;
11190 bestPenaltyTime
= currPenaltyTime
;
11195 if (selected
) *selected
= currindex
;
11199 // Look up a DNS Server, matching by name and InterfaceID
11200 mDNSlocal DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, mDNSInterfaceID InterfaceID
, mDNSs32 ServiceID
)
11202 DNSServer
*curmatch
= mDNSNULL
;
11203 char *ifname
= mDNSNULL
; // for logging purposes only
11204 mDNSOpaque128 allValid
;
11206 if (InterfaceID
== mDNSInterface_LocalOnly
)
11207 InterfaceID
= mDNSNULL
;
11209 if (InterfaceID
) ifname
= InterfaceNameForID(m
, InterfaceID
);
11211 // By passing in all ones, we make sure that every DNS server is considered
11212 allValid
.l
[0] = allValid
.l
[1] = allValid
.l
[2] = allValid
.l
[3] = 0xFFFFFFFF;
11214 curmatch
= GetBestServer(m
, name
, InterfaceID
, ServiceID
, allValid
, mDNSNULL
, mDNStrue
);
11216 if (curmatch
!= mDNSNULL
)
11217 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch
->addr
,
11218 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0), ifname
? ifname
: "None",
11219 InterfaceID
, name
);
11221 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname
? ifname
: "None", InterfaceID
, name
);
11226 // Look up a DNS Server for a question within its valid DNSServer bits
11227 mDNSexport DNSServer
*GetServerForQuestion(mDNS
*m
, DNSQuestion
*question
)
11229 DNSServer
*curmatch
= mDNSNULL
;
11230 char *ifname
= mDNSNULL
; // for logging purposes only
11231 mDNSInterfaceID InterfaceID
= question
->InterfaceID
;
11232 const domainname
*name
= &question
->qname
;
11235 if (InterfaceID
== mDNSInterface_LocalOnly
)
11236 InterfaceID
= mDNSNULL
;
11239 ifname
= InterfaceNameForID(m
, InterfaceID
);
11241 if (!mDNSOpaque128IsZero(&question
->validDNSServers
))
11243 curmatch
= GetBestServer(m
, name
, InterfaceID
, question
->ServiceID
, question
->validDNSServers
, &currindex
, mDNSfalse
);
11244 if (currindex
!= -1)
11245 bit_clr_opaque128(question
->validDNSServers
, currindex
);
11248 if (curmatch
!= mDNSNULL
)
11250 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11251 "[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
")",
11252 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, curmatch
, &curmatch
->addr
,
11253 mDNSVal16(curmatch
->port
), (curmatch
->penaltyTime
? (curmatch
->penaltyTime
- m
->timenow
) : 0),
11254 ifname
? ifname
: "None", InterfaceID
, question
->ServiceID
, DM_NAME_PARAM(name
), DNSTypeName(question
->qtype
));
11258 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11259 "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S
":%p:%d) for " PRI_DM_NAME
" (" PUB_S
")",
11260 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, ifname
? ifname
: "None", InterfaceID
,
11261 question
->ServiceID
, DM_NAME_PARAM(name
), DNSTypeName(question
->qtype
));
11266 #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11268 // Called in normal client context (lock not held)
11269 mDNSlocal
void LLQNATCallback(mDNS
*m
, NATTraversalInfo
*n
)
11273 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n
->ExternalAddress
, mDNSVal16(n
->ExternalPort
), n
->Result
);
11274 n
->clientContext
= mDNSNULL
; // we received at least one callback since starting this NAT-T
11275 for (q
= m
->Questions
; q
; q
=q
->next
)
11276 if (ActiveQuestion(q
) && !mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
)
11277 startLLQHandshake(m
, q
); // If ExternalPort is zero, will do StartLLQPolling instead
11281 // This function takes the DNSServer as a separate argument because sometimes the
11282 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11283 // status before switching to it.
11284 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11285 mDNSexport mDNSBool
ShouldSuppressUnicastQuery(const DNSQuestion
*const q
, const mdns_dns_service_t dnsservice
)
11287 mDNSlocal mDNSBool
ShouldSuppressUnicastQuery(const DNSQuestion
*const q
, const DNSServer
*const server
)
11290 mDNSBool suppress
= mDNSfalse
;
11291 const char *reason
= mDNSNULL
;
11293 if (q
->BlockedByPolicy
)
11295 suppress
= mDNStrue
;
11296 reason
= " (blocked by policy)";
11298 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11299 else if (!dnsservice
)
11301 if (!q
->IsUnicastDotLocal
)
11303 suppress
= mDNStrue
;
11304 reason
= " (no DNS service)";
11310 if (!q
->IsUnicastDotLocal
)
11312 suppress
= mDNStrue
;
11313 reason
= " (no DNS server)";
11317 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11318 else if ((q
->flags
& kDNSServiceFlagsDenyCellular
) && mdns_dns_service_interface_is_cellular(dnsservice
))
11320 else if ((q
->flags
& kDNSServiceFlagsDenyCellular
) && server
->isCell
)
11323 suppress
= mDNStrue
;
11324 reason
= " (interface is cellular)";
11326 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11327 else if ((q
->flags
& kDNSServiceFlagsDenyExpensive
) && mdns_dns_service_interface_is_expensive(dnsservice
))
11329 else if ((q
->flags
& kDNSServiceFlagsDenyExpensive
) && server
->isExpensive
)
11332 suppress
= mDNStrue
;
11333 reason
= " (interface is expensive)";
11335 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11336 else if ((q
->flags
& kDNSServiceFlagsDenyConstrained
) && mdns_dns_service_interface_is_constrained(dnsservice
))
11338 else if ((q
->flags
& kDNSServiceFlagsDenyConstrained
) && server
->isConstrained
)
11341 suppress
= mDNStrue
;
11342 reason
= " (interface is constrained)";
11344 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11345 else if (q
->SuppressUnusable
&& !DNS64IsQueryingARecord(q
->dns64
.state
))
11347 else if (q
->SuppressUnusable
)
11350 if (q
->qtype
== kDNSType_A
)
11352 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11353 if (!mdns_dns_service_a_queries_advised(dnsservice
))
11355 if (!server
->usableA
)
11358 suppress
= mDNStrue
;
11359 reason
= " (A records are unusable)";
11361 // If the server's configuration allows A record queries, suppress this query if
11362 // 1. the interface associated with the server is CLAT46; and
11363 // 2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11364 // See <rdar://problem/42672030> for more info.
11365 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11366 else if ((q
->flags
& kDNSServiceFlagsPathEvaluationDone
) && mdns_dns_service_interface_is_clat46(dnsservice
))
11368 else if ((q
->flags
& kDNSServiceFlagsPathEvaluationDone
) && server
->isCLAT46
)
11371 suppress
= mDNStrue
;
11372 reason
= " (CLAT46 A records are unusable)";
11375 else if (q
->qtype
== kDNSType_AAAA
)
11377 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11378 if (!mdns_dns_service_aaaa_queries_advised(dnsservice
))
11380 if (!server
->usableAAAA
)
11383 suppress
= mDNStrue
;
11384 reason
= " (AAAA records are unusable)";
11390 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11391 "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME
" " PUB_S PUB_S
,
11392 mDNSVal16(q
->TargetQID
), DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), reason
? reason
: "");
11397 mDNSlocal mDNSBool
ShouldSuppressQuery(DNSQuestion
*q
)
11399 // Multicast queries are never suppressed.
11400 if (mDNSOpaque16IsZero(q
->TargetQID
))
11404 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11405 return (ShouldSuppressUnicastQuery(q
, q
->dnsservice
));
11407 return (ShouldSuppressUnicastQuery(q
, q
->qDNSServer
));
11411 mDNSlocal
void CacheRecordRmvEventsForCurrentQuestion(mDNS
*const m
, DNSQuestion
*q
)
11416 cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
11417 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
11419 // Don't deliver RMV events for negative records
11420 if (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
)
11422 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11423 "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S
" Suppressing RMV events for question %p " PRI_DM_NAME
" (" PUB_S
"), CRActiveQuestion %p, CurrentAnswers %d",
11424 q
->request_id
, mDNSVal16(q
->TargetQID
), CRDisplayString(m
, cr
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), cr
->CRActiveQuestion
, q
->CurrentAnswers
);
11428 if (SameNameCacheRecordAnswersQuestion(cr
, q
))
11430 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11431 q
->qname
.c
, CRDisplayString(m
, cr
), q
->LOAddressAnswers
);
11433 q
->CurrentAnswers
--;
11434 if (cr
->resrec
.rdlength
> SmallRecordLimit
) q
->LargeAnswers
--;
11435 if (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) q
->UniqueAnswers
--;
11436 AnswerCurrentQuestionWithResourceRecord(m
, cr
, QC_rmv
);
11437 if (m
->CurrentQuestion
!= q
) break; // If callback deleted q, then we're finished here
11442 mDNSlocal mDNSBool
IsQuestionNew(mDNS
*const m
, DNSQuestion
*question
)
11445 for (q
= m
->NewQuestions
; q
; q
= q
->next
)
11446 if (q
== question
) return mDNStrue
;
11450 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11451 mDNSexport mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11453 mDNSlocal mDNSBool
LocalRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11459 if (m
->CurrentQuestion
)
11460 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11461 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11463 if (IsQuestionNew(m
, q
))
11465 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11468 m
->CurrentQuestion
= q
;
11469 ag
= AuthGroupForName(&m
->rrauth
, q
->qnamehash
, &q
->qname
);
11472 for (rr
= ag
->members
; rr
; rr
=rr
->next
)
11473 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11474 if (UniqueLocalOnlyRecord(rr
) && LocalOnlyRecordAnswersQuestion(rr
, q
))
11476 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11477 ARDisplayString(m
, rr
));
11478 if (q
->CurrentAnswers
<= 0 || q
->LOAddressAnswers
<= 0)
11480 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11481 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q
, q
->qname
.c
, DNSTypeName(q
->qtype
),
11482 q
->CurrentAnswers
, q
->LOAddressAnswers
);
11485 AnswerLocalQuestionWithLocalAuthRecord(m
, rr
, QC_rmv
); // MUST NOT dereference q again
11486 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11489 m
->CurrentQuestion
= mDNSNULL
;
11493 // Returns false if the question got deleted while delivering the RMV events
11494 // The caller should handle the case
11495 mDNSexport mDNSBool
CacheRecordRmvEventsForQuestion(mDNS
*const m
, DNSQuestion
*q
)
11497 if (m
->CurrentQuestion
)
11498 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11499 m
->CurrentQuestion
->qname
.c
, DNSTypeName(m
->CurrentQuestion
->qtype
));
11501 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11502 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11503 if (!IsQuestionNew(m
, q
) && !q
->LOAddressAnswers
)
11505 m
->CurrentQuestion
= q
;
11506 CacheRecordRmvEventsForCurrentQuestion(m
, q
);
11507 if (m
->CurrentQuestion
!= q
) { m
->CurrentQuestion
= mDNSNULL
; return mDNSfalse
; }
11508 m
->CurrentQuestion
= mDNSNULL
;
11510 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q
, q
->qname
.c
, DNSTypeName(q
->qtype
)); }
11514 mDNSlocal
void SuppressStatusChanged(mDNS
*const m
, DNSQuestion
*q
, DNSQuestion
**restart
)
11516 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11517 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11518 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11521 q
->Suppressed
= mDNSfalse
;
11522 if (!CacheRecordRmvEventsForQuestion(m
, q
))
11524 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11525 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11526 q
->request_id
, mDNSVal16(q
->TargetQID
));
11529 q
->Suppressed
= mDNStrue
;
11532 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11533 // and Suppressed status does not mean anything for these questions. As we are going to stop the
11534 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11535 // the restart will not be a duplicate ADD
11536 if (!LocalRecordRmvEventsForQuestion(m
, q
))
11538 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11539 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11540 q
->request_id
, mDNSVal16(q
->TargetQID
));
11544 // There are two cases here.
11546 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11547 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11548 // because when we get the response, if we had entries in the cache already, it will not answer
11549 // this question if the cache entry did not change. Hence, we need to restart
11550 // the query so that it can be answered from the cache.
11552 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11553 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11554 // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11555 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11556 // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11557 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11558 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11559 // This affects both efficiency and also the current design where there is only one active question
11560 // pointed to from a cache entry.
11562 // We restart queries in a two step process by first calling stop and build a temporary list which we
11563 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11564 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11565 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11566 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11567 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11569 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11571 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11572 "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME
" (" PUB_S
")",
11573 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
11574 mDNS_StopQuery_internal(m
, q
);
11575 q
->next
= *restart
;
11579 // The caller should hold the lock
11580 mDNSexport
void CheckSuppressUnusableQuestions(mDNS
*const m
)
11583 DNSQuestion
*restart
= mDNSNULL
;
11585 // We look through all questions including new questions. During network change events,
11586 // we potentially restart questions here in this function that ends up as new questions,
11587 // which may be suppressed at this instance. Before it is handled we get another network
11588 // event that changes the status e.g., address becomes available. If we did not process
11589 // new questions, we would never change its Suppressed status.
11591 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11592 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11593 // *any* other question which could be the next one that we may process here. RestartQuestion
11594 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11595 // if the "next" question is stopped while the CurrentQuestion is stopped
11596 if (m
->RestartQuestion
)
11597 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11598 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11599 m
->RestartQuestion
= m
->Questions
;
11600 while (m
->RestartQuestion
)
11602 q
= m
->RestartQuestion
;
11603 m
->RestartQuestion
= q
->next
;
11604 if (q
->SuppressUnusable
)
11606 const mDNSBool old
= q
->Suppressed
;
11607 q
->Suppressed
= ShouldSuppressQuery(q
);
11608 if (q
->Suppressed
!= old
)
11610 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11611 // followed by a negative cache response. Temporarily turn off suppression so that
11612 // AnswerCurrentQuestionWithResourceRecord can answer the question
11613 SuppressStatusChanged(m
, q
, &restart
);
11620 restart
= restart
->next
;
11621 q
->next
= mDNSNULL
;
11622 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
11623 mDNS_StartQuery_internal(m
, q
);
11627 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11628 mDNSlocal
void RestartUnicastQuestions(mDNS
*const m
)
11631 DNSQuestion
*restartList
= mDNSNULL
;
11633 if (m
->RestartQuestion
)
11634 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11635 m
->RestartQuestion
->qname
.c
, DNSTypeName(m
->RestartQuestion
->qtype
));
11636 m
->RestartQuestion
= m
->Questions
;
11637 while (m
->RestartQuestion
)
11639 q
= m
->RestartQuestion
;
11640 m
->RestartQuestion
= q
->next
;
11643 if (mDNSOpaque16IsZero(q
->TargetQID
))
11644 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
11646 q
->Restart
= mDNSfalse
;
11647 SuppressStatusChanged(m
, q
, &restartList
);
11650 while ((q
= restartList
) != mDNSNULL
)
11652 restartList
= q
->next
;
11653 q
->next
= mDNSNULL
;
11654 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11655 "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME
" (" PUB_S
")",
11656 q
->request_id
, mDNSVal16(q
->TargetQID
), q
, DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
));
11657 mDNS_StartQuery_internal(m
, q
);
11662 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11663 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11664 mDNSlocal mStatus
ValidateParameters(mDNS
*const m
, DNSQuestion
*const question
)
11666 if (!ValidateDomainName(&question
->qname
))
11668 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
11669 return(mStatus_Invalid
);
11672 // If this question is referencing a specific interface, verify it exists
11673 if (question
->InterfaceID
&& !LocalOnlyOrP2PInterface(question
->InterfaceID
))
11675 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, question
->InterfaceID
);
11677 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11678 IIDPrintable(question
->InterfaceID
), question
->qname
.c
, DNSTypeName(question
->qtype
));
11681 return(mStatus_NoError
);
11684 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11685 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11686 mDNSlocal
void InitDNSConfig(mDNS
*const m
, DNSQuestion
*const question
)
11688 // First reset all DNS Configuration
11689 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11690 mdns_forget(&question
->dnsservice
);
11692 question
->qDNSServer
= mDNSNULL
;
11693 question
->validDNSServers
= zeroOpaque128
;
11694 question
->triedAllServersOnce
= mDNSfalse
;
11695 question
->noServerResponse
= mDNSfalse
;
11697 question
->StopTime
= (question
->TimeoutQuestion
) ? question
->StopTime
: 0;
11698 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11699 mDNSPlatformMemZero(&question
->metrics
, sizeof(question
->metrics
));
11700 question
->metrics
.expiredAnswerState
= (question
->allowExpired
!= AllowExpired_None
) ? ExpiredAnswer_Allowed
: ExpiredAnswer_None
;
11703 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11704 if (LocalOnlyOrP2PInterface(question
->InterfaceID
) && !question
->TimeoutQuestion
)
11706 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11707 if (!mDNSOpaque16IsZero(question
->TargetQID
))
11709 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11710 mDNSu32 timeout
= 30;
11712 mDNSu32 timeout
= SetValidDNSServers(m
, question
);
11714 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11715 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11716 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11717 // it gets a full timeout value even if the original question times out earlier.
11718 if (question
->TimeoutQuestion
&& !question
->StopTime
)
11720 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11721 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11722 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME
" (" PUB_S
")",
11723 mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
11726 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11727 Querier_SetDNSServiceForQuestion(question
);
11729 question
->qDNSServer
= GetServerForQuestion(m
, question
);
11730 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
11731 "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME
" " PUB_S
" Timeout %d, DNS Server " PRI_IP_ADDR
":%d",
11732 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(&question
->qname
),
11733 DNSTypeName(question
->qtype
), timeout
, question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11734 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11737 else if (question
->TimeoutQuestion
&& !question
->StopTime
)
11739 // If the question is to be timed out and its a multicast, local-only or P2P case,
11740 // then set it's stop time.
11741 mDNSu32 timeout
= LocalOnlyOrP2PInterface(question
->InterfaceID
) ?
11742 DEFAULT_LO_OR_P2P_TIMEOUT
: GetTimeoutForMcastQuestion(m
, question
);
11743 question
->StopTime
= NonZeroTime(m
->timenow
+ timeout
* mDNSPlatformOneSecond
);
11744 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11745 "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME
" (" PUB_S
")",
11746 question
->request_id
, mDNSVal16(question
->TargetQID
), question
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
11748 // Set StopTime here since it is a part of DNS Configuration
11749 if (question
->StopTime
)
11750 SetNextQueryStopTime(m
, question
);
11751 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11752 // will never be transmitted on the wire.
11753 if (!(LocalOnlyOrP2PInterface(question
->InterfaceID
)))
11754 SetNextQueryTime(m
,question
);
11757 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11758 // state fields of the DNS Question. These are independent of the Client layer.
11759 mDNSlocal
void InitCommonState(mDNS
*const m
, DNSQuestion
*const question
)
11763 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11764 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11765 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11766 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11767 // that to go out immediately.
11768 question
->next
= mDNSNULL
;
11769 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11770 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11771 // the question list to check if ThisQInterval is negative which means the question has been
11772 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11773 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11774 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11775 // turned ON which can allocate memory e.g., base64 encoding.
11776 question
->ThisQInterval
= InitialQuestionInterval
; // MUST be > zero for an active question
11777 question
->qnamehash
= DomainNameHashValue(&question
->qname
);
11778 question
->DelayAnswering
= mDNSOpaque16IsZero(question
->TargetQID
) ? CheckForSoonToExpireRecords(m
, &question
->qname
, question
->qnamehash
) : 0;
11779 question
->LastQTime
= m
->timenow
;
11780 question
->ExpectUnicastResp
= 0;
11781 question
->LastAnswerPktNum
= m
->PktNum
;
11782 question
->RecentAnswerPkts
= 0;
11783 question
->CurrentAnswers
= 0;
11785 #if APPLE_OSX_mDNSResponder
11787 // Initial browse threshold used by Finder.
11788 #define mDNSFinderBrowseThreshold 20
11790 // Set the threshold at which we move to a passive browse state,
11791 // not actively sending queries.
11792 if (question
->flags
& kDNSServiceFlagsThresholdOne
)
11793 question
->BrowseThreshold
= 1;
11794 else if (question
->flags
& kDNSServiceFlagsThresholdFinder
)
11795 question
->BrowseThreshold
= mDNSFinderBrowseThreshold
;
11797 question
->BrowseThreshold
= 0;
11799 #else // APPLE_OSX_mDNSResponder
11800 question
->BrowseThreshold
= 0;
11801 #endif // APPLE_OSX_mDNSResponder
11802 question
->CachedAnswerNeedsUpdate
= mDNSfalse
;
11804 question
->LargeAnswers
= 0;
11805 question
->UniqueAnswers
= 0;
11806 question
->LOAddressAnswers
= 0;
11807 question
->FlappingInterface1
= mDNSNULL
;
11808 question
->FlappingInterface2
= mDNSNULL
;
11810 // mDNSPlatformGetDNSRoutePolicy() and InitDNSConfig() may set a DNSQuestion's BlockedByPolicy value,
11811 // so they should be called before calling ShouldSuppressQuery(), which checks BlockedByPolicy.
11812 question
->BlockedByPolicy
= mDNSfalse
;
11814 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11815 // since we would already have the question->ServiceID in that case.
11816 if (!(question
->flags
& kDNSServiceFlagsServiceIndex
))
11818 question
->ServiceID
= -1;
11819 #if APPLE_OSX_mDNSResponder
11820 if (!(question
->flags
& kDNSServiceFlagsPathEvaluationDone
) || question
->ForcePathEval
)
11822 if (question
->flags
& kDNSServiceFlagsPathEvaluationDone
)
11824 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11825 "[R%u->Q%u] Forcing another path evaluation", question
->request_id
, mDNSVal16(question
->TargetQID
));
11827 question
->ForcePathEval
= mDNSfalse
;
11828 mDNSPlatformGetDNSRoutePolicy(question
);
11833 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question
->qname
.c
,
11834 DNSTypeName(question
->qtype
), question
->pid
, question
->euid
, question
->ServiceID
);
11836 InitDNSConfig(m
, question
);
11837 question
->AuthInfo
= GetAuthInfoForQuestion(m
, question
);
11838 question
->Suppressed
= ShouldSuppressQuery(question
);
11839 question
->NextInDQList
= mDNSNULL
;
11840 question
->SendQNow
= mDNSNULL
;
11841 question
->SendOnAll
= mDNSfalse
;
11842 question
->RequestUnicast
= kDefaultRequestUnicastCount
;
11844 #if APPLE_OSX_mDNSResponder
11845 // Set the QU bit in the first query for the following options.
11846 if ((question
->flags
& kDNSServiceFlagsUnicastResponse
) || (question
->flags
& kDNSServiceFlagsThresholdFinder
))
11848 question
->RequestUnicast
= SET_QU_IN_FIRST_QUERY
;
11849 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question
->RequestUnicast
, question
->qname
.c
,
11850 DNSTypeName(question
->qtype
));
11852 #endif // APPLE_OSX_mDNSResponder
11854 question
->LastQTxTime
= m
->timenow
;
11855 question
->CNAMEReferrals
= 0;
11857 question
->WakeOnResolveCount
= 0;
11858 if (question
->WakeOnResolve
)
11860 question
->WakeOnResolveCount
= InitialWakeOnResolveCount
;
11863 for (i
=0; i
<DupSuppressInfoSize
; i
++)
11864 question
->DupSuppress
[i
].InterfaceID
= mDNSNULL
;
11866 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11867 question
->Restart
= mDNSfalse
;
11870 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11871 question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
, m
->timenow
,
11872 NextQSendTime(question
) - m
->timenow
,
11873 question
->DelayAnswering
? question
->DelayAnswering
- m
->timenow
: 0,
11874 question
, question
->DuplicateOf
? "duplicate of" : "not duplicate", question
->DuplicateOf
);
11876 if (question
->DelayAnswering
)
11877 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11878 question
->DelayAnswering
- m
->timenow
, question
->qname
.c
, DNSTypeName(question
->qtype
));
11881 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11882 mDNSlocal
void InitWABState(DNSQuestion
*const question
)
11884 // We'll create our question->LocalSocket on demand, if needed.
11885 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11886 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11887 // NAT mapping for receiving inbound add/remove events.
11888 question
->LocalSocket
= mDNSNULL
;
11889 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11890 mdns_querier_forget(&question
->querier
);
11892 question
->unansweredQueries
= 0;
11894 question
->nta
= mDNSNULL
;
11895 question
->servAddr
= zeroAddr
;
11896 question
->servPort
= zeroIPPort
;
11897 question
->tcp
= mDNSNULL
;
11898 question
->NoAnswer
= NoAnswer_Normal
;
11901 mDNSlocal
void InitLLQNATState(mDNS
*const m
)
11903 // If we don't have our NAT mapping active, start it now
11904 if (!m
->LLQNAT
.clientCallback
)
11906 m
->LLQNAT
.Protocol
= NATOp_MapUDP
;
11907 m
->LLQNAT
.IntPort
= m
->UnicastPort4
;
11908 m
->LLQNAT
.RequestedPort
= m
->UnicastPort4
;
11909 m
->LLQNAT
.clientCallback
= LLQNATCallback
;
11910 m
->LLQNAT
.clientContext
= (void*)1; // Means LLQ NAT Traversal just started
11911 mDNS_StartNATOperation_internal(m
, &m
->LLQNAT
);
11915 mDNSlocal
void InitLLQState(DNSQuestion
*const question
)
11917 question
->state
= LLQ_Init
;
11918 question
->ReqLease
= 0;
11919 question
->expire
= 0;
11920 question
->ntries
= 0;
11921 question
->id
= zeroOpaque64
;
11924 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11925 // DNSSEC & DNS Proxy fields of the DNS Question.
11926 mDNSlocal
void InitDNSSECProxyState(mDNS
*const m
, DNSQuestion
*const question
)
11929 question
->responseFlags
= zeroID
;
11932 // Once the question is completely initialized including the duplicate logic, this function
11933 // is called to finalize the unicast question which requires flushing the cache if needed,
11934 // activating the query etc.
11935 mDNSlocal
void FinalizeUnicastQuestion(mDNS
*const m
, DNSQuestion
*question
)
11937 // Ensure DNS related info of duplicate question is same as the orig question
11938 if (question
->DuplicateOf
)
11940 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11941 const DNSQuestion
*const duplicateOf
= question
->DuplicateOf
;
11942 mdns_replace(&question
->dnsservice
, duplicateOf
->dnsservice
);
11943 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11944 "[R%u->DupQ%u->Q%u] Duplicate question " PRI_DM_NAME
" (" PUB_S
")",
11945 question
->request_id
, mDNSVal16(question
->TargetQID
), mDNSVal16(duplicateOf
->TargetQID
),
11946 DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
11948 question
->validDNSServers
= question
->DuplicateOf
->validDNSServers
;
11949 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11950 // then we log a line as it could indicate an issue
11951 if (question
->DuplicateOf
->qDNSServer
== mDNSNULL
)
11953 if (question
->qDNSServer
)
11955 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11956 "[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
")",
11957 question
->request_id
, mDNSVal16(question
->TargetQID
), question
,
11958 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11959 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
), question
->DuplicateOf
,
11960 DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
11963 question
->qDNSServer
= question
->DuplicateOf
->qDNSServer
;
11964 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
11965 "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME
" (" PUB_S
"), DNS Server " PRI_IP_ADDR
":%d",
11966 question
->request_id
, mDNSVal16(question
->TargetQID
), mDNSVal16(question
->DuplicateOf
->TargetQID
),
11967 question
, question
->DuplicateOf
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
),
11968 question
->qDNSServer
? &question
->qDNSServer
->addr
: mDNSNULL
,
11969 mDNSVal16(question
->qDNSServer
? question
->qDNSServer
->port
: zeroIPPort
));
11973 ActivateUnicastQuery(m
, question
, mDNSfalse
);
11975 if (question
->LongLived
)
11977 // Unlike other initializations, InitLLQNATState should be done after
11978 // we determine that it is a unicast question. LongLived is set for
11979 // both multicast and unicast browse questions but we should initialize
11980 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11981 // start the NAT traversal that is not needed.
11982 InitLLQNATState(m
);
11986 mDNSexport mStatus
mDNS_StartQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
11991 // First check for cache space (can't do queries if there is no cache space allocated)
11992 if (m
->rrcache_size
== 0)
11993 return(mStatus_NoCache
);
11995 vStatus
= ValidateParameters(m
, question
);
12000 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12001 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12002 // This applies to the top label (TLD) only
12003 // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12004 if (IsHighASCIILabel(LastLabel(&question
->qname
)))
12006 domainname newname
;
12007 if (PerformNextPunycodeConversion(question
, &newname
))
12008 AssignDomainName(&question
->qname
, &newname
);
12010 #endif // USE_LIBIDN
12012 #ifndef UNICAST_DISABLED
12013 question
->TargetQID
= Question_uDNS(question
) ? mDNS_NewMessageID(m
) : zeroID
;
12015 question
->TargetQID
= zeroID
;
12017 debugf("mDNS_StartQuery_internal: %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12019 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12021 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12022 q
= &m
->LocalOnlyQuestions
;
12023 while (*q
&& *q
!= question
)
12028 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12029 question
->qname
.c
, DNSTypeName(question
->qtype
), question
);
12030 return(mStatus_AlreadyRegistered
);
12034 // Intialize the question. The only ordering constraint we have today is that
12035 // InitDNSSECProxyState should be called after the DNS server is selected (in
12036 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12039 InitCommonState(m
, question
);
12040 InitWABState(question
);
12041 InitLLQState(question
);
12042 InitDNSSECProxyState(m
, question
);
12044 // FindDuplicateQuestion should be called last after all the intialization
12045 // as the duplicate logic could be potentially based on any field in the
12047 question
->DuplicateOf
= FindDuplicateQuestion(m
, question
);
12048 if (question
->DuplicateOf
)
12049 question
->AuthInfo
= question
->DuplicateOf
->AuthInfo
;
12051 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12053 if (!m
->NewLocalOnlyQuestions
)
12054 m
->NewLocalOnlyQuestions
= question
;
12058 if (!m
->NewQuestions
)
12059 m
->NewQuestions
= question
;
12061 // If the question's id is non-zero, then it's Wide Area
12062 // MUST NOT do this Wide Area setup until near the end of
12063 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12064 // NS, etc.) and if we haven't finished setting up our own question and setting
12065 // m->NewQuestions if necessary then we could end up recursively re-entering
12066 // this routine with the question list data structures in an inconsistent state.
12067 if (!mDNSOpaque16IsZero(question
->TargetQID
))
12069 FinalizeUnicastQuestion(m
, question
);
12073 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12074 m
->NumAllInterfaceQuestions
++;
12075 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12076 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME
" (" PUB_S
")",
12077 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
12078 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12080 m
->NextBonjourDisableTime
= 0;
12081 if (m
->BonjourEnabled
== 0)
12083 // Enable Bonjour immediately by scheduling network changed processing where
12084 // we will join the multicast group on each active interface.
12085 m
->BonjourEnabled
= 1;
12086 m
->NetworkChanged
= m
->timenow
;
12090 if (question
->WakeOnResolve
)
12092 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question
->qname
.c
);
12093 mDNS_PurgeBeforeResolve(m
, question
);
12098 return(mStatus_NoError
);
12101 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12102 mDNSexport
void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
)
12104 debugf("CancelGetZoneData %##s (%s)", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
));
12105 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12106 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12108 if (nta
->question
.ThisQInterval
!= -1)
12110 mDNS_StopQuery_internal(m
, &nta
->question
);
12111 if (nta
->question
.ThisQInterval
!= -1)
12112 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta
->question
.qname
.c
, DNSTypeName(nta
->question
.qtype
), nta
->question
.ThisQInterval
);
12114 mDNSPlatformMemFree(nta
);
12117 mDNSexport mStatus
mDNS_StopQuery_internal(mDNS
*const m
, DNSQuestion
*const question
)
12119 CacheGroup
*cg
= CacheGroupForName(m
, question
->qnamehash
, &question
->qname
);
12121 DNSQuestion
**qp
= &m
->Questions
;
12123 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12125 if (LocalOnlyOrP2PInterface(question
->InterfaceID
))
12126 qp
= &m
->LocalOnlyQuestions
;
12127 while (*qp
&& *qp
!= question
) qp
=&(*qp
)->next
;
12128 if (*qp
) *qp
= (*qp
)->next
;
12132 if (question
->ThisQInterval
>= 0) // Only log error message if the query was supposed to be active
12134 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question
->qname
.c
, DNSTypeName(question
->qtype
));
12135 return(mStatus_BadReferenceErr
);
12138 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12139 if (!LocalOnlyOrP2PInterface(question
->InterfaceID
) && mDNSOpaque16IsZero(question
->TargetQID
))
12141 if (m
->NumAllInterfaceRecords
+ m
->NumAllInterfaceQuestions
== 1)
12142 m
->NextBonjourDisableTime
= NonZeroTime(m
->timenow
+ (BONJOUR_DISABLE_DELAY
* mDNSPlatformOneSecond
));
12143 m
->NumAllInterfaceQuestions
--;
12144 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
12145 "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME
" (" PUB_S
")",
12146 m
->NumAllInterfaceRecords
, m
->NumAllInterfaceQuestions
, DM_NAME_PARAM(&question
->qname
), DNSTypeName(question
->qtype
));
12150 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12151 if (Question_uDNS(question
) && !question
->metrics
.answered
&& (question
->metrics
.firstQueryTime
!= 0))
12153 mDNSu32 querySendCount
= question
->metrics
.querySendCount
;
12154 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12155 if (question
->querier
)
12157 querySendCount
+= mdns_querier_get_send_count(question
->querier
);
12160 if (querySendCount
> 0)
12162 const domainname
* queryName
;
12163 mDNSBool isForCell
;
12164 mDNSu32 durationMs
;
12166 queryName
= question
->metrics
.originalQName
? question
->metrics
.originalQName
: &question
->qname
;
12167 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12168 isForCell
= (question
->dnsservice
&& mdns_dns_service_interface_is_cellular(question
->dnsservice
));
12170 isForCell
= (question
->qDNSServer
&& question
->qDNSServer
->isCell
);
12172 durationMs
= ((m
->timenow
- question
->metrics
.firstQueryTime
) * 1000) / mDNSPlatformOneSecond
;
12173 MetricsUpdateDNSQueryStats(queryName
, question
->qtype
, mDNSNULL
, querySendCount
,
12174 question
->metrics
.expiredAnswerState
, question
->metrics
.dnsOverTCPState
, durationMs
, isForCell
);
12178 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12179 UpdateQuestionDuplicates(m
, question
);
12180 // But don't trash ThisQInterval until afterwards.
12181 question
->ThisQInterval
= -1;
12183 // If there are any cache records referencing this as their active question, then see if there is any
12184 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12185 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
12187 if (cr
->CRActiveQuestion
== question
)
12190 DNSQuestion
*replacement
= mDNSNULL
;
12191 // If we find an active question that is answered by this cached record, use it as the cache record's
12192 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12193 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12194 // via CacheRecordRmv() when the cache record expires.
12195 for (q
= m
->Questions
; q
&& (q
!= m
->NewQuestions
); q
= q
->next
)
12197 if (!q
->DuplicateOf
&& !q
->Suppressed
&& CacheRecordAnswersQuestion(cr
, q
))
12199 if (q
->ThisQInterval
> 0)
12204 else if (!replacement
)
12211 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12212 "CurrentAnswers %d, Suppressed %d", replacement
, CRDisplayString(m
,cr
), question
->CurrentAnswers
, replacement
->CurrentAnswers
, replacement
->Suppressed
);
12213 cr
->CRActiveQuestion
= replacement
; // Question used to be active; new value may or may not be null
12214 if (!replacement
) m
->rrcache_active
--; // If no longer active, decrement rrcache_active count
12218 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12219 // bump its pointer forward one question.
12220 if (m
->CurrentQuestion
== question
)
12222 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12223 question
->qname
.c
, DNSTypeName(question
->qtype
));
12224 m
->CurrentQuestion
= question
->next
;
12227 if (m
->NewQuestions
== question
)
12229 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12230 question
->qname
.c
, DNSTypeName(question
->qtype
));
12231 m
->NewQuestions
= question
->next
;
12234 if (m
->NewLocalOnlyQuestions
== question
) m
->NewLocalOnlyQuestions
= question
->next
;
12236 if (m
->RestartQuestion
== question
)
12238 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12239 question
->qname
.c
, DNSTypeName(question
->qtype
));
12240 m
->RestartQuestion
= question
->next
;
12243 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12244 question
->next
= mDNSNULL
;
12246 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12248 // And finally, cancel any associated GetZoneData operation that's still running.
12249 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12250 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12251 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12252 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12253 if (question
->tcp
) { DisposeTCPConn(question
->tcp
); question
->tcp
= mDNSNULL
; }
12254 if (question
->LocalSocket
) { mDNSPlatformUDPClose(question
->LocalSocket
); question
->LocalSocket
= mDNSNULL
; }
12255 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12256 Querier_HandleStoppedDNSQuestion(question
);
12258 if (!mDNSOpaque16IsZero(question
->TargetQID
) && question
->LongLived
)
12260 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12262 for (q
= m
->Questions
; q
; q
=q
->next
)
12263 if (!mDNSOpaque16IsZero(q
->TargetQID
) && q
->LongLived
) break;
12266 if (!m
->LLQNAT
.clientCallback
) // Should never happen, but just in case...
12268 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12272 LogInfo("Stopping LLQNAT");
12273 mDNS_StopNATOperation_internal(m
, &m
->LLQNAT
);
12274 m
->LLQNAT
.clientCallback
= mDNSNULL
; // Means LLQ NAT Traversal not running
12278 // If necessary, tell server it can delete this LLQ state
12279 if (question
->state
== LLQ_Established
)
12281 question
->ReqLease
= 0;
12282 sendLLQRefresh(m
, question
);
12283 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12284 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12285 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12286 // we let that run out its natural course and complete asynchronously.
12289 question
->tcp
->question
= mDNSNULL
;
12290 question
->tcp
= mDNSNULL
;
12293 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12294 else if (question
->dnsPushServer
!= mDNSNULL
)
12296 UnSubscribeToDNSPushNotificationServer(m
, question
);
12300 // wait until we send the refresh above which needs the nta
12301 if (question
->nta
) { CancelGetZoneData(m
, question
->nta
); question
->nta
= mDNSNULL
; }
12303 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12304 uDNSMetricsClear(&question
->metrics
);
12307 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12308 DNS64ResetState(question
);
12311 return(mStatus_NoError
);
12314 mDNSexport mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
)
12318 status
= mDNS_StartQuery_internal(m
, question
);
12323 mDNSexport mStatus
mDNS_StopQuery(mDNS
*const m
, DNSQuestion
*const question
)
12327 status
= mDNS_StopQuery_internal(m
, question
);
12332 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12333 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12334 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12335 // specifically to catch and report if the client callback does try to make API calls
12336 mDNSexport mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
)
12342 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12343 for (qq
= m
->NewQuestions
; qq
; qq
=qq
->next
) if (qq
== question
) break;
12345 status
= mDNS_StopQuery_internal(m
, question
);
12346 if (status
== mStatus_NoError
&& !qq
)
12348 const CacheRecord
*cr
;
12349 CacheGroup
*const cg
= CacheGroupForName(m
, question
->qnamehash
, &question
->qname
);
12350 LogInfo("Generating terminal removes for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
12351 for (cr
= cg
? cg
->members
: mDNSNULL
; cr
; cr
=cr
->next
)
12353 if (cr
->resrec
.RecordType
!= kDNSRecordTypePacketNegative
&& SameNameCacheRecordAnswersQuestion(cr
, question
))
12355 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12356 if (question
->QuestionCallback
)
12357 question
->QuestionCallback(m
, question
, &cr
->resrec
, mDNSfalse
);
12365 mDNSexport mStatus
mDNS_Reconfirm(mDNS
*const m
, CacheRecord
*const cr
)
12369 status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12370 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, cr
->resrec
.InterfaceID
, 0);
12375 mDNSexport mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
)
12377 mStatus status
= mStatus_BadReferenceErr
;
12380 cr
= FindIdenticalRecordInCache(m
, rr
);
12381 debugf("mDNS_ReconfirmByValue: %p %s", cr
, RRDisplayString(m
, rr
));
12382 if (cr
) status
= mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
12383 if (status
== mStatus_NoError
) ReconfirmAntecedents(m
, cr
->resrec
.name
, cr
->resrec
.namehash
, cr
->resrec
.InterfaceID
, 0);
12388 mDNSlocal mStatus
mDNS_StartBrowse_internal(mDNS
*const m
, DNSQuestion
*const question
,
12389 const domainname
*const srv
, const domainname
*const domain
,
12390 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12391 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12392 mDNSQuestionCallback
*Callback
, void *Context
)
12394 question
->InterfaceID
= InterfaceID
;
12395 question
->flags
= flags
;
12396 question
->qtype
= kDNSType_PTR
;
12397 question
->qclass
= kDNSClass_IN
;
12398 question
->LongLived
= mDNStrue
;
12399 question
->ExpectUnique
= mDNSfalse
;
12400 question
->ForceMCast
= ForceMCast
;
12401 question
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
12402 question
->SuppressUnusable
= mDNSfalse
;
12403 question
->AppendSearchDomains
= mDNSfalse
;
12404 question
->TimeoutQuestion
= 0;
12405 question
->WakeOnResolve
= 0;
12406 question
->UseBackgroundTraffic
= useBackgroundTrafficClass
;
12407 question
->ProxyQuestion
= 0;
12408 question
->QuestionCallback
= Callback
;
12409 question
->QuestionContext
= Context
;
12411 if (!ConstructServiceName(&question
->qname
, mDNSNULL
, srv
, domain
))
12412 return(mStatus_BadParamErr
);
12414 return(mDNS_StartQuery_internal(m
, question
));
12417 mDNSexport mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
12418 const domainname
*const srv
, const domainname
*const domain
,
12419 const mDNSInterfaceID InterfaceID
, mDNSu32 flags
,
12420 mDNSBool ForceMCast
, mDNSBool useBackgroundTrafficClass
,
12421 mDNSQuestionCallback
*Callback
, void *Context
)
12425 status
= mDNS_StartBrowse_internal(m
, question
, srv
, domain
, InterfaceID
, flags
, ForceMCast
, useBackgroundTrafficClass
, Callback
, Context
);
12431 mDNSexport mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
12432 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
)
12434 question
->InterfaceID
= InterfaceID
;
12435 question
->flags
= 0;
12436 question
->qtype
= kDNSType_PTR
;
12437 question
->qclass
= kDNSClass_IN
;
12438 question
->LongLived
= mDNSfalse
;
12439 question
->ExpectUnique
= mDNSfalse
;
12440 question
->ForceMCast
= mDNSfalse
;
12441 question
->ReturnIntermed
= mDNSfalse
;
12442 question
->SuppressUnusable
= mDNSfalse
;
12443 question
->AppendSearchDomains
= mDNSfalse
;
12444 question
->TimeoutQuestion
= 0;
12445 question
->WakeOnResolve
= 0;
12446 question
->UseBackgroundTraffic
= mDNSfalse
;
12447 question
->ProxyQuestion
= 0;
12448 question
->pid
= mDNSPlatformGetPID();
12449 question
->euid
= 0;
12450 question
->QuestionCallback
= Callback
;
12451 question
->QuestionContext
= Context
;
12452 if (DomainType
> mDNS_DomainTypeMax
) return(mStatus_BadParamErr
);
12453 if (!MakeDomainNameFromDNSNameString(&question
->qname
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
12454 if (!dom
) dom
= &localdomain
;
12455 if (!AppendDomainName(&question
->qname
, dom
)) return(mStatus_BadParamErr
);
12456 return(mDNS_StartQuery(m
, question
));
12459 // ***************************************************************************
12460 #if COMPILER_LIKES_PRAGMA_MARK
12462 #pragma mark - Responder Functions
12465 mDNSexport mStatus
mDNS_Register(mDNS
*const m
, AuthRecord
*const rr
)
12469 status
= mDNS_Register_internal(m
, rr
);
12474 mDNSexport mStatus
mDNS_Update(mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
12475 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
)
12477 if (!ValidateRData(rr
->resrec
.rrtype
, newrdlength
, newrdata
))
12479 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr
->resrec
, &newrdata
->u
, m
->MsgBuffer
));
12480 return(mStatus_Invalid
);
12485 // If TTL is unspecified, leave TTL unchanged
12486 if (newttl
== 0) newttl
= rr
->resrec
.rroriginalttl
;
12488 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12491 RData
*n
= rr
->NewRData
;
12492 rr
->NewRData
= mDNSNULL
; // Clear the NewRData pointer ...
12493 if (rr
->UpdateCallback
)
12494 rr
->UpdateCallback(m
, rr
, n
, rr
->newrdlength
); // ...and let the client free this memory, if necessary
12497 rr
->NewRData
= newrdata
;
12498 rr
->newrdlength
= newrdlength
;
12499 rr
->UpdateCallback
= Callback
;
12501 #ifndef UNICAST_DISABLED
12502 if (rr
->ARType
!= AuthRecordLocalOnly
&& rr
->ARType
!= AuthRecordP2P
&& !IsLocalDomain(rr
->resrec
.name
))
12504 mStatus status
= uDNS_UpdateRecord(m
, rr
);
12505 // The caller frees the memory on error, don't retain stale pointers
12506 if (status
!= mStatus_NoError
) { rr
->NewRData
= mDNSNULL
; rr
->newrdlength
= 0; }
12512 if (RRLocalOnly(rr
) || (rr
->resrec
.rroriginalttl
== newttl
&&
12513 rr
->resrec
.rdlength
== newrdlength
&& mDNSPlatformMemSame(rr
->resrec
.rdata
->u
.data
, newrdata
->u
.data
, newrdlength
)))
12514 CompleteRDataUpdate(m
, rr
);
12517 rr
->AnnounceCount
= InitialAnnounceCount
;
12518 InitializeLastAPTime(m
, rr
);
12519 while (rr
->NextUpdateCredit
&& m
->timenow
- rr
->NextUpdateCredit
>= 0) GrantUpdateCredit(rr
);
12520 if (!rr
->UpdateBlocked
&& rr
->UpdateCredits
) rr
->UpdateCredits
--;
12521 if (!rr
->NextUpdateCredit
) rr
->NextUpdateCredit
= NonZeroTime(m
->timenow
+ kUpdateCreditRefreshInterval
);
12522 if (rr
->AnnounceCount
> rr
->UpdateCredits
+ 1) rr
->AnnounceCount
= (mDNSu8
)(rr
->UpdateCredits
+ 1);
12523 if (rr
->UpdateCredits
<= 5)
12525 mDNSu32 delay
= 6 - rr
->UpdateCredits
; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12526 if (!rr
->UpdateBlocked
) rr
->UpdateBlocked
= NonZeroTime(m
->timenow
+ (mDNSs32
)delay
* mDNSPlatformOneSecond
);
12527 rr
->ThisAPInterval
*= 4;
12528 rr
->LastAPTime
= rr
->UpdateBlocked
- rr
->ThisAPInterval
;
12529 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12530 rr
->resrec
.name
->c
, delay
, delay
> 1 ? "s" : "");
12532 rr
->resrec
.rroriginalttl
= newttl
;
12536 return(mStatus_NoError
);
12539 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12540 // the record list and/or question list.
12541 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12542 mDNSexport mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
)
12546 status
= mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_normal
);
12551 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12552 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
12553 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12554 mDNSlocal
void mDNS_RandomizedHostNameCallback(mDNS
*m
, AuthRecord
*rr
, mStatus result
);
12557 mDNSlocal AuthRecord
*GetInterfaceAddressRecord(NetworkInterfaceInfo
*intf
, mDNSBool forRandHostname
)
12559 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12560 return(forRandHostname
? &intf
->RR_AddrRand
: &intf
->RR_A
);
12562 (void)forRandHostname
; // Unused.
12563 return(&intf
->RR_A
);
12567 mDNSlocal AuthRecord
*GetFirstAddressRecordEx(const mDNS
*const m
, const mDNSBool forRandHostname
)
12569 NetworkInterfaceInfo
*intf
;
12570 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12572 if (!intf
->Advertise
) continue;
12573 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12574 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
)) continue;
12576 return(GetInterfaceAddressRecord(intf
, forRandHostname
));
12580 #define GetFirstAddressRecord(M) GetFirstAddressRecordEx(M, mDNSfalse)
12582 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12583 // (It's a set of records, not a set of interfaces.)
12584 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12585 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool useRandomizedHostname
)
12587 mDNSlocal
void AdvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12590 const domainname
*hostname
;
12591 mDNSRecordCallback
*hostnameCallback
;
12592 AuthRecord
*addrAR
;
12594 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12595 const mDNSBool interfaceIsAWDL
= mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
);
12597 mDNSu8 addrRecordType
;
12598 char buffer
[MAX_REVERSE_MAPPING_NAME
];
12600 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12601 if (interfaceIsAWDL
|| useRandomizedHostname
)
12603 hostname
= &m
->RandomizedHostname
;
12604 hostnameCallback
= mDNS_RandomizedHostNameCallback
;
12609 hostname
= &m
->MulticastHostname
;
12610 hostnameCallback
= mDNS_HostNameCallback
;
12613 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12614 if (!interfaceIsAWDL
&& useRandomizedHostname
)
12616 addrAR
= &set
->RR_AddrRand
;
12622 addrAR
= &set
->RR_A
;
12623 ptrAR
= &set
->RR_PTR
;
12625 if (addrAR
->resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
12627 addrRecordType
= set
->DirectLink
? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
12628 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12629 if (hostname
== &m
->RandomizedHostname
) addrRecordType
= kDNSRecordTypeKnownUnique
;
12630 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12631 "AdvertiseInterface: Advertising " PUB_S
" hostname on interface " PUB_S
,
12632 (hostname
== &m
->RandomizedHostname
) ? "randomized" : "normal", set
->ifname
);
12634 LogInfo("AdvertiseInterface: Advertising for ifname %s", set
->ifname
);
12637 // Send dynamic update for non-linklocal IPv4 Addresses
12638 mDNS_SetupResourceRecord(addrAR
, mDNSNULL
, set
->InterfaceID
, kDNSType_A
, kHostNameTTL
, addrRecordType
, AuthRecordAny
, hostnameCallback
, set
);
12639 if (ptrAR
) mDNS_SetupResourceRecord(ptrAR
, mDNSNULL
, set
->InterfaceID
, kDNSType_PTR
, kHostNameTTL
, kDNSRecordTypeKnownUnique
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
12641 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12642 addrAR
->AllowRemoteQuery
= mDNStrue
;
12643 if (ptrAR
) ptrAR
->AllowRemoteQuery
= mDNStrue
;
12645 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12646 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12647 AssignDomainName(&addrAR
->namestorage
, hostname
);
12648 if (set
->ip
.type
== mDNSAddrType_IPv4
)
12650 addrAR
->resrec
.rrtype
= kDNSType_A
;
12651 addrAR
->resrec
.rdata
->u
.ipv4
= set
->ip
.ip
.v4
;
12652 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12653 mDNS_snprintf(buffer
, sizeof(buffer
), "%d.%d.%d.%d.in-addr.arpa.",
12654 set
->ip
.ip
.v4
.b
[3], set
->ip
.ip
.v4
.b
[2], set
->ip
.ip
.v4
.b
[1], set
->ip
.ip
.v4
.b
[0]);
12656 else if (set
->ip
.type
== mDNSAddrType_IPv6
)
12659 addrAR
->resrec
.rrtype
= kDNSType_AAAA
;
12660 addrAR
->resrec
.rdata
->u
.ipv6
= set
->ip
.ip
.v6
;
12661 for (i
= 0; i
< 16; i
++)
12663 static const char hexValues
[] = "0123456789ABCDEF";
12664 buffer
[i
* 4 ] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] & 0x0F];
12665 buffer
[i
* 4 + 1] = '.';
12666 buffer
[i
* 4 + 2] = hexValues
[set
->ip
.ip
.v6
.b
[15 - i
] >> 4];
12667 buffer
[i
* 4 + 3] = '.';
12669 mDNS_snprintf(&buffer
[64], sizeof(buffer
)-64, "ip6.arpa.");
12674 MakeDomainNameFromDNSNameString(&ptrAR
->namestorage
, buffer
);
12675 ptrAR
->AutoTarget
= Target_AutoHost
; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12676 ptrAR
->ForceMCast
= mDNStrue
; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12679 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12680 addrAR
->RRSet
= interfaceIsAWDL
? addrAR
: GetFirstAddressRecordEx(m
, useRandomizedHostname
);
12682 addrAR
->RRSet
= GetFirstAddressRecord(m
);
12684 if (!addrAR
->RRSet
) addrAR
->RRSet
= addrAR
;
12685 mDNS_Register_internal(m
, addrAR
);
12686 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "Initialized RRSet for " PRI_S
, ARDisplayString(m
, addrAR
));
12687 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "RRSet: " PRI_S
, ARDisplayString(m
, addrAR
->RRSet
));
12688 if (ptrAR
) mDNS_Register_internal(m
, ptrAR
);
12690 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12691 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12692 D2D_start_advertising_interface(set
);
12696 mDNSlocal
void AdvertiseInterfaceIfNeeded(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12698 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12699 if (mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
))
12701 if ((m
->AutoTargetAWDLIncludedCount
> 0) || (m
->AutoTargetAWDLOnlyCount
> 0))
12703 AdvertiseInterface(m
, set
, mDNSfalse
);
12708 if (m
->AutoTargetServices
> 0) AdvertiseInterface(m
, set
, mDNSfalse
);
12709 if (m
->AutoTargetAWDLIncludedCount
> 0) AdvertiseInterface(m
, set
, mDNStrue
);
12712 if (m
->AutoTargetServices
> 0) AdvertiseInterface(m
, set
);
12716 mDNSlocal
void DeadvertiseInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, DeadvertiseFlags flags
)
12718 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12719 const mDNSBool interfaceIsAWDL
= mDNSPlatformInterfaceIsAWDL(set
->InterfaceID
);
12722 // Unregister these records.
12723 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12724 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12725 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12726 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12727 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12728 if ((!interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_NormalHostname
)) ||
12729 ( interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_RandHostname
)))
12731 if (flags
& kDeadvertiseFlag_NormalHostname
)
12734 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12735 "DeadvertiseInterface: Deadvertising " PUB_S
" hostname on interface " PUB_S
,
12736 (flags
& kDeadvertiseFlag_RandHostname
) ? "randomized" : "normal", set
->ifname
);
12737 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12738 D2D_stop_advertising_interface(set
);
12740 if (set
->RR_A
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_A
, mDNS_Dereg_normal
);
12741 if (set
->RR_PTR
.resrec
.RecordType
) mDNS_Deregister_internal(m
, &set
->RR_PTR
, mDNS_Dereg_normal
);
12743 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12744 if (!interfaceIsAWDL
&& (flags
& kDeadvertiseFlag_RandHostname
))
12746 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
12747 "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S
, set
->ifname
);
12748 AuthRecord
*const ar
= &set
->RR_AddrRand
;
12749 if (ar
->resrec
.RecordType
) mDNS_Deregister_internal(m
, ar
, mDNS_Dereg_normal
);
12754 // Change target host name for record.
12755 mDNSlocal
void UpdateTargetHostName(mDNS
*const m
, AuthRecord
*const rr
)
12757 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12758 // If this record was also registered with any D2D plugins, stop advertising
12759 // the version with the old host name.
12760 D2D_stop_advertising_record(rr
);
12763 SetTargetToHostName(m
, rr
);
12765 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12766 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12767 D2D_start_advertising_record(rr
);
12771 mDNSlocal
void DeadvertiseAllInterfaceRecords(mDNS
*const m
, DeadvertiseFlags flags
)
12773 NetworkInterfaceInfo
*intf
;
12774 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12776 if (intf
->Advertise
) DeadvertiseInterface(m
, intf
, flags
);
12780 mDNSexport
void mDNS_SetFQDN(mDNS
*const m
)
12782 domainname newmname
;
12786 if (!AppendDomainLabel(&newmname
, &m
->hostlabel
)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12787 if (!AppendLiteralLabelString(&newmname
, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12791 if (SameDomainNameCS(&m
->MulticastHostname
, &newmname
)) debugf("mDNS_SetFQDN - hostname unchanged");
12794 AssignDomainName(&m
->MulticastHostname
, &newmname
);
12795 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_NormalHostname
);
12796 AdvertiseNecessaryInterfaceRecords(m
);
12799 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12800 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12801 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
) if (rr
->AutoTarget
) UpdateTargetHostName(m
, rr
);
12806 mDNSlocal
void mDNS_HostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
12808 (void)rr
; // Unused parameter
12812 char *msg
= "Unknown result";
12813 if (result
== mStatus_NoError
) msg
= "Name registered";
12814 else if (result
== mStatus_NameConflict
) msg
= "Name conflict";
12815 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
12819 if (result
== mStatus_NoError
)
12821 // Notify the client that the host name is successfully registered
12822 if (m
->MainCallback
)
12823 m
->MainCallback(m
, mStatus_NoError
);
12825 else if (result
== mStatus_NameConflict
)
12827 domainlabel oldlabel
= m
->hostlabel
;
12829 // 1. First give the client callback a chance to pick a new name
12830 if (m
->MainCallback
)
12831 m
->MainCallback(m
, mStatus_NameConflict
);
12833 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12834 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12835 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12836 if (SameDomainLabel(m
->hostlabel
.c
, oldlabel
.c
))
12837 IncrementLabelSuffix(&m
->hostlabel
, mDNSfalse
);
12839 // 3. Generate the FQDNs from the hostlabel,
12840 // and make sure all SRV records, etc., are updated to reference our new hostname
12842 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel
.c
, m
->hostlabel
.c
);
12844 else if (result
== mStatus_MemFree
)
12846 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12847 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12848 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12851 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result
, rr
->resrec
.name
->c
);
12854 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12855 mDNSlocal
void mDNS_RandomizedHostNameCallback(mDNS
*const m
, AuthRecord
*const addrRecord
, const mStatus result
)
12857 (void)addrRecord
; // Unused parameter
12859 if (result
== mStatus_NameConflict
)
12862 domainlabel newUUIDLabel
;
12864 GetRandomUUIDLabel(&newUUIDLabel
);
12865 if (SameDomainLabel(newUUIDLabel
.c
, m
->RandomizedHostname
.c
))
12867 IncrementLabelSuffix(&newUUIDLabel
, mDNSfalse
);
12872 m
->RandomizedHostname
.c
[0] = 0;
12873 AppendDomainLabel(&m
->RandomizedHostname
, &newUUIDLabel
);
12874 AppendLiteralLabelString(&m
->RandomizedHostname
, "local");
12876 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_RandHostname
);
12877 AdvertiseNecessaryInterfaceRecords(m
);
12878 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
12880 if (rr
->AutoTarget
&& AuthRecordIncludesOrIsAWDL(rr
)) UpdateTargetHostName(m
, rr
);
12882 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
12884 if (rr
->AutoTarget
&& AuthRecordIncludesOrIsAWDL(rr
)) UpdateTargetHostName(m
, rr
);
12892 mDNSlocal
void UpdateInterfaceProtocols(mDNS
*const m
, NetworkInterfaceInfo
*active
)
12894 NetworkInterfaceInfo
*intf
;
12895 active
->IPv4Available
= mDNSfalse
;
12896 active
->IPv6Available
= mDNSfalse
;
12897 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
12898 if (intf
->InterfaceID
== active
->InterfaceID
)
12900 if (intf
->ip
.type
== mDNSAddrType_IPv4
&& intf
->McastTxRx
) active
->IPv4Available
= mDNStrue
;
12901 if (intf
->ip
.type
== mDNSAddrType_IPv6
&& intf
->McastTxRx
) active
->IPv6Available
= mDNStrue
;
12905 mDNSlocal
void RestartRecordGetZoneData(mDNS
* const m
)
12908 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12909 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
12910 if (AuthRecord_uDNS(rr
) && rr
->state
!= regState_NoTarget
)
12912 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr
->resrec
.name
->c
);
12913 // Zero out the updateid so that if we have a pending response from the server, it won't
12914 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12915 if (rr
->nta
) { rr
->updateid
= zeroID
; CancelGetZoneData(m
, rr
->nta
); }
12916 rr
->nta
= StartGetZoneData(m
, rr
->resrec
.name
, ZoneServiceUpdate
, RecordRegistrationGotZoneData
, rr
);
12920 mDNSlocal
void InitializeNetWakeState(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12923 // We initialize ThisQInterval to -1 indicating that the question has not been started
12924 // yet. If the question (browse) is started later during interface registration, it will
12925 // be stopped during interface deregistration. We can't sanity check to see if the
12926 // question has been stopped or not before initializing it to -1 because we need to
12927 // initialize it to -1 the very first time.
12929 set
->NetWakeBrowse
.ThisQInterval
= -1;
12930 for (i
=0; i
<3; i
++)
12932 set
->NetWakeResolve
[i
].ThisQInterval
= -1;
12933 set
->SPSAddr
[i
].type
= mDNSAddrType_None
;
12935 set
->NextSPSAttempt
= -1;
12936 set
->NextSPSAttemptTime
= m
->timenow
;
12939 mDNSexport
void mDNS_ActivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12941 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12942 while (p
&& p
!= set
) p
=p
->next
;
12943 if (!p
) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12945 if (set
->InterfaceActive
)
12947 LogSPS("ActivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12948 mDNS_StartBrowse_internal(m
, &set
->NetWakeBrowse
, &SleepProxyServiceType
, &localdomain
, set
->InterfaceID
, 0, mDNSfalse
, mDNSfalse
, m
->SPSBrowseCallback
, set
);
12952 mDNSexport
void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
)
12954 NetworkInterfaceInfo
*p
= m
->HostInterfaces
;
12955 while (p
&& p
!= set
) p
=p
->next
;
12956 if (!p
) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set
); return; }
12958 // Note: We start the browse only if the interface is NetWake capable and we use this to
12959 // stop the resolves also. Hence, the resolves should not be started without the browse
12960 // being started i.e, resolves should not happen unless NetWake capable which is
12961 // guaranteed by BeginSleepProcessing.
12962 if (set
->NetWakeBrowse
.ThisQInterval
>= 0)
12965 LogSPS("DeactivateNetWake for %s (%#a)", set
->ifname
, &set
->ip
);
12967 // Stop our browse and resolve operations
12968 mDNS_StopQuery_internal(m
, &set
->NetWakeBrowse
);
12969 for (i
=0; i
<3; i
++) if (set
->NetWakeResolve
[i
].ThisQInterval
>= 0) mDNS_StopQuery_internal(m
, &set
->NetWakeResolve
[i
]);
12971 // Make special call to the browse callback to let it know it can to remove all records for this interface
12972 if (m
->SPSBrowseCallback
)
12974 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12975 m
->SPSBrowseCallback(m
, &set
->NetWakeBrowse
, mDNSNULL
, mDNSfalse
);
12976 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12979 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12980 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12981 InitializeNetWakeState(m
, set
);
12985 mDNSexport mStatus
mDNS_RegisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, InterfaceActivationSpeed activationSpeed
)
12988 mDNSBool FirstOfType
= mDNStrue
;
12989 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
12991 if (!set
->InterfaceID
)
12993 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_ERROR
,
12994 "Tried to register a NetworkInterfaceInfo with zero InterfaceID - ifaddr: " PRI_IP_ADDR
, &set
->ip
);
12995 return(mStatus_Invalid
);
12998 if (!mDNSAddressIsValidNonZero(&set
->mask
))
13000 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_ERROR
,
13001 "Tried to register a NetworkInterfaceInfo with invalid mask - ifaddr: " PRI_IP_ADDR
", ifmask: " PUB_IP_ADDR
,
13002 &set
->ip
, &set
->mask
);
13003 return(mStatus_Invalid
);
13008 // Assume this interface will be active now, unless we find a duplicate already in the list
13009 set
->InterfaceActive
= mDNStrue
;
13010 set
->IPv4Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
);
13011 set
->IPv6Available
= (mDNSu8
)(set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
);
13013 InitializeNetWakeState(m
, set
);
13015 // Scan list to see if this InterfaceID is already represented
13020 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_ERROR
,
13021 "Tried to register a NetworkInterfaceInfo that's already in the list - "
13022 "ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
, set
->ifname
, &set
->ip
);
13024 return(mStatus_AlreadyRegistered
);
13027 if ((*p
)->InterfaceID
== set
->InterfaceID
)
13029 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13030 set
->InterfaceActive
= mDNSfalse
;
13031 if (set
->ip
.type
== (*p
)->ip
.type
) FirstOfType
= mDNSfalse
;
13032 if (set
->ip
.type
== mDNSAddrType_IPv4
&& set
->McastTxRx
) (*p
)->IPv4Available
= mDNStrue
;
13033 if (set
->ip
.type
== mDNSAddrType_IPv6
&& set
->McastTxRx
) (*p
)->IPv6Available
= mDNStrue
;
13039 set
->next
= mDNSNULL
;
13042 if (set
->Advertise
) AdvertiseInterfaceIfNeeded(m
, set
);
13044 if (set
->InterfaceActive
)
13046 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_INFO
,
13047 "Interface not represented in list; marking active and retriggering queries - "
13048 "ifid: %d, ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
, IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13052 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_INFO
,
13053 "Interface already represented in list - "
13054 "ifid: %d, ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
, IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13057 if (set
->NetWake
) mDNS_ActivateNetWake_internal(m
, set
);
13059 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13060 // giving the false impression that there's an active representative of this interface when there really isn't.
13061 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13062 // even if we believe that we previously had an active representative of this interface.
13063 if (set
->McastTxRx
&& (FirstOfType
|| set
->InterfaceActive
))
13066 // Normally, after an interface comes up, we pause half a second before beginning probing.
13067 // This is to guard against cases where there's rapid interface changes, where we could be confused by
13068 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13069 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13070 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13071 // and think it's a conflicting answer to our probe.
13072 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13073 mDNSs32 probedelay
;
13074 mDNSu8 numannounce
;
13075 switch (activationSpeed
)
13077 case FastActivation
:
13078 probedelay
= (mDNSs32
)0;
13079 numannounce
= InitialAnnounceCount
;
13080 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_DEFAULT
,
13081 "Using fast activation for DirectLink interface - ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
,
13082 set
->ifname
, &set
->ip
);
13085 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13086 case SlowActivation
:
13087 probedelay
= mDNSPlatformOneSecond
* 5;
13088 numannounce
= (mDNSu8
)1;
13089 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_DEFAULT
,
13090 "Frequent transitions for interface, doing slow activation - "
13091 "ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
, set
->ifname
, &set
->ip
);
13092 m
->mDNSStats
.InterfaceUpFlap
++;
13096 case NormalActivation
:
13098 probedelay
= mDNSPlatformOneSecond
/ 2;
13099 numannounce
= InitialAnnounceCount
;
13103 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_INFO
,
13104 "Interface probe will be delayed - ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
", probe delay: %d",
13105 set
->ifname
, &set
->ip
, probedelay
);
13107 // No probe or sending suppression on DirectLink type interfaces.
13108 if (activationSpeed
== FastActivation
)
13110 m
->SuppressSending
= 0;
13111 m
->SuppressProbes
= 0;
13115 // Use a small amount of randomness:
13116 // In the case of a network administrator turning on an Ethernet hub so that all the
13117 // connected machines establish link at exactly the same time, we don't want them all
13118 // to go and hit the network with identical queries at exactly the same moment.
13119 // We set a random delay of up to InitialQuestionInterval (1/3 second).
13120 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13121 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13122 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13123 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13124 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13125 if (!m
->SuppressSending
) m
->SuppressSending
= m
->timenow
+ (mDNSs32
)mDNSRandom((mDNSu32
)InitialQuestionInterval
);
13127 if (m
->SuppressProbes
== 0 ||
13128 m
->SuppressProbes
- NonZeroTime(m
->timenow
+ probedelay
) < 0)
13129 m
->SuppressProbes
= NonZeroTime(m
->timenow
+ probedelay
);
13132 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13133 // it here also handles the wake up case as the network link comes UP after waking causing
13134 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13135 // that the network link comes UP after 60 seconds and we never set the OWNER option
13136 m
->AnnounceOwner
= NonZeroTime(m
->timenow
+ 60 * mDNSPlatformOneSecond
);
13137 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_DEBUG
, "Setting AnnounceOwner");
13139 m
->mDNSStats
.InterfaceUp
++;
13140 for (q
= m
->Questions
; q
; q
=q
->next
) // Scan our list of questions
13142 if (mDNSOpaque16IsZero(q
->TargetQID
))
13144 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
) // If non-specific Q, or Q on this specific interface,
13145 { // then reactivate this question
13146 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13147 // If flapping, delay between first and second queries is nine seconds instead of one second
13148 mDNSBool dodelay
= (activationSpeed
== SlowActivation
) && (q
->FlappingInterface1
== set
->InterfaceID
|| q
->FlappingInterface2
== set
->InterfaceID
);
13149 mDNSs32 initial
= dodelay
? InitialQuestionInterval
* QuestionIntervalStep2
: InitialQuestionInterval
;
13150 mDNSs32 qdelay
= dodelay
? kDefaultQueryDelayTimeForFlappingInterface
: 0;
13153 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_INFO
,
13154 "No cache records expired for the question " PRI_DM_NAME
" (" PUB_S
");"
13155 " delaying it by %d seconds", DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), qdelay
);
13158 mDNSs32 initial
= InitialQuestionInterval
;
13159 mDNSs32 qdelay
= 0;
13162 if (!q
->ThisQInterval
|| q
->ThisQInterval
> initial
)
13164 q
->ThisQInterval
= initial
;
13165 q
->RequestUnicast
= kDefaultRequestUnicastCount
;
13167 q
->LastQTime
= m
->timenow
- q
->ThisQInterval
+ qdelay
;
13168 q
->RecentAnswerPkts
= 0;
13169 SetNextQueryTime(m
,q
);
13174 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13175 // we now need them to re-probe if necessary, and then re-announce.
13176 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13178 if (!rr
->resrec
.InterfaceID
|| rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13180 mDNSCoreRestartRegistration(m
, rr
, numannounce
);
13185 RestartRecordGetZoneData(m
);
13187 mDNS_UpdateAllowSleep(m
);
13190 return(mStatus_NoError
);
13193 mDNSlocal
void AdjustAddressRecordSetsEx(mDNS
*const m
, NetworkInterfaceInfo
*removedIntf
, mDNSBool forRandHostname
)
13195 NetworkInterfaceInfo
*intf
;
13196 const AuthRecord
*oldAR
;
13198 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13199 if (mDNSPlatformInterfaceIsAWDL(removedIntf
->InterfaceID
)) return;
13201 oldAR
= GetInterfaceAddressRecord(removedIntf
, forRandHostname
);
13202 newAR
= GetFirstAddressRecordEx(m
, forRandHostname
);
13203 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13206 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13207 if (mDNSPlatformInterfaceIsAWDL(intf
->InterfaceID
)) continue;
13209 ar
= GetInterfaceAddressRecord(intf
, forRandHostname
);
13210 if (ar
->RRSet
== oldAR
)
13212 ar
->RRSet
= newAR
? newAR
: ar
;
13213 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "Changed RRSet for " PRI_S
, ARDisplayString(m
, ar
));
13214 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "New RRSet: " PRI_S
, ARDisplayString(m
, ar
->RRSet
));
13218 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13219 #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue)
13221 #define AdjustAddressRecordSets(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse)
13223 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13224 // the record list and/or question list.
13225 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13226 mDNSexport
void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, InterfaceActivationSpeed activationSpeed
)
13228 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13229 (void)activationSpeed
; // Unused parameter
13231 NetworkInterfaceInfo
**p
= &m
->HostInterfaces
;
13232 mDNSBool revalidate
= mDNSfalse
;
13233 NetworkInterfaceInfo
*intf
;
13237 // Find this record in our list
13238 while (*p
&& *p
!= set
) p
=&(*p
)->next
;
13241 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_DEBUG
, "NetworkInterfaceInfo not found in list");
13246 mDNS_DeactivateNetWake_internal(m
, set
);
13248 // Unlink this record from our list
13250 set
->next
= mDNSNULL
;
13252 if (!set
->InterfaceActive
)
13254 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13255 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13256 if (intf
->InterfaceActive
&& intf
->InterfaceID
== set
->InterfaceID
)
13257 UpdateInterfaceProtocols(m
, intf
);
13261 intf
= FirstInterfaceForID(m
, set
->InterfaceID
);
13264 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_INFO
,
13265 "Another representative of InterfaceID exists - ifid: %d, ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
,
13266 IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13267 if (intf
->InterfaceActive
)
13269 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_ERROR
,
13270 "intf->InterfaceActive already set for interface - ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
,
13271 set
->ifname
, &set
->ip
);
13273 intf
->InterfaceActive
= mDNStrue
;
13274 UpdateInterfaceProtocols(m
, intf
);
13276 if (intf
->NetWake
) mDNS_ActivateNetWake_internal(m
, intf
);
13278 // See if another representative *of the same type* exists. If not, we mave have gone from
13279 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13280 for (intf
= m
->HostInterfaces
; intf
; intf
= intf
->next
)
13281 if (intf
->InterfaceID
== set
->InterfaceID
&& intf
->ip
.type
== set
->ip
.type
)
13283 if (!intf
) revalidate
= mDNStrue
;
13291 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13292 mDNSu32 cacheHitMulticastCount
= 0;
13293 mDNSu32 cacheMissMulticastCount
= 0;
13294 mDNSu32 cacheHitUnicastCount
= 0;
13295 mDNSu32 cacheMissUnicastCount
= 0;
13297 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_INFO
,
13298 "Last representative of InterfaceID deregistered; marking questions etc. dormant - "
13299 "ifid: %d, ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
,
13300 IIDPrintable(set
->InterfaceID
), set
->ifname
, &set
->ip
);
13302 m
->mDNSStats
.InterfaceDown
++;
13304 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13305 if (set
->McastTxRx
&& (activationSpeed
== SlowActivation
))
13307 LogRedact(MDNS_LOG_CATEGORY_MDNS
, MDNS_LOG_DEFAULT
,
13308 "Frequent transitions for interface - ifname: " PUB_S
", ifaddr: " PRI_IP_ADDR
,
13309 set
->ifname
, &set
->ip
);
13310 m
->mDNSStats
.InterfaceDownFlap
++;
13314 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13315 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13316 for (q
= m
->Questions
; q
; q
=q
->next
)
13318 if (mDNSOpaque16IsZero(q
->TargetQID
)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13320 if (q
->InterfaceID
== set
->InterfaceID
) q
->ThisQInterval
= 0;
13321 if (!q
->InterfaceID
|| q
->InterfaceID
== set
->InterfaceID
)
13323 q
->FlappingInterface2
= q
->FlappingInterface1
;
13324 q
->FlappingInterface1
= set
->InterfaceID
; // Keep history of the last two interfaces to go away
13329 // 2. Flush any cache records received on this interface
13330 revalidate
= mDNSfalse
; // Don't revalidate if we're flushing the records
13331 FORALL_CACHERECORDS(slot
, cg
, rr
)
13333 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13335 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13336 // If this interface is deemed flapping,
13337 // postpone deleting the cache records in case the interface comes back again
13338 if (set
->McastTxRx
&& (activationSpeed
== SlowActivation
))
13340 // For a flapping interface we want these records to go away after
13341 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13342 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13343 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13344 // if the interface does come back, any relevant questions will be reactivated anyway
13345 rr
->UnansweredQueries
= MaxUnansweredQueries
;
13350 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13351 if (rr
->LastCachedAnswerTime
)
13353 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13354 if (rr
->resrec
.dnsservice
) cacheHitUnicastCount
++;
13356 if (rr
->resrec
.rDNSServer
) cacheHitUnicastCount
++;
13358 else cacheHitMulticastCount
++;
13362 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13363 if (rr
->resrec
.dnsservice
) cacheMissUnicastCount
++;
13365 if (rr
->resrec
.rDNSServer
) cacheMissUnicastCount
++;
13367 else cacheMissMulticastCount
++;
13370 mDNS_PurgeCacheResourceRecord(m
, rr
);
13374 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13375 dnssd_analytics_update_cache_usage_counts(cacheHitMulticastCount
, cacheMissMulticastCount
, cacheHitUnicastCount
, cacheMissUnicastCount
);
13380 // If we still have address records referring to this one, update them.
13381 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13382 // so the call to AdjustAddressRecordSets*() won’t accidentally find it.
13383 AdjustAddressRecordSets(m
, set
);
13384 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13385 AdjustAddressRecordSetsForRandHostname(m
, set
);
13388 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13389 if (set
->Advertise
) DeadvertiseInterface(m
, set
, kDeadvertiseFlag_All
);
13391 // If we have any cache records received on this interface that went away, then re-verify them.
13392 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13393 // giving the false impression that there's an active representative of this interface when there really isn't.
13394 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13395 if (revalidate
&& !m
->ShutdownTime
)
13400 FORALL_CACHERECORDS(slot
, cg
, rr
)
13401 if (rr
->resrec
.InterfaceID
== set
->InterfaceID
)
13402 mDNS_Reconfirm_internal(m
, rr
, kDefaultReconfirmTimeForFlappingInterface
);
13405 mDNS_UpdateAllowSleep(m
);
13410 mDNSlocal
void ServiceCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13412 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13413 (void)m
; // Unused parameter
13417 char *msg
= "Unknown result";
13418 if (result
== mStatus_NoError
) msg
= "Name Registered";
13419 else if (result
== mStatus_NameConflict
) msg
= "Name Conflict";
13420 else if (result
== mStatus_MemFree
) msg
= "Memory Free";
13421 debugf("ServiceCallback: %##s (%s) %s (%d)", rr
->resrec
.name
->c
, DNSTypeName(rr
->resrec
.rrtype
), msg
, result
);
13425 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13426 if (result
== mStatus_NoError
&& rr
!= &sr
->RR_SRV
) return;
13428 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13429 if (result
== mStatus_NameConflict
)
13431 sr
->Conflict
= mDNStrue
; // Record that this service set had a conflict
13432 mDNS_DeregisterService(m
, sr
); // Unlink the records from our list
13436 if (result
== mStatus_MemFree
)
13438 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13439 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13440 // every record is finished cleaning up.
13442 ExtraResourceRecord
*e
= sr
->Extras
;
13444 if (sr
->RR_SRV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13445 if (sr
->RR_TXT
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13446 if (sr
->RR_PTR
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13447 if (sr
->RR_ADV
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13448 for (i
=0; i
<sr
->NumSubTypes
; i
++) if (sr
->SubTypes
[i
].resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13452 if (e
->r
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
) return;
13456 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13457 // then we can now report the NameConflict to the client
13458 if (sr
->Conflict
) result
= mStatus_NameConflict
;
13462 LogInfo("ServiceCallback: All records %s for %##s", (result
== mStatus_MemFree
? "Unregistered" : "Registered"), sr
->RR_PTR
.resrec
.name
->c
);
13463 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13464 // function is allowed to do anything, including deregistering this service and freeing its memory.
13465 if (sr
->ServiceCallback
)
13466 sr
->ServiceCallback(m
, sr
, result
);
13469 mDNSlocal
void NSSCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
13471 ServiceRecordSet
*sr
= (ServiceRecordSet
*)rr
->RecordContext
;
13472 if (sr
->ServiceCallback
)
13473 sr
->ServiceCallback(m
, sr
, result
);
13477 // Derive AuthRecType from the kDNSServiceFlags* values.
13478 mDNSlocal AuthRecType
setAuthRecType(mDNSInterfaceID InterfaceID
, mDNSu32 flags
)
13480 AuthRecType artype
;
13482 if (InterfaceID
== mDNSInterface_LocalOnly
)
13483 artype
= AuthRecordLocalOnly
;
13484 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13485 artype
= AuthRecordP2P
;
13486 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
)
13487 && (flags
& kDNSServiceFlagsIncludeAWDL
))
13488 artype
= AuthRecordAnyIncludeAWDLandP2P
;
13489 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
))
13490 artype
= AuthRecordAnyIncludeP2P
;
13491 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeAWDL
))
13492 artype
= AuthRecordAnyIncludeAWDL
;
13494 artype
= AuthRecordAny
;
13500 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13501 // Type is service type (e.g. "_ipp._tcp.")
13502 // Domain is fully qualified domain name (i.e. ending with a null label)
13503 // We always register a TXT, even if it is empty (so that clients are not
13504 // left waiting forever looking for a nonexistent record.)
13505 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13506 // then the default host name (m->MulticastHostname) is automatically used
13507 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13508 mDNSexport mStatus
mDNS_RegisterService(mDNS
*const m
, ServiceRecordSet
*sr
,
13509 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13510 const domainname
*const host
, mDNSIPPort port
, RData
*const txtrdata
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
13511 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
13512 mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
, mDNSu32 flags
)
13516 AuthRecType artype
;
13517 mDNSu8 recordType
= (flags
& kDNSServiceFlagsKnownUnique
) ? kDNSRecordTypeKnownUnique
: kDNSRecordTypeUnique
;
13519 sr
->ServiceCallback
= Callback
;
13520 sr
->ServiceContext
= Context
;
13521 sr
->Conflict
= mDNSfalse
;
13523 sr
->Extras
= mDNSNULL
;
13524 sr
->NumSubTypes
= NumSubTypes
;
13525 sr
->SubTypes
= SubTypes
;
13528 artype
= setAuthRecType(InterfaceID
, flags
);
13530 // Initialize the AuthRecord objects to sane values
13531 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13532 mDNS_SetupResourceRecord(&sr
->RR_ADV
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeAdvisory
, artype
, ServiceCallback
, sr
);
13533 mDNS_SetupResourceRecord(&sr
->RR_PTR
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13535 if (flags
& kDNSServiceFlagsWakeOnlyService
)
13537 sr
->RR_PTR
.AuthFlags
= AuthFlagsWakeOnly
;
13540 mDNS_SetupResourceRecord(&sr
->RR_SRV
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, recordType
, artype
, ServiceCallback
, sr
);
13541 mDNS_SetupResourceRecord(&sr
->RR_TXT
, txtrdata
, InterfaceID
, kDNSType_TXT
, kStandardTTL
, recordType
, artype
, ServiceCallback
, sr
);
13543 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13544 if (mDNSIPPortIsZero(port
))
13545 return(mDNS_RegisterNoSuchService(m
, &sr
->RR_SRV
, name
, type
, domain
, mDNSNULL
, InterfaceID
, NSSCallback
, sr
, flags
));
13547 // If the caller is registering an oversized TXT record,
13548 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13549 if (sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
< txtlen
)
13550 sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
= txtlen
;
13552 // Set up the record names
13553 // For now we only create an advisory record for the main type, not for subtypes
13554 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13555 if (ConstructServiceName(&sr
->RR_ADV
.namestorage
, (const domainlabel
*)"\x09_services", (const domainname
*)"\x07_dns-sd\x04_udp", domain
) == mDNSNULL
)
13556 return(mStatus_BadParamErr
);
13557 if (ConstructServiceName(&sr
->RR_PTR
.namestorage
, mDNSNULL
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13558 if (ConstructServiceName(&sr
->RR_SRV
.namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13559 AssignDomainName(&sr
->RR_TXT
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13561 // 1. Set up the ADV record rdata to advertise our service type
13562 AssignDomainName(&sr
->RR_ADV
.resrec
.rdata
->u
.name
, sr
->RR_PTR
.resrec
.name
);
13564 // 2. Set up the PTR record rdata to point to our service name
13565 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13566 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13567 AssignDomainName(&sr
->RR_PTR
.resrec
.rdata
->u
.name
, sr
->RR_SRV
.resrec
.name
);
13568 sr
->RR_PTR
.Additional1
= &sr
->RR_SRV
;
13569 sr
->RR_PTR
.Additional2
= &sr
->RR_TXT
;
13571 // 2a. Set up any subtype PTRs to point to our service name
13572 // If the client is using subtypes, it is the client's responsibility to have
13573 // already set the first label of the record name to the subtype being registered
13574 for (i
=0; i
<NumSubTypes
; i
++)
13577 AssignDomainName(&st
, sr
->SubTypes
[i
].resrec
.name
);
13578 st
.c
[1+st
.c
[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13579 AppendDomainName(&st
, type
);
13580 mDNS_SetupResourceRecord(&sr
->SubTypes
[i
], mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, ServiceCallback
, sr
);
13581 if (ConstructServiceName(&sr
->SubTypes
[i
].namestorage
, mDNSNULL
, &st
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13582 AssignDomainName(&sr
->SubTypes
[i
].resrec
.rdata
->u
.name
, &sr
->RR_SRV
.namestorage
);
13583 sr
->SubTypes
[i
].Additional1
= &sr
->RR_SRV
;
13584 sr
->SubTypes
[i
].Additional2
= &sr
->RR_TXT
;
13587 // 3. Set up the SRV record rdata.
13588 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.priority
= 0;
13589 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.weight
= 0;
13590 sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
= port
;
13592 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13593 if (host
&& host
->c
[0]) AssignDomainName(&sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
, host
);
13594 else { sr
->RR_SRV
.AutoTarget
= Target_AutoHost
; sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
.c
[0] = '\0'; }
13596 // 4. Set up the TXT record rdata,
13597 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13598 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13599 if (txtinfo
== mDNSNULL
) sr
->RR_TXT
.resrec
.rdlength
= 0;
13600 else if (txtinfo
!= sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
)
13602 sr
->RR_TXT
.resrec
.rdlength
= txtlen
;
13603 if (sr
->RR_TXT
.resrec
.rdlength
> sr
->RR_TXT
.resrec
.rdata
->MaxRDLength
) return(mStatus_BadParamErr
);
13604 mDNSPlatformMemCopy(sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, txtinfo
, txtlen
);
13606 sr
->RR_TXT
.DependentOn
= &sr
->RR_SRV
;
13609 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13610 // that if the SRV cannot find a target, rest of the records that belong to this service
13611 // will not be activated.
13612 err
= mDNS_Register_internal(m
, &sr
->RR_SRV
);
13613 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13614 // any list and hence no need to deregister. We could probably do similar checks for other
13615 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13621 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_TXT
);
13622 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13623 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13624 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13625 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13626 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13627 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_ADV
);
13628 for (i
=0; i
<NumSubTypes
; i
++) if (!err
) err
= mDNS_Register_internal(m
, &sr
->SubTypes
[i
]);
13629 if (!err
) err
= mDNS_Register_internal(m
, &sr
->RR_PTR
);
13633 if (err
) mDNS_DeregisterService(m
, sr
);
13637 mDNSexport mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
,
13638 ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
, mDNSu32 flags
)
13640 ExtraResourceRecord
**e
;
13642 AuthRecType artype
;
13643 mDNSInterfaceID InterfaceID
= sr
->RR_PTR
.resrec
.InterfaceID
;
13644 ResourceRecord
*rr
;
13646 artype
= setAuthRecType(InterfaceID
, flags
);
13648 extra
->next
= mDNSNULL
;
13649 mDNS_SetupResourceRecord(&extra
->r
, rdata
, sr
->RR_PTR
.resrec
.InterfaceID
,
13650 extra
->r
.resrec
.rrtype
, ttl
, kDNSRecordTypeUnique
, artype
, ServiceCallback
, sr
);
13651 AssignDomainName(&extra
->r
.namestorage
, sr
->RR_SRV
.resrec
.name
);
13655 if (extra
->r
.resrec
.rrtype
== kDNSType_TXT
)
13657 if (sr
->RR_TXT
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_TXT
.resrec
;
13659 else if (extra
->r
.resrec
.rrtype
== kDNSType_SRV
)
13661 if (sr
->RR_SRV
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
) rr
= &sr
->RR_SRV
.resrec
;
13666 ExtraResourceRecord
*srExtra
;
13668 for (srExtra
= sr
->Extras
; srExtra
; srExtra
= srExtra
->next
)
13670 if ((srExtra
->r
.resrec
.rrtype
== extra
->r
.resrec
.rrtype
) && (srExtra
->r
.resrec
.RecordType
& kDNSRecordTypeUniqueMask
))
13672 rr
= &srExtra
->r
.resrec
;
13678 if (rr
&& (extra
->r
.resrec
.rroriginalttl
!= rr
->rroriginalttl
))
13680 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13681 extra
->r
.resrec
.rroriginalttl
, rr
->rroriginalttl
, RRDisplayString(m
, &extra
->r
.resrec
));
13682 extra
->r
.resrec
.rroriginalttl
= rr
->rroriginalttl
;
13686 while (*e
) e
= &(*e
)->next
;
13688 extra
->r
.DependentOn
= &sr
->RR_SRV
;
13690 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13691 extra
->r
.resrec
.name
->c
, DNSTypeName(extra
->r
.resrec
.rrtype
), extra
->r
.resrec
.rdlength
);
13693 status
= mDNS_Register_internal(m
, &extra
->r
);
13694 if (status
== mStatus_NoError
) *e
= extra
;
13700 mDNSexport mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
,
13701 mDNSRecordCallback MemFreeCallback
, void *Context
)
13703 ExtraResourceRecord
**e
;
13708 while (*e
&& *e
!= extra
) e
= &(*e
)->next
;
13711 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra
->r
.resrec
.name
->c
);
13712 status
= mStatus_BadReferenceErr
;
13716 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra
->r
.resrec
.name
->c
);
13717 extra
->r
.RecordCallback
= MemFreeCallback
;
13718 extra
->r
.RecordContext
= Context
;
13720 status
= mDNS_Deregister_internal(m
, &extra
->r
, mDNS_Dereg_normal
);
13726 mDNSexport mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
)
13728 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13729 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13730 domainlabel name1
, name2
;
13731 domainname type
, domain
;
13732 const domainname
*host
= sr
->RR_SRV
.AutoTarget
? mDNSNULL
: &sr
->RR_SRV
.resrec
.rdata
->u
.srv
.target
;
13733 ExtraResourceRecord
*extras
= sr
->Extras
;
13736 DeconstructServiceName(sr
->RR_SRV
.resrec
.name
, &name1
, &type
, &domain
);
13740 IncrementLabelSuffix(&name2
, mDNStrue
);
13744 if (SameDomainName(&domain
, &localdomain
))
13745 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type
.c
, name1
.c
, newname
->c
);
13746 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type
.c
, domain
.c
, name1
.c
, newname
->c
);
13748 // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13749 // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13750 if (sr
->RR_TXT
.NewRData
) CompleteRDataUpdate(m
, &sr
->RR_TXT
);
13751 err
= mDNS_RegisterService(m
, sr
, newname
, &type
, &domain
,
13752 host
, sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
,
13753 (sr
->RR_TXT
.resrec
.rdata
!= &sr
->RR_TXT
.rdatastorage
) ? sr
->RR_TXT
.resrec
.rdata
: mDNSNULL
,
13754 sr
->RR_TXT
.resrec
.rdata
->u
.txt
.c
, sr
->RR_TXT
.resrec
.rdlength
,
13755 sr
->SubTypes
, sr
->NumSubTypes
,
13756 sr
->RR_PTR
.resrec
.InterfaceID
, sr
->ServiceCallback
, sr
->ServiceContext
, sr
->flags
);
13758 // mDNS_RegisterService() just reset sr->Extras to NULL.
13759 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13760 // through the old list of extra records, and re-add them to our freshly created service registration
13761 while (!err
&& extras
)
13763 ExtraResourceRecord
*e
= extras
;
13764 extras
= extras
->next
;
13765 err
= mDNS_AddRecordToService(m
, sr
, e
, e
->r
.resrec
.rdata
, e
->r
.resrec
.rroriginalttl
, 0);
13771 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13772 // which may change the record list and/or question list.
13773 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13774 mDNSexport mStatus
mDNS_DeregisterService_drt(mDNS
*const m
, ServiceRecordSet
*sr
, mDNS_Dereg_type drt
)
13776 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13777 if (mDNSIPPortIsZero(sr
->RR_SRV
.resrec
.rdata
->u
.srv
.port
)) return(mDNS_DeregisterNoSuchService(m
, &sr
->RR_SRV
));
13779 if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
13781 debugf("Service set for %##s already deregistered", sr
->RR_SRV
.resrec
.name
->c
);
13782 return(mStatus_BadReferenceErr
);
13784 else if (sr
->RR_PTR
.resrec
.RecordType
== kDNSRecordTypeDeregistering
)
13786 LogInfo("Service set for %##s already in the process of deregistering", sr
->RR_SRV
.resrec
.name
->c
);
13787 // Avoid race condition:
13788 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13789 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13790 // If the client happens to deregister the service in the middle of that process, then
13791 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13792 // instead of incorrectly promoting it to mStatus_NameConflict.
13793 // This race condition is exposed particularly when the conformance test generates
13794 // a whole batch of simultaneous conflicts across a range of services all advertised
13795 // using the same system default name, and if we don't take this precaution then
13796 // we end up incrementing m->nicelabel multiple times instead of just once.
13797 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13798 sr
->Conflict
= mDNSfalse
;
13799 return(mStatus_NoError
);
13805 ExtraResourceRecord
*e
;
13809 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13810 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13811 mDNS_Deregister_internal(m
, &sr
->RR_SRV
, mDNS_Dereg_repeat
);
13812 mDNS_Deregister_internal(m
, &sr
->RR_TXT
, mDNS_Dereg_repeat
);
13813 mDNS_Deregister_internal(m
, &sr
->RR_ADV
, drt
);
13815 // We deregister all of the extra records, but we leave the sr->Extras list intact
13816 // in case the client wants to do a RenameAndReregister and reinstate the registration
13819 mDNS_Deregister_internal(m
, &e
->r
, mDNS_Dereg_repeat
);
13823 for (i
=0; i
<sr
->NumSubTypes
; i
++)
13824 mDNS_Deregister_internal(m
, &sr
->SubTypes
[i
], drt
);
13826 status
= mDNS_Deregister_internal(m
, &sr
->RR_PTR
, drt
);
13832 // Create a registration that asserts that no such service exists with this name.
13833 // This can be useful where there is a given function is available through several protocols.
13834 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13835 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13836 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13837 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13838 mDNSexport mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
13839 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
13840 const domainname
*const host
,
13841 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
, mDNSu32 flags
)
13843 AuthRecType artype
;
13845 artype
= setAuthRecType(InterfaceID
, flags
);
13847 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_SRV
, kHostNameTTL
, kDNSRecordTypeUnique
, artype
, Callback
, Context
);
13848 if (ConstructServiceName(&rr
->namestorage
, name
, type
, domain
) == mDNSNULL
) return(mStatus_BadParamErr
);
13849 rr
->resrec
.rdata
->u
.srv
.priority
= 0;
13850 rr
->resrec
.rdata
->u
.srv
.weight
= 0;
13851 rr
->resrec
.rdata
->u
.srv
.port
= zeroIPPort
;
13852 if (host
&& host
->c
[0]) AssignDomainName(&rr
->resrec
.rdata
->u
.srv
.target
, host
);
13853 else rr
->AutoTarget
= Target_AutoHost
;
13854 return(mDNS_Register(m
, rr
));
13857 mDNSexport mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
,
13858 mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
)
13860 AuthRecType artype
;
13862 if (InterfaceID
== mDNSInterface_LocalOnly
)
13863 artype
= AuthRecordLocalOnly
;
13864 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
13865 artype
= AuthRecordP2P
;
13867 artype
= AuthRecordAny
;
13868 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, kDNSType_PTR
, kStandardTTL
, kDNSRecordTypeShared
, artype
, mDNSNULL
, mDNSNULL
);
13869 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, mDNS_DomainTypeNames
[DomainType
])) return(mStatus_BadParamErr
);
13870 if (!MakeDomainNameFromDNSNameString(&rr
->resrec
.rdata
->u
.name
, domname
)) return(mStatus_BadParamErr
);
13871 return(mDNS_Register(m
, rr
));
13874 mDNSlocal mDNSBool
mDNS_IdUsedInResourceRecordsList(mDNS
* const m
, mDNSOpaque16 id
)
13877 for (r
= m
->ResourceRecords
; r
; r
=r
->next
) if (mDNSSameOpaque16(id
, r
->updateid
)) return mDNStrue
;
13881 mDNSlocal mDNSBool
mDNS_IdUsedInQuestionsList(mDNS
* const m
, mDNSOpaque16 id
)
13884 for (q
= m
->Questions
; q
; q
=q
->next
) if (mDNSSameOpaque16(id
, q
->TargetQID
)) return mDNStrue
;
13888 mDNSexport mDNSOpaque16
mDNS_NewMessageID(mDNS
* const m
)
13893 for (i
=0; i
<10; i
++)
13895 id
= mDNSOpaque16fromIntVal(1 + (mDNSu16
)mDNSRandom(0xFFFE));
13896 if (!mDNS_IdUsedInResourceRecordsList(m
, id
) && !mDNS_IdUsedInQuestionsList(m
, id
)) break;
13899 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id
));
13904 // ***************************************************************************
13905 #if COMPILER_LIKES_PRAGMA_MARK
13907 #pragma mark - Sleep Proxy Server
13910 mDNSlocal
void RestartARPProbing(mDNS
*const m
, AuthRecord
*const rr
)
13912 // If we see an ARP from a machine we think is sleeping, then either
13913 // (i) the machine has woken, or
13914 // (ii) it's just a stray old packet from before the machine slept
13915 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13916 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13917 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13918 // 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*
13919 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13920 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13922 rr
->resrec
.RecordType
= kDNSRecordTypeUnique
;
13923 rr
->ProbeCount
= DefaultProbeCountForTypeUnique
;
13924 rr
->ProbeRestartCount
++;
13926 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13927 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13928 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13929 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13930 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13931 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13932 if (rr
->AnnounceCount
== InitialAnnounceCount
&& m
->timenow
- rr
->LastAPTime
>= 0)
13933 InitializeLastAPTime(m
, rr
);
13936 rr
->AnnounceCount
= InitialAnnounceCount
;
13937 rr
->ThisAPInterval
= mDNSPlatformOneSecond
;
13938 rr
->LastAPTime
= m
->timenow
+ mDNSPlatformOneSecond
* 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13939 SetNextAnnounceProbeTime(m
, rr
);
13943 mDNSlocal
void mDNSCoreReceiveRawARP(mDNS
*const m
, const ARP_EthIP
*const arp
, const mDNSInterfaceID InterfaceID
)
13945 static const mDNSOpaque16 ARP_op_request
= { { 0, 1 } };
13947 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
13953 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13954 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13955 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13956 // The times we might need to react to an ARP Announcement are:
13957 // (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
13958 // (ii) if it's a conflicting Announcement from another host
13959 // -- and we check for these in Pass 2 below.
13960 if (mDNSSameOpaque16(arp
->op
, ARP_op_request
) && !mDNSSameIPv4Address(arp
->spa
, arp
->tpa
))
13962 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
13963 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
13964 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->tpa
))
13966 static const char msg1
[] = "ARP Req from owner -- re-probing";
13967 static const char msg2
[] = "Ignoring ARP Request from ";
13968 static const char msg3
[] = "Creating Local ARP Cache entry ";
13969 static const char msg4
[] = "Answering ARP Request from ";
13970 const char *const msg
= mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
13971 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
13972 mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
) ? msg3
: msg4
;
13973 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13974 intf
->ifname
, msg
, arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
,
13975 &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
13978 if ( rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
13979 RestartARPProbing(m
, rr
);
13981 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
13983 else if (msg
== msg3
)
13985 mDNSPlatformSetLocalAddressCacheEntry(&rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
13987 else if (msg
== msg4
)
13989 SendARP(m
, 2, rr
, (mDNSv4Addr
*)arp
->tpa
.b
, &arp
->sha
, (mDNSv4Addr
*)arp
->spa
.b
, &arp
->sha
);
13995 // 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.
13996 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13997 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13998 // 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.
13999 // If we see an apparently conflicting ARP, we check the sender hardware address:
14000 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
14001 // 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.
14002 if (mDNSSameEthAddress(&arp
->sha
, &intf
->MAC
))
14003 debugf("ARP from self for %.4a", arp
->tpa
.b
);
14006 if (!mDNSSameIPv4Address(arp
->spa
, zerov4Addr
))
14007 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14008 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14009 rr
->AddressProxy
.type
== mDNSAddrType_IPv4
&& mDNSSameIPv4Address(rr
->AddressProxy
.ip
.v4
, arp
->spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
14011 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
14013 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14014 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14018 RestartARPProbing(m
, rr
);
14019 if (mDNSSameEthAddress(&arp
->sha
, &rr
->WakeUp
.IMAC
))
14021 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf
->ifname
,
14022 mDNSSameIPv4Address(arp
->spa
, arp
->tpa
) ? "Announcement " : mDNSSameOpaque16(arp
->op
, ARP_op_request
) ? "Request " : "Response ",
14023 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, ARDisplayString(m
, rr
));
14027 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14028 arp
->sha
.b
, arp
->spa
.b
, arp
->tpa
.b
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14029 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14039 // Option 1 is Source Link Layer Address Option
14040 // Option 2 is Target Link Layer Address Option
14041 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14043 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14044 while (options < end)
14046 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14047 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14048 options += options[1] * 8;
14054 mDNSlocal
void mDNSCoreReceiveRawND(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSv6Addr
*spa
,
14055 const IPv6NDP
*const ndp
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
14058 NetworkInterfaceInfo
*intf
= FirstInterfaceForID(m
, InterfaceID
);
14063 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14064 if (ndp
->type
== NDP_Sol
)
14066 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14068 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14069 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14070 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, ndp
->target
))
14072 static const char msg1
[] = "NDP Req from owner -- re-probing";
14073 static const char msg2
[] = "Ignoring NDP Request from ";
14074 static const char msg3
[] = "Creating Local NDP Cache entry ";
14075 static const char msg4
[] = "Answering NDP Request from ";
14076 static const char msg5
[] = "Answering NDP Probe from ";
14077 const char *const msg
= mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
) ? msg1
:
14078 (rr
->AnnounceCount
== InitialAnnounceCount
) ? msg2
:
14079 mDNSSameEthAddress(sha
, &intf
->MAC
) ? msg3
:
14080 mDNSIPv6AddressIsZero(*spa
) ? msg4
: msg5
;
14081 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14082 intf
->ifname
, msg
, sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14085 if (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
)
14086 RestartARPProbing(m
, rr
);
14088 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m
,rr
));
14090 else if (msg
== msg3
)
14091 mDNSPlatformSetLocalAddressCacheEntry(&rr
->AddressProxy
, &rr
->WakeUp
.IMAC
, InterfaceID
);
14092 else if (msg
== msg4
)
14093 SendNDP(m
, NDP_Adv
, NDP_Solicited
, rr
, &ndp
->target
, mDNSNULL
, spa
, sha
);
14094 else if (msg
== msg5
)
14095 SendNDP(m
, NDP_Adv
, 0, rr
, &ndp
->target
, mDNSNULL
, &AllHosts_v6
, &AllHosts_v6_Eth
);
14099 // 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.
14100 if (mDNSSameEthAddress(sha
, &intf
->MAC
))
14101 debugf("NDP from self for %.16a", &ndp
->target
);
14104 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14105 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14106 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14107 // Hence it is the NDP target address we care about, not the actual packet source address.
14108 if (ndp
->type
== NDP_Adv
) spa
= &ndp
->target
;
14109 if (!mDNSSameIPv6Address(*spa
, zerov6Addr
))
14110 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14111 if (rr
->resrec
.InterfaceID
== InterfaceID
&& rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14112 rr
->AddressProxy
.type
== mDNSAddrType_IPv6
&& mDNSSameIPv6Address(rr
->AddressProxy
.ip
.v6
, *spa
) && (rr
->ProbeRestartCount
< MAX_PROBE_RESTARTS
))
14114 if (mDNSSameEthAddress(&zeroEthAddr
, &rr
->WakeUp
.HMAC
))
14116 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14117 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14121 RestartARPProbing(m
, rr
);
14122 if (mDNSSameEthAddress(sha
, &rr
->WakeUp
.IMAC
))
14124 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf
->ifname
,
14125 ndp
->type
== NDP_Sol
? "Solicitation " : "Advertisement", sha
, spa
, &ndp
->target
, ARDisplayString(m
, rr
));
14129 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf
->ifname
,
14130 sha
, spa
, &ndp
->target
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, rr
));
14131 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14140 mDNSlocal
void mDNSCoreReceiveRawTransportPacket(mDNS
*const m
, const mDNSEthAddr
*const sha
, const mDNSAddr
*const src
, const mDNSAddr
*const dst
, const mDNSu8 protocol
,
14141 const mDNSu8
*const p
, const TransportLayerPacket
*const t
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
, const mDNSu16 len
)
14143 const mDNSIPPort port
= (protocol
== 0x06) ? t
->tcp
.dst
: (protocol
== 0x11) ? t
->udp
.dst
: zeroIPPort
;
14144 mDNSBool wake
= mDNSfalse
;
14145 mDNSBool kaWake
= mDNSfalse
;
14149 #define XX wake ? "Received" : "Ignoring", end-p
14150 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end
-p
, src
, dst
);
14156 #define TH_FIN 0x01
14157 #define TH_SYN 0x02
14158 #define TH_RST 0x04
14159 #define TH_ACK 0x10
14161 kr
= mDNS_MatchKeepaliveInfo(m
, dst
, src
, port
, t
->tcp
.src
, &seq
, &ack
);
14164 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
));
14166 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14167 // (b) packet that contains new data and acks a sequence number higher than the one
14168 // we have been sending in the keepalive
14170 wake
= ((t
->tcp
.flags
& TH_RST
) || (t
->tcp
.flags
& TH_FIN
)) ;
14174 mDNSu32 pseq
, pack
;
14175 mDNSBool data
= mDNSfalse
;
14178 // Convert to host order
14179 ptr
= (mDNSu8
*)&seq
;
14180 seq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14182 ptr
= (mDNSu8
*)&ack
;
14183 ack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14186 ptr
= (mDNSu8
*)&pseq
;
14187 pseq
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14190 ptr
= (mDNSu8
*)&pack
;
14191 pack
= ptr
[0] << 24 | ptr
[1] << 16 | ptr
[2] << 8 | ptr
[3];
14193 // If the other side is acking one more than our sequence number (keepalive is one
14194 // less than the last valid sequence sent) and it's sequence is more than what we
14196 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14197 tcphlen
= ((t
->tcp
.offset
>> 4) * 4);
14198 if (end
- ((mDNSu8
*)t
+ tcphlen
) > 0) data
= mDNStrue
;
14199 wake
= ((int)(pack
- seq
) > 0) && ((int)(pseq
- ack
) >= 0) && data
;
14201 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14202 if ((t
->tcp
.flags
& TH_ACK
) && (data
== mDNSfalse
) &&
14203 ((int)(ack
- pseq
) == 1))
14206 mDNS_SendKeepaliveACK(m
, kr
);
14208 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14209 end
, tcphlen
, end
- ((mDNSu8
*)t
+ tcphlen
), pack
, seq
, pseq
, ack
, wake
);
14211 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t
->tcp
.flags
); }
14217 // (a) RST is not set, AND
14218 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14219 wake
= (!(t
->tcp
.flags
& TH_RST
) && (t
->tcp
.flags
& (TH_FIN
|TH_SYN
)) != TH_FIN
);
14221 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14222 // except for ssh connections, where we'll wake for plain data packets too
14223 if (!mDNSSameIPPort(port
, SSHPort
) && !(t
->tcp
.flags
& 2)) wake
= mDNSfalse
;
14225 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX
,
14226 src
, mDNSVal16(t
->tcp
.src
), dst
, mDNSVal16(port
),
14227 (t
->tcp
.flags
& 2) ? " SYN" : "",
14228 (t
->tcp
.flags
& 1) ? " FIN" : "",
14229 (t
->tcp
.flags
& 4) ? " RST" : "");
14235 #define ARD_AsNumber 3283
14236 static const mDNSIPPort ARD
= { { ARD_AsNumber
>> 8, ARD_AsNumber
& 0xFF } };
14237 const mDNSu16 udplen
= (mDNSu16
)((mDNSu16
)t
->bytes
[4] << 8 | t
->bytes
[5]); // Length *including* 8-byte UDP header
14238 if (udplen
>= sizeof(UDPHeader
))
14240 const mDNSu16 datalen
= udplen
- sizeof(UDPHeader
);
14243 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14244 if (mDNSSameIPPort(port
, IPSECPort
))
14246 // Specifically ignore NAT keepalive packets
14247 if (datalen
== 1 && end
>= &t
->bytes
[9] && t
->bytes
[8] == 0xFF) wake
= mDNSfalse
;
14250 // Skip over the Non-ESP Marker if present
14251 const mDNSBool NonESP
= (end
>= &t
->bytes
[12] && t
->bytes
[8] == 0 && t
->bytes
[9] == 0 && t
->bytes
[10] == 0 && t
->bytes
[11] == 0);
14252 const IKEHeader
*const ike
= (IKEHeader
*)(t
+ (NonESP
? 12 : 8));
14253 const mDNSu16 ikelen
= datalen
- (NonESP
? 4 : 0);
14254 if (ikelen
>= sizeof(IKEHeader
) && end
>= ((mDNSu8
*)ike
) + sizeof(IKEHeader
))
14255 if ((ike
->Version
& 0x10) == 0x10)
14257 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14258 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14259 if (ike
->ExchangeType
== 5 || ike
->ExchangeType
== 34) wake
= mDNSfalse
;
14260 LogSPS("%s %d-byte IKE ExchangeType %d", XX
, ike
->ExchangeType
);
14265 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14266 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14267 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14268 // UDP header (8 bytes)
14269 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14270 if (mDNSSameIPPort(port
, ARD
)) wake
= (datalen
>= 110 && end
>= &t
->bytes
[10] && t
->bytes
[8] == 0x13 && t
->bytes
[9] == 0x88);
14272 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX
, src
, mDNSVal16(t
->udp
.src
), dst
, mDNSVal16(port
));
14277 case 0x3A: if (&t
->bytes
[len
] <= end
)
14279 mDNSu16 checksum
= IPv6CheckSum(&src
->ip
.v6
, &dst
->ip
.v6
, protocol
, t
->bytes
, len
);
14280 if (!checksum
) mDNSCoreReceiveRawND(m
, sha
, &src
->ip
.v6
, &t
->ndp
, &t
->bytes
[len
], InterfaceID
);
14281 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum
, t
->bytes
[2], t
->bytes
[3], src
, dst
);
14285 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end
-p
, protocol
, src
, dst
);
14291 AuthRecord
*rr
, *r2
;
14294 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
14295 if (rr
->resrec
.InterfaceID
== InterfaceID
&&
14296 rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14297 rr
->AddressProxy
.type
&& mDNSSameAddress(&rr
->AddressProxy
, dst
))
14299 const mDNSu8
*const tp
= (protocol
== 6) ? (const mDNSu8
*)"\x4_tcp" : (const mDNSu8
*)"\x4_udp";
14300 for (r2
= m
->ResourceRecords
; r2
; r2
=r2
->next
)
14301 if (r2
->resrec
.InterfaceID
== InterfaceID
&& mDNSSameEthAddress(&r2
->WakeUp
.HMAC
, &rr
->WakeUp
.HMAC
) &&
14302 r2
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
&&
14303 r2
->resrec
.rrtype
== kDNSType_SRV
&& mDNSSameIPPort(r2
->resrec
.rdata
->u
.srv
.port
, port
) &&
14304 SameDomainLabel(ThirdLabel(r2
->resrec
.name
)->c
, tp
))
14306 if (!r2
&& mDNSSameIPPort(port
, IPSECPort
)) r2
= rr
; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14307 if (!r2
&& kaWake
) r2
= rr
; // So that we wake for keepalive packets, even without a matching SRV record
14310 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14311 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, &rr
->WakeUp
.IMAC
, ARDisplayString(m
, r2
));
14312 ScheduleWakeup(m
, rr
->resrec
.InterfaceID
, &rr
->WakeUp
.HMAC
);
14315 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14316 InterfaceNameForID(m
, rr
->resrec
.InterfaceID
), dst
, &rr
->WakeUp
.HMAC
, tp
, mDNSVal16(port
));
14322 mDNSexport
void mDNSCoreReceiveRawPacket(mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
)
14324 static const mDNSOpaque16 Ethertype_ARP
= { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14325 static const mDNSOpaque16 Ethertype_IPv4
= { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14326 static const mDNSOpaque16 Ethertype_IPv6
= { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14327 static const mDNSOpaque16 ARP_hrd_eth
= { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14328 static const mDNSOpaque16 ARP_pro_ip
= { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14330 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14331 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14332 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14333 // since it points to a an address 14 bytes before pkt.
14334 const EthernetHeader
*const eth
= (const EthernetHeader
*)p
;
14335 const NetworkLayerPacket
*const pkt
= (const NetworkLayerPacket
*)(eth
+1);
14337 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14339 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14340 if (end
>= p
+42 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_ARP
) && mDNSSameOpaque16(pkt
->arp
.hrd
, ARP_hrd_eth
) && mDNSSameOpaque16(pkt
->arp
.pro
, ARP_pro_ip
))
14341 mDNSCoreReceiveRawARP(m
, &pkt
->arp
, InterfaceID
);
14342 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14343 else if (end
>= p
+34 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv4
) && (pkt
->v4
.flagsfrags
.b
[0] & 0x1F) == 0 && pkt
->v4
.flagsfrags
.b
[1] == 0)
14345 const mDNSu8
*const trans
= p
+ 14 + (pkt
->v4
.vlen
& 0xF) * 4;
14346 const mDNSu8
* transEnd
= p
+ 14 + mDNSVal16(pkt
->v4
.totlen
);
14347 if (transEnd
> end
) transEnd
= end
;
14348 debugf("Got IPv4 %02X from %.4a to %.4a", pkt
->v4
.protocol
, &pkt
->v4
.src
.b
, &pkt
->v4
.dst
.b
);
14349 src
.type
= mDNSAddrType_IPv4
; src
.ip
.v4
= pkt
->v4
.src
;
14350 dst
.type
= mDNSAddrType_IPv4
; dst
.ip
.v4
= pkt
->v4
.dst
;
14351 if (transEnd
>= trans
+ RequiredCapLen(pkt
->v4
.protocol
))
14352 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v4
.protocol
, p
, (TransportLayerPacket
*)trans
, transEnd
, InterfaceID
, 0);
14354 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14355 else if (end
>= p
+54 && mDNSSameOpaque16(eth
->ethertype
, Ethertype_IPv6
))
14357 const mDNSu8
*const trans
= p
+ 54;
14358 debugf("Got IPv6 %02X from %.16a to %.16a", pkt
->v6
.pro
, &pkt
->v6
.src
.b
, &pkt
->v6
.dst
.b
);
14359 src
.type
= mDNSAddrType_IPv6
; src
.ip
.v6
= pkt
->v6
.src
;
14360 dst
.type
= mDNSAddrType_IPv6
; dst
.ip
.v6
= pkt
->v6
.dst
;
14361 if (end
>= trans
+ RequiredCapLen(pkt
->v6
.pro
))
14362 mDNSCoreReceiveRawTransportPacket(m
, ð
->src
, &src
, &dst
, pkt
->v6
.pro
, p
, (TransportLayerPacket
*)trans
, end
, InterfaceID
,
14363 (mDNSu16
)pkt
->bytes
[4] << 8 | pkt
->bytes
[5]);
14367 mDNSlocal
void ConstructSleepProxyServerName(mDNS
*const m
, domainlabel
*name
)
14369 name
->c
[0] = (mDNSu8
)mDNS_snprintf((char*)name
->c
+1, 62, "%d-%d-%d-%d.%d %#s",
14370 m
->SPSType
, m
->SPSPortability
, m
->SPSMarginalPower
, m
->SPSTotalPower
, m
->SPSFeatureFlags
, &m
->nicelabel
);
14373 #ifndef SPC_DISABLED
14374 mDNSlocal
void SleepProxyServerCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
14376 if (result
== mStatus_NameConflict
)
14377 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
14378 else if (result
== mStatus_MemFree
)
14384 m
->SPSState
= (mDNSu8
)(m
->SPSSocket
!= mDNSNULL
);
14388 ConstructSleepProxyServerName(m
, &name
);
14389 mDNS_RegisterService(m
, srs
,
14390 &name
, &SleepProxyServiceType
, &localdomain
,
14391 mDNSNULL
, m
->SPSSocket
->port
, // Host, port
14393 (mDNSu8
*)"", 1, // TXT data, length
14394 mDNSNULL
, 0, // Subtypes (none)
14395 mDNSInterface_Any
, // Interface ID
14396 SleepProxyServerCallback
, mDNSNULL
, 0); // Callback, context, flags
14398 LogSPS("Sleep Proxy Server %#s %s", srs
->RR_SRV
.resrec
.name
->c
, m
->SPSState
? "started" : "stopped");
14404 // Called with lock held
14405 mDNSexport
void mDNSCoreBeSleepProxyServer_internal(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
, mDNSu8 features
)
14407 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14408 mDNS_DropLockBeforeCallback();
14410 // If turning off SPS, close our socket
14411 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14412 if (!sps
&& m
->SPSSocket
) { mDNSPlatformUDPClose(m
->SPSSocket
); m
->SPSSocket
= mDNSNULL
; }
14414 // If turning off, or changing type, deregister old name
14415 #ifndef SPC_DISABLED
14416 if (m
->SPSState
== 1 && sps
!= m
->SPSType
)
14417 { m
->SPSState
= 2; mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, sps
? mDNS_Dereg_rapid
: mDNS_Dereg_normal
); }
14418 #endif // SPC_DISABLED
14420 // Record our new SPS parameters
14422 m
->SPSPortability
= port
;
14423 m
->SPSMarginalPower
= marginalpower
;
14424 m
->SPSTotalPower
= totpower
;
14425 m
->SPSFeatureFlags
= features
;
14426 // If turning on, open socket and advertise service
14431 m
->SPSSocket
= mDNSPlatformUDPSocket(zeroIPPort
);
14432 if (!m
->SPSSocket
) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail
; }
14434 #ifndef SPC_DISABLED
14435 if (m
->SPSState
== 0) SleepProxyServerCallback(m
, &m
->SPSRecords
, mStatus_MemFree
);
14436 #endif // SPC_DISABLED
14438 else if (m
->SPSState
)
14440 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m
->SPSState
);
14441 m
->NextScheduledSPS
= m
->timenow
;
14444 mDNS_ReclaimLockAfterCallback();
14447 // ***************************************************************************
14448 #if COMPILER_LIKES_PRAGMA_MARK
14450 #pragma mark - Startup and Shutdown
14453 mDNSlocal
void mDNS_GrowCache_internal(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14455 if (storage
&& numrecords
)
14458 debugf("Adding cache storage for %d more records (%d bytes)", numrecords
, numrecords
*sizeof(CacheEntity
));
14459 for (i
=0; i
<numrecords
; i
++) storage
[i
].next
= &storage
[i
+1];
14460 storage
[numrecords
-1].next
= m
->rrcache_free
;
14461 m
->rrcache_free
= storage
;
14462 m
->rrcache_size
+= numrecords
;
14466 mDNSexport
void mDNS_GrowCache(mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
)
14469 mDNS_GrowCache_internal(m
, storage
, numrecords
);
14473 mDNSlocal mStatus
mDNS_InitStorage(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14474 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14475 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14481 if (!rrcachestorage
) rrcachesize
= 0;
14484 m
->NetworkChanged
= 0;
14485 m
->CanReceiveUnicastOn5353
= mDNSfalse
; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14486 m
->AdvertiseLocalAddresses
= AdvertiseLocalAddresses
;
14487 m
->DivertMulticastAdvertisements
= mDNSfalse
;
14488 m
->mDNSPlatformStatus
= mStatus_Waiting
;
14489 m
->UnicastPort4
= zeroIPPort
;
14490 m
->UnicastPort6
= zeroIPPort
;
14491 m
->PrimaryMAC
= zeroEthAddr
;
14492 m
->MainCallback
= Callback
;
14493 m
->MainContext
= Context
;
14494 m
->rec
.r
.resrec
.RecordType
= 0;
14496 // For debugging: To catch and report locking failures
14498 m
->mDNS_reentrancy
= 0;
14499 m
->ShutdownTime
= 0;
14500 m
->lock_rrcache
= 0;
14501 m
->lock_Questions
= 0;
14502 m
->lock_Records
= 0;
14504 // Task Scheduling variables
14505 result
= mDNSPlatformTimeInit();
14506 if (result
!= mStatus_NoError
) return(result
);
14507 m
->timenow_adjust
= (mDNSs32
)mDNSRandom(0xFFFFFFFF);
14508 timenow
= mDNS_TimeNow_NoLock(m
);
14510 m
->timenow
= 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14511 m
->timenow_last
= timenow
;
14512 m
->NextScheduledEvent
= timenow
;
14513 m
->SuppressSending
= timenow
;
14514 m
->NextCacheCheck
= timenow
+ FutureTime
;
14515 m
->NextScheduledQuery
= timenow
+ FutureTime
;
14516 m
->NextScheduledProbe
= timenow
+ FutureTime
;
14517 m
->NextScheduledResponse
= timenow
+ FutureTime
;
14518 m
->NextScheduledNATOp
= timenow
+ FutureTime
;
14519 m
->NextScheduledSPS
= timenow
+ FutureTime
;
14520 m
->NextScheduledKA
= timenow
+ FutureTime
;
14521 m
->NextScheduledStopTime
= timenow
+ FutureTime
;
14522 m
->NextBLEServiceTime
= 0; // zero indicates inactive
14524 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14525 m
->NextBonjourDisableTime
= 0; // Timer active when non zero.
14526 m
->BonjourEnabled
= 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14529 m
->RandomQueryDelay
= 0;
14530 m
->RandomReconfirmDelay
= 0;
14533 m
->LocalRemoveEvents
= mDNSfalse
;
14534 m
->SleepState
= SleepState_Awake
;
14535 m
->SleepSeqNum
= 0;
14536 m
->SystemWakeOnLANEnabled
= mDNSfalse
;
14537 m
->AnnounceOwner
= NonZeroTime(timenow
+ 60 * mDNSPlatformOneSecond
);
14541 #if APPLE_OSX_mDNSResponder
14542 m
->UnicastPacketsSent
= 0;
14543 m
->MulticastPacketsSent
= 0;
14544 m
->RemoteSubnet
= 0;
14545 #endif // APPLE_OSX_mDNSResponder
14547 // These fields only required for mDNS Searcher...
14548 m
->Questions
= mDNSNULL
;
14549 m
->NewQuestions
= mDNSNULL
;
14550 m
->CurrentQuestion
= mDNSNULL
;
14551 m
->LocalOnlyQuestions
= mDNSNULL
;
14552 m
->NewLocalOnlyQuestions
= mDNSNULL
;
14553 m
->RestartQuestion
= mDNSNULL
;
14554 m
->rrcache_size
= 0;
14555 m
->rrcache_totalused
= 0;
14556 m
->rrcache_active
= 0;
14557 m
->rrcache_report
= 10;
14558 m
->rrcache_free
= mDNSNULL
;
14560 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
14562 m
->rrcache_hash
[slot
] = mDNSNULL
;
14563 m
->rrcache_nextcheck
[slot
] = timenow
+ FutureTime
;;
14566 mDNS_GrowCache_internal(m
, rrcachestorage
, rrcachesize
);
14567 m
->rrauth
.rrauth_free
= mDNSNULL
;
14569 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
14570 m
->rrauth
.rrauth_hash
[slot
] = mDNSNULL
;
14572 // Fields below only required for mDNS Responder...
14573 m
->hostlabel
.c
[0] = 0;
14574 m
->nicelabel
.c
[0] = 0;
14575 m
->MulticastHostname
.c
[0] = 0;
14576 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14577 m
->RandomizedHostname
.c
[0] = 0;
14579 m
->HIHardware
.c
[0] = 0;
14580 m
->HISoftware
.c
[0] = 0;
14581 m
->ResourceRecords
= mDNSNULL
;
14582 m
->DuplicateRecords
= mDNSNULL
;
14583 m
->NewLocalRecords
= mDNSNULL
;
14584 m
->NewLocalOnlyRecords
= mDNSfalse
;
14585 m
->CurrentRecord
= mDNSNULL
;
14586 m
->HostInterfaces
= mDNSNULL
;
14587 m
->ProbeFailTime
= 0;
14588 m
->NumFailedProbes
= 0;
14589 m
->SuppressProbes
= 0;
14591 #ifndef UNICAST_DISABLED
14592 m
->NextuDNSEvent
= timenow
+ FutureTime
;
14593 m
->NextSRVUpdate
= timenow
+ FutureTime
;
14595 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14596 m
->DNSServers
= mDNSNULL
;
14599 m
->Router
= zeroAddr
;
14600 m
->AdvertisedV4
= zeroAddr
;
14601 m
->AdvertisedV6
= zeroAddr
;
14603 m
->AuthInfoList
= mDNSNULL
;
14605 m
->ReverseMap
.ThisQInterval
= -1;
14606 m
->StaticHostname
.c
[0] = 0;
14608 m
->Hostnames
= mDNSNULL
;
14610 m
->WABBrowseQueriesCount
= 0;
14611 m
->WABLBrowseQueriesCount
= 0;
14612 m
->WABRegQueriesCount
= 0;
14613 m
->AutoTargetServices
= 0;
14615 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14616 m
->NumAllInterfaceRecords
= 0;
14617 m
->NumAllInterfaceQuestions
= 0;
14619 // NAT traversal fields
14620 m
->LLQNAT
.clientCallback
= mDNSNULL
;
14621 m
->LLQNAT
.clientContext
= mDNSNULL
;
14622 m
->NATTraversals
= mDNSNULL
;
14623 m
->CurrentNATTraversal
= mDNSNULL
;
14624 m
->retryIntervalGetAddr
= 0; // delta between time sent and retry
14625 m
->retryGetAddr
= timenow
+ FutureTime
; // absolute time when we retry
14626 m
->ExtAddress
= zerov4Addr
;
14627 m
->PCPNonce
[0] = mDNSRandom(-1);
14628 m
->PCPNonce
[1] = mDNSRandom(-1);
14629 m
->PCPNonce
[2] = mDNSRandom(-1);
14631 m
->NATMcastRecvskt
= mDNSNULL
;
14632 m
->LastNATupseconds
= 0;
14633 m
->LastNATReplyLocalTime
= timenow
;
14634 m
->LastNATMapResultCode
= NATErr_None
;
14636 m
->UPnPInterfaceID
= 0;
14637 m
->SSDPSocket
= mDNSNULL
;
14638 m
->SSDPWANPPPConnection
= mDNSfalse
;
14639 m
->UPnPRouterPort
= zeroIPPort
;
14640 m
->UPnPSOAPPort
= zeroIPPort
;
14641 m
->UPnPRouterURL
= mDNSNULL
;
14642 m
->UPnPWANPPPConnection
= mDNSfalse
;
14643 m
->UPnPSOAPURL
= mDNSNULL
;
14644 m
->UPnPRouterAddressString
= mDNSNULL
;
14645 m
->UPnPSOAPAddressString
= mDNSNULL
;
14647 m
->SPSPortability
= 0;
14648 m
->SPSMarginalPower
= 0;
14649 m
->SPSTotalPower
= 0;
14650 m
->SPSFeatureFlags
= 0;
14652 m
->SPSProxyListChanged
= mDNSNULL
;
14653 m
->SPSSocket
= mDNSNULL
;
14654 m
->SPSBrowseCallback
= mDNSNULL
;
14655 m
->ProxyRecords
= 0;
14657 m
->DNSPushServers
= mDNSNULL
;
14658 m
->DNSPushZones
= mDNSNULL
;
14661 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14662 if (WCFConnectionNew
)
14664 m
->WCF
= WCFConnectionNew();
14665 if (!m
->WCF
) { LogMsg("WCFConnectionNew failed"); return -1; }
14669 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
14670 result
= init_and_load_trust_anchors();
14671 if (result
!= mStatus_NoError
) return(result
);
14677 mDNSexport mStatus
mDNS_Init(mDNS
*const m
, mDNS_PlatformSupport
*const p
,
14678 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
14679 mDNSBool AdvertiseLocalAddresses
, mDNSCallback
*Callback
, void *Context
)
14681 mStatus result
= mDNS_InitStorage(m
, p
, rrcachestorage
, rrcachesize
, AdvertiseLocalAddresses
, Callback
, Context
);
14682 if (result
!= mStatus_NoError
)
14685 #if MDNS_MALLOC_DEBUGGING
14686 static mDNSListValidator lv
;
14687 mDNSPlatformAddListValidator(&lv
, mDNS_ValidateLists
, "mDNS_ValidateLists", m
);
14689 result
= mDNSPlatformInit(m
);
14691 #ifndef UNICAST_DISABLED
14692 // It's better to do this *after* the platform layer has set up the
14693 // interface list and security credentials
14694 uDNS_SetupDNSConfig(m
); // Get initial DNS configuration
14700 mDNSexport
void mDNS_ConfigChanged(mDNS
*const m
)
14702 if (m
->SPSState
== 1)
14704 domainlabel name
, newname
;
14705 #ifndef SPC_DISABLED
14706 domainname type
, domain
;
14707 DeconstructServiceName(m
->SPSRecords
.RR_SRV
.resrec
.name
, &name
, &type
, &domain
);
14708 #endif // SPC_DISABLED
14709 ConstructSleepProxyServerName(m
, &newname
);
14710 if (!SameDomainLabelCS(name
.c
, newname
.c
))
14712 LogSPS("Renaming SPS from “%#s” to “%#s”", name
.c
, newname
.c
);
14713 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14714 // it will reregister the service under the new name
14716 #ifndef SPC_DISABLED
14717 mDNS_DeregisterService_drt(m
, &m
->SPSRecords
, mDNS_Dereg_rapid
);
14718 #endif // SPC_DISABLED
14722 if (m
->MainCallback
)
14723 m
->MainCallback(m
, mStatus_ConfigChanged
);
14726 mDNSlocal
void DynDNSHostNameCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
14729 debugf("NameStatusCallback: result %d for registration of name %##s", result
, rr
->resrec
.name
->c
);
14730 mDNSPlatformDynDNSHostNameStatusChanged(rr
->resrec
.name
, result
);
14733 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14734 mDNSlocal
void PurgeOrReconfirmCacheRecord(mDNS
*const m
, CacheRecord
*cr
)
14736 mDNSBool purge
= cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
||
14737 cr
->resrec
.rrtype
== kDNSType_A
||
14738 cr
->resrec
.rrtype
== kDNSType_AAAA
||
14739 cr
->resrec
.rrtype
== kDNSType_SRV
||
14740 cr
->resrec
.rrtype
== kDNSType_CNAME
;
14742 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14743 purge
? "purging" : "reconfirming",
14744 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
,
14745 cr
->resrec
.rDNSServer
? mDNSVal16(cr
->resrec
.rDNSServer
->port
) : -1,
14746 cr
->resrec
.rDNSServer
? cr
->resrec
.rDNSServer
->domain
.c
: mDNSNULL
, CRDisplayString(m
, cr
));
14750 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14751 mDNS_PurgeCacheResourceRecord(m
, cr
);
14755 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m
, cr
), cr
->resrec
.RecordType
);
14756 mDNS_Reconfirm_internal(m
, cr
, kDefaultReconfirmTimeForNoAnswer
);
14761 mDNSlocal
void mDNS_PurgeBeforeResolve(mDNS
*const m
, DNSQuestion
*q
)
14763 CacheGroup
*const cg
= CacheGroupForName(m
, q
->qnamehash
, &q
->qname
);
14765 for (rp
= cg
? cg
->members
: mDNSNULL
; rp
; rp
= rp
->next
)
14767 if (SameNameCacheRecordAnswersQuestion(rp
, q
))
14769 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m
, rp
));
14770 mDNS_PurgeCacheResourceRecord(m
, rp
);
14775 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14776 mDNSexport
void DNSServerChangeForQuestion(mDNS
*const m
, DNSQuestion
*q
, DNSServer
*new)
14782 if (q
->DuplicateOf
)
14783 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q
->qname
.c
);
14785 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14786 // of events for all of them are consistent. Duplicates for a question are always inserted
14787 // after in the list.
14788 q
->qDNSServer
= new;
14789 for (qptr
= q
->next
; qptr
; qptr
= qptr
->next
)
14791 if (qptr
->DuplicateOf
== q
) { qptr
->validDNSServers
= q
->validDNSServers
; qptr
->qDNSServer
= new; }
14796 mDNSlocal
void SetConfigState(mDNS
*const m
, mDNSBool
delete)
14799 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14805 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14806 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14808 ptr
->penaltyTime
= 0;
14809 ptr
->flags
|= DNSServerFlag_Delete
;
14810 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14811 if (ptr
->flags
& DNSServerFlag_Unreachable
)
14812 NumUnreachableDNSServers
--;
14816 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14817 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14819 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14820 mr
->flags
|= McastResolver_FlagDelete
;
14824 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14825 for (ptr
= m
->DNSServers
; ptr
; ptr
= ptr
->next
)
14827 ptr
->penaltyTime
= 0;
14828 ptr
->flags
&= ~DNSServerFlag_Delete
;
14829 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14830 if (ptr
->flags
& DNSServerFlag_Unreachable
)
14831 NumUnreachableDNSServers
++;
14835 for (mr
= m
->McastResolvers
; mr
; mr
= mr
->next
)
14836 mr
->flags
&= ~McastResolver_FlagDelete
;
14840 mDNSlocal
void SetDynDNSHostNameIfChanged(mDNS
*const m
, domainname
*const fqdn
)
14842 // Did our FQDN change?
14843 if (!SameDomainName(fqdn
, &m
->FQDN
))
14845 if (m
->FQDN
.c
[0]) mDNS_RemoveDynDNSHostName(m
, &m
->FQDN
);
14847 AssignDomainName(&m
->FQDN
, fqdn
);
14851 mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1);
14852 mDNS_AddDynDNSHostName(m
, &m
->FQDN
, DynDNSHostNameCallback
, mDNSNULL
);
14857 // Even though this is called “Setup” it is not called just once at startup.
14858 // It’s actually called multiple times, every time there’s a configuration change.
14859 mDNSexport mStatus
uDNS_SetupDNSConfig(mDNS
*const m
)
14861 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14866 mDNSAddr v4
, v6
, r
;
14868 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14869 DNSServer
*ptr
, **p
= &m
->DNSServers
;
14870 const DNSServer
*oldServers
= m
->DNSServers
;
14873 McastResolver
*mr
, **mres
= &m
->McastResolvers
;
14874 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14875 DNSPushNotificationServer
**psp
;
14878 debugf("uDNS_SetupDNSConfig: entry");
14880 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14881 uDNS_SetupWABQueries(m
);
14885 // We need to first mark all the entries to be deleted. If the configuration changed, then
14886 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14888 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14889 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14890 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14891 // for the dns configuration change notification.
14892 SetConfigState(m
, mDNStrue
);
14893 if (!mDNSPlatformSetDNSConfig(mDNStrue
, mDNSfalse
, &fqdn
, mDNSNULL
, mDNSNULL
, mDNStrue
))
14895 SetDynDNSHostNameIfChanged(m
, &fqdn
);
14896 SetConfigState(m
, mDNSfalse
);
14898 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14899 return mStatus_NoError
;
14902 // For now, we just delete the mcast resolvers. We don't deal with cache or
14903 // questions here. Neither question nor cache point to mcast resolvers. Questions
14904 // do inherit the timeout values from mcast resolvers. But we don't bother
14905 // affecting them as they never change.
14908 if (((*mres
)->flags
& McastResolver_FlagDelete
) != 0)
14911 *mres
= (*mres
)->next
;
14912 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr
, mr
->domain
.c
);
14913 mDNSPlatformMemFree(mr
);
14917 (*mres
)->flags
&= ~McastResolver_FlagNew
;
14918 mres
= &(*mres
)->next
;
14922 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14923 Querier_ProcessDNSServiceChanges();
14925 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14927 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14928 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14929 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14930 // DNSServers and flush the cache.
14932 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14933 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14934 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14935 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14936 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14937 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14938 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14939 // the same resGroupID.
14941 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14942 // of the old followed by ADD of the new records.
14944 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14945 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14946 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14948 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14949 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14950 // non-scoped question and vice versa.
14952 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14953 DNS64RestartQuestions(m
);
14956 // First, restart questions whose suppression status will change. The suppression status of each question in a given
14957 // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14958 // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14959 // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14960 // suppressed (or non-suppressed).
14961 for (q
= m
->Questions
; q
; q
= q
->next
)
14964 const DNSServer
*t
;
14965 mDNSBool oldSuppressed
;
14967 if (mDNSOpaque16IsZero(q
->TargetQID
)) continue;
14969 SetValidDNSServers(m
, q
);
14970 q
->triedAllServersOnce
= mDNSfalse
;
14971 s
= GetServerForQuestion(m
, q
);
14975 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
14976 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR
":%d (" PRI_DM_NAME
") to "
14977 PRI_IP_ADDR
":%d (" PRI_DM_NAME
") for question " PRI_DM_NAME
" (" PUB_S
") (scope:%p)",
14978 q
->request_id
, mDNSVal16(q
->TargetQID
),
14979 t
? &t
->addr
: mDNSNULL
, mDNSVal16(t
? t
->port
: zeroIPPort
), DM_NAME_PARAM(t
? &t
->domain
: mDNSNULL
),
14980 s
? &s
->addr
: mDNSNULL
, mDNSVal16(s
? s
->port
: zeroIPPort
), DM_NAME_PARAM(s
? &s
->domain
: mDNSNULL
),
14981 DM_NAME_PARAM(&q
->qname
), DNSTypeName(q
->qtype
), q
->InterfaceID
);
14982 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14983 // If this question had a DNS Push server associated with it, substitute the new server for the
14984 // old one. If there is no new server, then we'll clean up the push server later.
14985 if (!q
->DuplicateOf
&& (q
->dnsPushServer
!= mDNSNULL
))
14987 if (q
->dnsPushServer
->qDNSServer
== t
)
14989 q
->dnsPushServer
->qDNSServer
= s
; // which might be null
14991 // If it is null, do the accounting and drop the push server.
14992 if (q
->dnsPushServer
->qDNSServer
== mDNSNULL
)
14994 DNSPushReconcileConnection(m
, q
);
14999 oldSuppressed
= q
->Suppressed
;
15000 q
->Suppressed
= ShouldSuppressUnicastQuery(q
, s
);
15001 if (!q
->Suppressed
!= !oldSuppressed
) q
->Restart
= mDNStrue
;
15003 RestartUnicastQuestions(m
);
15005 // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
15006 // have already had their server changed by being restarted.
15007 for (q
= m
->Questions
; q
; q
= q
->next
)
15010 const DNSServer
*t
;
15012 if (mDNSOpaque16IsZero(q
->TargetQID
) || q
->DuplicateOf
) continue;
15014 SetValidDNSServers(m
, q
);
15015 q
->triedAllServersOnce
= mDNSfalse
;
15016 s
= GetServerForQuestion(m
, q
);
15018 DNSServerChangeForQuestion(m
, q
, s
);
15019 if (s
== t
) continue;
15021 q
->Suppressed
= ShouldSuppressUnicastQuery(q
, s
);
15022 q
->unansweredQueries
= 0;
15023 q
->TargetQID
= mDNS_NewMessageID(m
);
15024 if (!q
->Suppressed
) ActivateUnicastQuery(m
, q
, mDNStrue
);
15027 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15028 // The above code may have found some DNS Push servers that are no longer valid. Now that we
15029 // are done running through the code, we need to drop our connections to those servers.
15030 // When we get here, any such servers should have zero questions associated with them.
15031 for (psp
= &m
->DNSPushServers
; *psp
!= mDNSNULL
; )
15033 DNSPushNotificationServer
*server
= *psp
;
15035 // It's possible that a push server whose DNS server has been deleted could be still connected but
15036 // not referenced by any questions. In this case, we just delete the push server rather than trying
15037 // to figure out with which DNS server (if any) to associate it.
15038 if (server
->qDNSServer
!= mDNSNULL
&& server
->qDNSServer
->flags
& DNSServerFlag_Delete
)
15040 server
->qDNSServer
= mDNSNULL
;
15043 if (server
->qDNSServer
== mDNSNULL
)
15045 // This would be a programming error, so should never happen.
15046 if (server
->numberOfQuestions
!= 0)
15048 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server
->serverName
);
15050 DNSPushServerDrop(server
);
15051 *psp
= server
->next
;
15052 mDNSPlatformMemFree(server
);
15056 psp
= &(*psp
)->next
;
15061 FORALL_CACHERECORDS(slot
, cg
, cr
)
15063 if (cr
->resrec
.InterfaceID
) continue;
15065 // We already walked the questions and restarted/reactivated them if the dns server
15066 // change affected the question. That should take care of updating the cache. But
15067 // what if there is no active question at this point when the DNS server change
15068 // happened ? There could be old cache entries lying around and if we don't flush
15069 // them, a new question after the DNS server change could pick up these stale
15070 // entries and get a wrong answer.
15072 // For cache entries that have active questions we might have skipped rescheduling
15073 // the questions if they were suppressed (see above). To keep it simple, we walk
15074 // all the cache entries to make sure that there are no stale entries. We use the
15075 // active question's InterfaceID/ServiceID for looking up the right DNS server.
15077 // Note: If GetServerForName returns NULL, it could either mean that there are no
15078 // DNS servers or no matching DNS servers for this question. In either case,
15079 // the cache should get purged below when we process deleted DNS servers.
15081 if (cr
->CRActiveQuestion
)
15083 // Purge or Reconfirm if this cache entry would use the new DNS server
15084 ptr
= GetServerForName(m
, cr
->resrec
.name
, cr
->CRActiveQuestion
->InterfaceID
, cr
->CRActiveQuestion
->ServiceID
);
15085 if (ptr
&& (ptr
!= cr
->resrec
.rDNSServer
))
15087 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15088 CRDisplayString(m
, cr
), &ptr
->addr
,
15089 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
);
15090 PurgeOrReconfirmCacheRecord(m
, cr
);
15092 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15093 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15094 if (!cr
->resrec
.rDNSServer
&& cr
->CRActiveQuestion
->qDNSServer
)
15096 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr
->CRActiveQuestion
->qDNSServer
->addr
, CRDisplayString(m
, cr
));
15097 cr
->resrec
.rDNSServer
= cr
->CRActiveQuestion
->qDNSServer
;
15101 if (cr
->resrec
.rDNSServer
&& cr
->resrec
.rDNSServer
->flags
& DNSServerFlag_Delete
)
15103 DNSQuestion
*qptr
= cr
->CRActiveQuestion
;
15104 if (qptr
->qDNSServer
== cr
->resrec
.rDNSServer
)
15106 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15107 " to be freed", CRDisplayString(m
, cr
),
15108 qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
,
15109 &cr
->resrec
.rDNSServer
->addr
);
15110 qptr
->validDNSServers
= zeroOpaque128
;
15111 qptr
->qDNSServer
= mDNSNULL
;
15112 cr
->resrec
.rDNSServer
= mDNSNULL
;
15116 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15117 " resetting to question's DNSServer Address %#a", CRDisplayString(m
, cr
),
15118 qptr
->qname
.c
, DNSTypeName(qptr
->qtype
), qptr
->InterfaceID
,
15119 &cr
->resrec
.rDNSServer
->addr
,
15120 qptr
->qDNSServer
? &qptr
->qDNSServer
->addr
: mDNSNULL
);
15121 cr
->resrec
.rDNSServer
= qptr
->qDNSServer
;
15123 PurgeOrReconfirmCacheRecord(m
, cr
);
15126 else if (!cr
->resrec
.rDNSServer
|| cr
->resrec
.rDNSServer
->flags
& DNSServerFlag_Delete
)
15128 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
15129 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S
", DNS server " PUB_S
" " PRI_IP_ADDR
" " PUB_S
,
15130 CRDisplayString(m
, cr
), !cr
->resrec
.rDNSServer
? "(to be deleted)" : "",
15131 cr
->resrec
.rDNSServer
? &cr
->resrec
.rDNSServer
->addr
: mDNSNULL
,
15132 cr
->resrec
.rDNSServer
? DNSScopeToString(cr
->resrec
.rDNSServer
->scopeType
) : "" );
15133 cr
->resrec
.rDNSServer
= mDNSNULL
;
15134 mDNS_PurgeCacheResourceRecord(m
, cr
);
15138 // Delete all the DNS servers that are flagged for deletion
15141 if (((*p
)->flags
& DNSServerFlag_Delete
) != 0)
15145 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr
, &ptr
->addr
, mDNSVal16(ptr
->port
), ptr
->domain
.c
);
15146 mDNSPlatformMemFree(ptr
);
15153 LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m
));
15155 // 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).
15156 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15157 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15158 // 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.
15159 if ((m
->DNSServers
!= mDNSNULL
) != (oldServers
!= mDNSNULL
))
15162 FORALL_CACHERECORDS(slot
, cg
, cr
)
15164 if (!cr
->resrec
.InterfaceID
)
15166 mDNS_PurgeCacheResourceRecord(m
, cr
);
15170 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15171 m
->DNSServers
? "DNS server became" : "No DNS servers", count
);
15173 // Force anything that needs to get zone data to get that information again
15174 RestartRecordGetZoneData(m
);
15176 #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
15178 SetDynDNSHostNameIfChanged(m
, &fqdn
);
15182 // handle router and primary interface changes
15183 v4
= v6
= r
= zeroAddr
;
15184 v4
.type
= r
.type
= mDNSAddrType_IPv4
;
15186 if (mDNSPlatformGetPrimaryInterface(&v4
, &v6
, &r
) == mStatus_NoError
&& !mDNSv4AddressIsLinkLocal(&v4
.ip
.v4
))
15188 mDNS_SetPrimaryInterfaceInfo(m
,
15189 !mDNSIPv4AddressIsZero(v4
.ip
.v4
) ? &v4
: mDNSNULL
,
15190 !mDNSIPv6AddressIsZero(v6
.ip
.v6
) ? &v6
: mDNSNULL
,
15191 !mDNSIPv4AddressIsZero(r
.ip
.v4
) ? &r
: mDNSNULL
);
15195 mDNS_SetPrimaryInterfaceInfo(m
, mDNSNULL
, mDNSNULL
, mDNSNULL
);
15196 if (m
->FQDN
.c
[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m
->FQDN
, 1); // Set status to 1 to indicate temporary failure
15199 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m
));
15200 return mStatus_NoError
;
15203 mDNSexport
void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
)
15205 m
->mDNSPlatformStatus
= result
;
15206 if (m
->MainCallback
)
15209 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15210 m
->MainCallback(m
, mStatus_NoError
);
15211 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15216 mDNSlocal
void DeregLoop(mDNS
*const m
, AuthRecord
*const start
)
15218 m
->CurrentRecord
= start
;
15219 while (m
->CurrentRecord
)
15221 AuthRecord
*rr
= m
->CurrentRecord
;
15222 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15223 (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
) ? "Initiating " : "Accelerating",
15224 rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15225 if (rr
->resrec
.RecordType
!= kDNSRecordTypeDeregistering
)
15226 mDNS_Deregister_internal(m
, rr
, mDNS_Dereg_rapid
);
15227 else if (rr
->AnnounceCount
> 1)
15229 rr
->AnnounceCount
= 1;
15230 rr
->LastAPTime
= m
->timenow
- rr
->ThisAPInterval
;
15232 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15233 // new records could have been added to the end of the list as a result of that call.
15234 if (m
->CurrentRecord
== rr
) // If m->CurrentRecord was not advanced for us, do it now
15235 m
->CurrentRecord
= rr
->next
;
15239 mDNSexport
void mDNS_StartExit(mDNS
*const m
)
15245 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_StartExit");
15246 m
->ShutdownTime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
* 5);
15248 mDNSCoreBeSleepProxyServer_internal(m
, 0, 0, 0, 0, 0);
15250 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15251 if (WCFConnectionDealloc
)
15255 WCFConnectionDealloc(m
->WCF
);
15261 #ifndef UNICAST_DISABLED
15265 // Don't need to do SleepRecordRegistrations() here
15266 // because we deregister all records and services later in this routine
15267 while (m
->Hostnames
) mDNS_RemoveDynDNSHostName(m
, &m
->Hostnames
->fqdn
);
15269 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15270 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15271 // and we may crash because the list still contains dangling pointers.
15272 for (s
= SearchList
; s
; s
= s
->next
)
15273 while (s
->AuthRecs
)
15275 ARListElem
*dereg
= s
->AuthRecs
;
15276 s
->AuthRecs
= s
->AuthRecs
->next
;
15277 mDNS_Deregister_internal(m
, &dereg
->ar
, mDNS_Dereg_normal
); // Memory will be freed in the FreeARElemCallback
15282 DeadvertiseAllInterfaceRecords(m
, kDeadvertiseFlag_All
);
15284 // Shut down all our active NAT Traversals
15285 while (m
->NATTraversals
)
15287 NATTraversalInfo
*t
= m
->NATTraversals
;
15288 mDNS_StopNATOperation_internal(m
, t
); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15290 // After stopping the NAT Traversal, we zero out the fields.
15291 // This has particularly important implications for our AutoTunnel records --
15292 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15293 // handlers to just turn around and attempt to re-register those same records.
15294 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15296 t
->ExternalAddress
= zerov4Addr
;
15297 t
->NewAddress
= zerov4Addr
;
15298 t
->ExternalPort
= zeroIPPort
;
15299 t
->RequestedPort
= zeroIPPort
;
15301 t
->Result
= mStatus_NoError
;
15304 // Make sure there are nothing but deregistering records remaining in the list
15305 if (m
->CurrentRecord
)
15307 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
15308 "mDNS_StartExit: ERROR m->CurrentRecord already set " PRI_S
, ARDisplayString(m
, m
->CurrentRecord
));
15311 // We're in the process of shutting down, so queries, etc. are no longer available.
15312 // Consequently, determining certain information, e.g. the uDNS update server's IP
15313 // address, will not be possible. The records on the main list are more likely to
15314 // already contain such information, so we deregister the duplicate records first.
15315 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_StartExit: Deregistering duplicate resource records");
15316 DeregLoop(m
, m
->DuplicateRecords
);
15317 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_StartExit: Deregistering resource records");
15318 DeregLoop(m
, m
->ResourceRecords
);
15320 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15321 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15322 if (m
->NextScheduledResponse
- m
->timenow
< mDNSPlatformOneSecond
)
15324 m
->NextScheduledResponse
= m
->timenow
;
15325 m
->SuppressSending
= 0;
15328 if (m
->ResourceRecords
)
15330 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_StartExit: Sending final record deregistrations");
15334 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_StartExit: No deregistering records remain");
15337 for (rr
= m
->DuplicateRecords
; rr
; rr
= rr
->next
)
15339 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
15340 "mDNS_StartExit: Should not still have Duplicate Records remaining: %02X " PRI_S
,
15341 rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15344 // If any deregistering records remain, send their deregistration announcements before we exit
15345 if (m
->mDNSPlatformStatus
!= mStatus_NoError
) DiscardDeregistrations(m
);
15349 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_StartExit: done");
15352 mDNSexport
void mDNS_FinalExit(mDNS
*const m
)
15354 mDNSu32 rrcache_active
= 0;
15355 mDNSu32 rrcache_totalused
= m
->rrcache_totalused
;
15359 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_FinalExit: mDNSPlatformClose");
15360 mDNSPlatformClose(m
);
15362 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
15364 while (m
->rrcache_hash
[slot
])
15366 CacheGroup
*cg
= m
->rrcache_hash
[slot
];
15367 while (cg
->members
)
15369 CacheRecord
*cr
= cg
->members
;
15370 cg
->members
= cg
->members
->next
;
15371 if (cr
->CRActiveQuestion
) rrcache_active
++;
15372 ReleaseCacheRecord(m
, cr
);
15374 cg
->rrcache_tail
= &cg
->members
;
15375 ReleaseCacheGroup(m
, &m
->rrcache_hash
[slot
]);
15378 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused
, rrcache_active
);
15379 if (rrcache_active
!= m
->rrcache_active
)
15380 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused
, rrcache_active
, m
->rrcache_active
);
15382 for (rr
= m
->ResourceRecords
; rr
; rr
= rr
->next
)
15383 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr
, rr
->resrec
.RecordType
, ARDisplayString(m
, rr
));
15385 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15386 uninit_trust_anchors();
15387 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15389 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "mDNS_FinalExit: done");
15393 #include "../unittests/mdns_ut.c"