]>
Commit | Line | Data |
---|---|---|
f0cc3e7b | 1 | /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*- |
7f0064bd | 2 | * |
19fa75a9 | 3 | * Copyright (c) 2002-2020 Apple Inc. All rights reserved. |
c9b9ae52 | 4 | * |
67c8f8a1 A |
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 | |
83fb1e36 | 8 | * |
67c8f8a1 | 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
83fb1e36 | 10 | * |
67c8f8a1 A |
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 | |
c9b9ae52 | 15 | * limitations under the License. |
c9b9ae52 A |
16 | * |
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. | |
83fb1e36 | 19 | * |
c9b9ae52 | 20 | * The previous point is very important: This file does not depend on any external |
67c8f8a1 | 21 | * header files. It should compile on *any* platform that has a C compiler, without |
c9b9ae52 A |
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). | |
263eeeab | 24 | */ |
c9b9ae52 | 25 | |
95d7a4a3 | 26 | #include "DNSCommon.h" // Defines general DNS utility routines |
83fb1e36 | 27 | #include "uDNS.h" // Defines entry points into unicast-specific routines |
f0cc3e7b A |
28 | |
29 | #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) | |
30 | #include "D2D.h" | |
31 | #endif | |
32 | ||
19fa75a9 A |
33 | #if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN) |
34 | #include <bsm/libbsm.h> | |
35 | #endif | |
36 | ||
37 | #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) | |
38 | #include "dnssd_analytics.h" | |
39 | #endif | |
40 | ||
41 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
42 | #include "QuerierSupport.h" | |
f0cc3e7b | 43 | #endif |
67c8f8a1 | 44 | |
c9b9ae52 | 45 | // Disable certain benign warnings with Microsoft compilers |
83fb1e36 A |
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) | |
51 | ||
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) | |
6528fe3e A |
58 | #endif |
59 | ||
51601d48 | 60 | #include "dns_sd.h" // for kDNSServiceFlags* definitions |
12c5fa7a | 61 | #include "dns_sd_internal.h" |
51601d48 | 62 | |
263eeeab | 63 | #if APPLE_OSX_mDNSResponder |
9f221bca A |
64 | // Delay in seconds before disabling multicast after there are no active queries or registrations. |
65 | #define BONJOUR_DISABLE_DELAY 60 | |
f0cc3e7b A |
66 | #endif |
67 | ||
68 | #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER) | |
69 | #include <WebFilterDNS/WebFilterDNS.h> | |
9f221bca | 70 | |
263eeeab A |
71 | WCFConnection *WCFConnectionNew(void) __attribute__((weak_import)); |
72 | void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import)); | |
f0cc3e7b | 73 | #endif |
263eeeab | 74 | |
f0cc3e7b | 75 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
9f221bca A |
76 | #include "Metrics.h" |
77 | #endif | |
78 | ||
f0cc3e7b | 79 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) |
12c5fa7a A |
80 | #include "DNS64.h" |
81 | #endif | |
82 | ||
19fa75a9 A |
83 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) |
84 | #include "dnssec_v2.h" | |
85 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
86 | ||
32bb7e43 A |
87 | // Forward declarations |
88 | mDNSlocal void BeginSleepProcessing(mDNS *const m); | |
89 | mDNSlocal void RetrySPSRegistrations(mDNS *const m); | |
9f221bca | 90 | mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly); |
19fa75a9 | 91 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
294beb6e | 92 | mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q); |
19fa75a9 | 93 | #endif |
564f2ae2 | 94 | mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q); |
83fb1e36 | 95 | mDNSlocal void mDNS_SendKeepalives(mDNS *const m); |
51601d48 A |
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); | |
98 | ||
f0cc3e7b A |
99 | typedef mDNSu32 DeadvertiseFlags; |
100 | #define kDeadvertiseFlag_NormalHostname (1U << 0) | |
101 | #define kDeadvertiseFlag_RandHostname (1U << 1) | |
102 | #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname) | |
103 | ||
104 | mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags); | |
105 | mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set); | |
9f221bca | 106 | mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth); |
83fb1e36 | 107 | |
6528fe3e | 108 | // *************************************************************************** |
c9b9ae52 | 109 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e A |
110 | #pragma mark - Program Constants |
111 | #endif | |
112 | ||
51601d48 A |
113 | // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it |
114 | #define MDNS_TRACER 1 | |
67c8f8a1 | 115 | |
c9b9ae52 A |
116 | // Any records bigger than this are considered 'large' records |
117 | #define SmallRecordLimit 1024 | |
118 | ||
c9b9ae52 | 119 | #define kMaxUpdateCredits 10 |
7f0064bd | 120 | #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6) |
c9b9ae52 | 121 | |
51601d48 A |
122 | // define special NR_AnswerTo values |
123 | #define NR_AnswerMulticast (mDNSu8*)~0 | |
124 | #define NR_AnswerUnicast (mDNSu8*)~1 | |
125 | ||
12c5fa7a A |
126 | // Question default timeout values |
127 | #define DEFAULT_MCAST_TIMEOUT 5 | |
128 | #define DEFAULT_LO_OR_P2P_TIMEOUT 5 | |
129 | ||
51601d48 A |
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 | |
9f221bca A |
134 | #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY |
135 | ||
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) | |
139 | ||
140 | // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets | |
141 | #define MAX_CONFLICT_PROCESSING_DELAYS 3 | |
51601d48 | 142 | |
9f221bca A |
143 | // RFC 6762 defines Passive Observation Of Failures (POOF) |
144 | // | |
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. | |
149 | // | |
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. | |
154 | // | |
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. | |
159 | // | |
160 | // <https://tools.ietf.org/html/rfc6762#section-10.5> | |
161 | ||
162 | #define POOF_ENABLED 1 | |
51601d48 | 163 | |
283ee3ff | 164 | mDNSexport const char *const mDNS_DomainTypeNames[] = |
83fb1e36 A |
165 | { |
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 | |
171 | }; | |
6528fe3e | 172 | |
7f0064bd A |
173 | #ifdef UNICAST_DISABLED |
174 | #define uDNS_IsActiveQuery(q, u) mDNSfalse | |
175 | #endif | |
176 | ||
c9b9ae52 A |
177 | // *************************************************************************** |
178 | #if COMPILER_LIKES_PRAGMA_MARK | |
6528fe3e A |
179 | #pragma mark - |
180 | #pragma mark - General Utility Functions | |
181 | #endif | |
182 | ||
f0cc3e7b A |
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) | |
187 | { | |
188 | mDNS *m = context; | |
189 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) | |
190 | mDNSu32 NumAllInterfaceRecords = 0; | |
191 | mDNSu32 NumAllInterfaceQuestions = 0; | |
192 | #endif | |
193 | ||
194 | // Check core mDNS lists | |
195 | AuthRecord *rr; | |
196 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
197 | { | |
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++; | |
205 | #endif | |
206 | } | |
207 | ||
208 | for (rr = m->DuplicateRecords; rr; rr=rr->next) | |
209 | { | |
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++; | |
214 | #endif | |
215 | } | |
216 | ||
217 | rr = m->NewLocalRecords; | |
218 | if (rr) | |
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); | |
221 | ||
222 | rr = m->CurrentRecord; | |
223 | if (rr) | |
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); | |
226 | ||
227 | DNSQuestion *q; | |
228 | for (q = m->Questions; q; q=q->next) | |
229 | { | |
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++; | |
237 | #endif | |
238 | } | |
239 | ||
240 | CacheGroup *cg; | |
241 | CacheRecord *cr; | |
242 | mDNSu32 slot; | |
243 | FORALL_CACHERECORDS(slot, cg, cr) | |
244 | { | |
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) | |
248 | { | |
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)); | |
251 | } | |
252 | } | |
253 | ||
254 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) | |
255 | if (m->NumAllInterfaceRecords != NumAllInterfaceRecords) | |
256 | LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords); | |
257 | ||
258 | if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions) | |
259 | LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions); | |
260 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) | |
261 | } | |
262 | #endif // MDNS_MALLOC_DEBUGGING | |
263 | ||
51601d48 A |
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 && \ | |
83fb1e36 A |
269 | (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \ |
270 | ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \ | |
51601d48 A |
271 | (rr)->resrec.rrtype == kDNSType_CNAME || \ |
272 | (rr)->resrec.rrtype == kDNSType_PTR)) | |
294beb6e A |
273 | |
274 | mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q) | |
83fb1e36 | 275 | { |
51601d48 | 276 | mDNS_CheckLock(m); |
294beb6e | 277 | |
83fb1e36 A |
278 | if (m->NextScheduledStopTime - q->StopTime > 0) |
279 | m->NextScheduledStopTime = q->StopTime; | |
280 | } | |
294beb6e | 281 | |
67c8f8a1 | 282 | mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q) |
83fb1e36 | 283 | { |
51601d48 | 284 | mDNS_CheckLock(m); |
67c8f8a1 | 285 | |
83fb1e36 A |
286 | if (ActiveQuestion(q)) |
287 | { | |
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); | |
294 | } | |
295 | } | |
6528fe3e | 296 | |
294beb6e | 297 | mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e) |
83fb1e36 | 298 | { |
f0cc3e7b | 299 | #if MDNS_MALLOC_DEBUGGING >= 1 |
83fb1e36 A |
300 | unsigned int i; |
301 | for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF; | |
294beb6e | 302 | #endif |
83fb1e36 A |
303 | e->next = r->rrauth_free; |
304 | r->rrauth_free = e; | |
305 | r->rrauth_totalused--; | |
306 | } | |
294beb6e A |
307 | |
308 | mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp) | |
83fb1e36 A |
309 | { |
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); | |
318 | } | |
294beb6e A |
319 | |
320 | mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG) | |
83fb1e36 A |
321 | { |
322 | AuthEntity *e = mDNSNULL; | |
323 | ||
324 | if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); } | |
325 | r->rrauth_lock = 1; | |
326 | ||
327 | if (!r->rrauth_free) | |
328 | { | |
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. | |
f0cc3e7b | 333 | AuthEntity *storage = (AuthEntity *) mDNSPlatformMemAllocateClear(sizeof(*storage)); |
83fb1e36 A |
334 | storage->next = mDNSNULL; |
335 | r->rrauth_free = storage; | |
336 | } | |
337 | ||
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. | |
340 | if (!r->rrauth_free) | |
341 | { | |
342 | mDNSu32 oldtotalused = r->rrauth_totalused; | |
343 | mDNSu32 slot; | |
344 | for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) | |
345 | { | |
346 | AuthGroup **cp = &r->rrauth_hash[slot]; | |
347 | while (*cp) | |
348 | { | |
349 | if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next; | |
350 | else ReleaseAuthGroup(r, cp); | |
351 | } | |
352 | } | |
353 | LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d", | |
354 | oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused); | |
355 | } | |
356 | ||
357 | if (r->rrauth_free) // If there are records in the free list, take one | |
358 | { | |
359 | e = r->rrauth_free; | |
360 | r->rrauth_free = e->next; | |
361 | if (++r->rrauth_totalused >= r->rrauth_report) | |
362 | { | |
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; | |
367 | } | |
368 | mDNSPlatformMemZero(e, sizeof(*e)); | |
369 | } | |
370 | ||
371 | r->rrauth_lock = 0; | |
372 | ||
373 | return(e); | |
374 | } | |
294beb6e | 375 | |
12c5fa7a | 376 | mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name) |
83fb1e36 A |
377 | { |
378 | AuthGroup *ag; | |
12c5fa7a A |
379 | const mDNSu32 slot = namehash % AUTH_HASH_SLOTS; |
380 | ||
83fb1e36 A |
381 | for (ag = r->rrauth_hash[slot]; ag; ag=ag->next) |
382 | if (ag->namehash == namehash && SameDomainName(ag->name, name)) | |
383 | break; | |
384 | return(ag); | |
385 | } | |
294beb6e | 386 | |
12c5fa7a | 387 | mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr) |
83fb1e36 | 388 | { |
12c5fa7a | 389 | return(AuthGroupForName(r, rr->namehash, rr->name)); |
83fb1e36 | 390 | } |
294beb6e | 391 | |
12c5fa7a | 392 | mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr) |
83fb1e36 A |
393 | { |
394 | mDNSu16 namelen = DomainNameLength(rr->name); | |
395 | AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL); | |
12c5fa7a | 396 | const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS; |
83fb1e36 A |
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)) | |
f0cc3e7b | 404 | ag->name = (domainname *) mDNSPlatformMemAllocate(namelen); |
83fb1e36 A |
405 | else |
406 | ag->name = (domainname*)ag->namestorage; | |
407 | if (!ag->name) | |
408 | { | |
409 | LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c); | |
410 | ReleaseAuthEntity(r, (AuthEntity*)ag); | |
411 | return(mDNSNULL); | |
412 | } | |
413 | AssignDomainName(ag->name, rr->name); | |
414 | ||
12c5fa7a | 415 | if (AuthGroupForRecord(r, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c); |
83fb1e36 | 416 | r->rrauth_hash[slot] = ag; |
12c5fa7a | 417 | if (AuthGroupForRecord(r, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c); |
83fb1e36 A |
418 | |
419 | return(ag); | |
420 | } | |
294beb6e A |
421 | |
422 | // Returns the AuthGroup in which the AuthRecord was inserted | |
423 | mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr) | |
83fb1e36 A |
424 | { |
425 | AuthGroup *ag; | |
12c5fa7a A |
426 | |
427 | (void)m; | |
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 | |
83fb1e36 A |
430 | if (ag) |
431 | { | |
83fb1e36 A |
432 | *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list |
433 | ag->rrauth_tail = &(rr->next); // Advance tail pointer | |
434 | } | |
435 | return ag; | |
436 | } | |
294beb6e A |
437 | |
438 | mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr) | |
83fb1e36 A |
439 | { |
440 | AuthGroup *a; | |
83fb1e36 | 441 | AuthRecord **rp; |
83fb1e36 | 442 | |
12c5fa7a | 443 | a = AuthGroupForRecord(r, &rr->resrec); |
83fb1e36 | 444 | if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; } |
9f221bca | 445 | rp = &a->members; |
83fb1e36 A |
446 | while (*rp) |
447 | { | |
448 | if (*rp != rr) | |
449 | rp=&(*rp)->next; | |
450 | else | |
451 | { | |
452 | // We don't break here, so that we can set the tail below without tracking "prev" pointers | |
453 | ||
454 | LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr)); | |
455 | *rp = (*rp)->next; // Cut record from list | |
456 | } | |
457 | } | |
458 | // TBD: If there are no more members, release authgroup ? | |
9f221bca | 459 | a->rrauth_tail = rp; |
83fb1e36 A |
460 | return a; |
461 | } | |
294beb6e | 462 | |
12c5fa7a | 463 | mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name) |
83fb1e36 A |
464 | { |
465 | CacheGroup *cg; | |
12c5fa7a | 466 | mDNSu32 slot = HashSlotFromNameHash(namehash); |
83fb1e36 A |
467 | for (cg = m->rrcache_hash[slot]; cg; cg=cg->next) |
468 | if (cg->namehash == namehash && SameDomainName(cg->name, name)) | |
469 | break; | |
470 | return(cg); | |
471 | } | |
283ee3ff | 472 | |
12c5fa7a | 473 | mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr) |
83fb1e36 | 474 | { |
12c5fa7a | 475 | return(CacheGroupForName(m, rr->namehash, rr->name)); |
83fb1e36 | 476 | } |
283ee3ff | 477 | |
9f221bca | 478 | mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr) |
83fb1e36 A |
479 | { |
480 | NetworkInterfaceInfo *intf; | |
481 | ||
482 | if (addr->type == mDNSAddrType_IPv4) | |
483 | { | |
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) | |
489 | return(mDNStrue); | |
490 | } | |
491 | ||
492 | if (addr->type == mDNSAddrType_IPv6) | |
493 | { | |
9f221bca | 494 | if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue); |
83fb1e36 A |
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)) | |
51601d48 | 501 | return(mDNStrue); |
83fb1e36 A |
502 | } |
503 | ||
504 | return(mDNSfalse); | |
505 | } | |
283ee3ff | 506 | |
32bb7e43 | 507 | mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID) |
83fb1e36 A |
508 | { |
509 | NetworkInterfaceInfo *intf = m->HostInterfaces; | |
510 | while (intf && intf->InterfaceID != InterfaceID) intf = intf->next; | |
511 | return(intf); | |
512 | } | |
32bb7e43 | 513 | |
51601d48 A |
514 | mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID) |
515 | { | |
516 | NetworkInterfaceInfo *intf; | |
517 | ||
518 | if (!InterfaceID) | |
519 | return mDNSNULL; | |
520 | ||
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) | |
524 | { | |
525 | if (intf->InterfaceID == InterfaceID && | |
526 | intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4)) | |
527 | { | |
528 | debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4); | |
529 | return intf; | |
530 | } | |
531 | } | |
532 | return (mDNSNULL); | |
533 | } | |
534 | ||
ca3eca6b | 535 | mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID) |
83fb1e36 A |
536 | { |
537 | NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); | |
538 | return(intf ? intf->ifname : mDNSNULL); | |
539 | } | |
32bb7e43 | 540 | |
294beb6e | 541 | // Caller should hold the lock |
f0cc3e7b | 542 | mDNSlocal void GenerateNegativeResponseEx(mDNS *const m, mDNSInterfaceID InterfaceID, QC_result qc, mDNSBool noData) |
83fb1e36 A |
543 | { |
544 | DNSQuestion *q; | |
545 | if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; } | |
546 | q = m->CurrentQuestion; | |
f0cc3e7b A |
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 ")", | |
19fa75a9 | 549 | q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); |
83fb1e36 | 550 | |
9f221bca | 551 | MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, InterfaceID, mDNSNULL); |
f0cc3e7b | 552 | m->rec.r.resrec.negativeRecordType = noData ? kNegativeRecordType_NoData : kNegativeRecordType_Unspecified; |
9f221bca | 553 | |
83fb1e36 A |
554 | // We need to force the response through in the following cases |
555 | // | |
556 | // a) SuppressUnusable questions that are suppressed | |
557 | // b) Append search domains and retry the question | |
558 | // | |
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". | |
51601d48 | 561 | AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc); |
83fb1e36 A |
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 | |
565 | } | |
f0cc3e7b | 566 | #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse) |
83fb1e36 A |
567 | |
568 | mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr) | |
569 | { | |
570 | const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name); | |
571 | if (q->CNAMEReferrals >= 10 || selfref) | |
b8d5688b | 572 | { |
f0cc3e7b A |
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, | |
19fa75a9 | 575 | q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), |
f0cc3e7b A |
576 | q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr)); |
577 | ||
b8d5688b | 578 | } |
83fb1e36 A |
579 | else |
580 | { | |
51601d48 A |
581 | UDPSocket *sock = q->LocalSocket; |
582 | mDNSOpaque16 id = q->TargetQID; | |
f0cc3e7b | 583 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
9f221bca A |
584 | uDNSMetrics metrics; |
585 | #endif | |
51601d48 | 586 | |
9f221bca | 587 | q->LocalSocket = mDNSNULL; |
83fb1e36 A |
588 | |
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. | |
598 | ||
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. | |
603 | ||
f0cc3e7b A |
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, | |
19fa75a9 | 606 | q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), |
f0cc3e7b | 607 | q->CNAMEReferrals, RRDisplayString(m, rr)); |
83fb1e36 | 608 | |
19fa75a9 A |
609 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
610 | if (!mDNSOpaque16IsZero(q->TargetQID)) | |
611 | { | |
612 | // Must be called before zeroing out q->metrics below. | |
613 | Querier_PrepareQuestionForCNAMERestart(q); | |
614 | } | |
615 | #endif | |
f0cc3e7b | 616 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
9f221bca A |
617 | if ((q->CNAMEReferrals == 0) && !q->metrics.originalQName) |
618 | { | |
619 | domainname * qName; | |
620 | mDNSu16 qNameLen; | |
621 | ||
622 | qNameLen = DomainNameLength(&q->qname); | |
623 | if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME)) | |
624 | { | |
f0cc3e7b | 625 | qName = (domainname *) mDNSPlatformMemAllocate(qNameLen); |
9f221bca A |
626 | if (qName) |
627 | { | |
628 | mDNSPlatformMemCopy(qName->c, q->qname.c, qNameLen); | |
629 | q->metrics.originalQName = qName; | |
630 | } | |
631 | } | |
632 | } | |
633 | metrics = q->metrics; | |
19fa75a9 A |
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. | |
9f221bca A |
636 | mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics)); |
637 | #endif | |
83fb1e36 A |
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)) | |
645 | { | |
f0cc3e7b A |
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, | |
19fa75a9 | 648 | q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), RRDisplayString(m, rr)); |
f0cc3e7b | 649 | q->IsUnicastDotLocal = mDNStrue; |
83fb1e36 | 650 | } |
19fa75a9 A |
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 | |
83fb1e36 A |
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; | |
f0cc3e7b A |
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 | |
9f221bca A |
660 | q->metrics = metrics; |
661 | #endif | |
51601d48 A |
662 | if (sock) |
663 | { | |
9f221bca A |
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); | |
666 | else | |
667 | { | |
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; | |
671 | q->TargetQID = id; | |
672 | } | |
51601d48 | 673 | } |
83fb1e36 A |
674 | } |
675 | } | |
294beb6e | 676 | |
9f221bca A |
677 | #ifdef USE_LIBIDN |
678 | ||
679 | #include <unicode/uidna.h> | |
680 | ||
681 | // #define DEBUG_PUNYCODE 1 | |
682 | ||
683 | mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end) | |
684 | { | |
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); | |
19fa75a9 | 688 | int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, (int32_t)(end-(dst+1)), &info, &errorCode); |
9f221bca A |
689 | uidna_close(uts46); |
690 | #if DEBUG_PUNYCODE | |
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); | |
694 | #endif | |
695 | if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL; | |
696 | *dst = len; | |
697 | return(dst + 1 + len); | |
698 | } | |
699 | ||
700 | mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d) | |
701 | { | |
702 | int i; | |
703 | for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue; | |
704 | return mDNSfalse; | |
705 | } | |
706 | ||
707 | mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d) | |
708 | { | |
709 | const mDNSu8 *ptr = d->c; | |
710 | const mDNSu8 *ans = mDNSNULL; | |
711 | while (ptr[0]) | |
712 | { | |
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; | |
716 | ptr = next; | |
717 | } | |
718 | return ans; | |
719 | } | |
720 | ||
721 | mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname) | |
722 | { | |
723 | const mDNSu8 *h = FindLastHighASCIILabel(&q->qname); | |
724 | #if DEBUG_PUNYCODE | |
725 | LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h); | |
726 | #endif | |
727 | if (!h) return mDNSfalse; // There are no high-ascii labels to convert | |
728 | ||
729 | mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME); | |
730 | if (!dst) | |
731 | return mDNSfalse; // The label was not convertible to Punycode | |
732 | else | |
733 | { | |
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 | |
738 | ||
19fa75a9 | 739 | mDNSPlatformMemCopy(newname->c, q->qname.c, (mDNSu32)(h - q->qname.c)); // Fill in the leading part |
9f221bca A |
740 | mDNSPlatformMemCopy(dst, src, remainder); // Fill in the trailing part |
741 | #if DEBUG_PUNYCODE | |
742 | LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c); | |
743 | #endif | |
744 | return mDNStrue; | |
745 | } | |
746 | } | |
747 | ||
748 | #endif // USE_LIBIDN | |
749 | ||
294beb6e A |
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) | |
83fb1e36 A |
753 | { |
754 | DNSQuestion *q = m->CurrentQuestion; | |
755 | mDNSBool followcname; | |
756 | ||
757 | if (!q) | |
758 | { | |
759 | LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr)); | |
760 | return; | |
761 | } | |
762 | ||
763 | followcname = FollowCNAME(q, &rr->resrec, AddRecord); | |
764 | ||
765 | // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique | |
766 | if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask)) | |
767 | { | |
768 | LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s", | |
769 | AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr)); | |
770 | return; | |
771 | } | |
772 | ||
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) | |
777 | { | |
778 | q->CurrentAnswers += AddRecord ? 1 : -1; | |
51601d48 | 779 | if (UniqueLocalOnlyRecord(rr)) |
83fb1e36 A |
780 | { |
781 | if (!followcname || q->ReturnIntermed) | |
782 | { | |
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; | |
83fb1e36 A |
786 | q->QuestionCallback(m, q, &rr->resrec, AddRecord); |
787 | } | |
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); | |
793 | return; | |
794 | } | |
795 | else | |
796 | { | |
83fb1e36 A |
797 | q->QuestionCallback(m, q, &rr->resrec, AddRecord); |
798 | } | |
799 | } | |
800 | mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again | |
801 | } | |
283ee3ff | 802 | |
f0cc3e7b | 803 | mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord) |
83fb1e36 A |
804 | { |
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) | |
810 | { | |
811 | mDNSBool answered; | |
812 | DNSQuestion *q = m->CurrentQuestion; | |
f0cc3e7b A |
813 | if (RRAny(ar)) |
814 | answered = AuthRecordAnswersQuestion(ar, q); | |
83fb1e36 | 815 | else |
f0cc3e7b | 816 | answered = LocalOnlyRecordAnswersQuestion(ar, q); |
83fb1e36 | 817 | if (answered) |
f0cc3e7b | 818 | AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again |
83fb1e36 A |
819 | if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now |
820 | m->CurrentQuestion = q->next; | |
821 | } | |
822 | m->CurrentQuestion = mDNSNULL; | |
823 | } | |
294beb6e | 824 | |
263eeeab A |
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(). | |
832 | // | |
833 | // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(), | |
834 | // and by mDNS_Deregister_internal() | |
835 | ||
f0cc3e7b | 836 | mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord) |
83fb1e36 A |
837 | { |
838 | if (m->CurrentQuestion) | |
839 | LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)", | |
840 | m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); | |
841 | ||
842 | m->CurrentQuestion = m->LocalOnlyQuestions; | |
843 | while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions) | |
844 | { | |
845 | mDNSBool answered; | |
846 | DNSQuestion *q = m->CurrentQuestion; | |
847 | // We are called with both LocalOnly/P2P record or a regular AuthRecord | |
f0cc3e7b A |
848 | if (RRAny(ar)) |
849 | answered = AuthRecordAnswersQuestion(ar, q); | |
83fb1e36 | 850 | else |
f0cc3e7b | 851 | answered = LocalOnlyRecordAnswersQuestion(ar, q); |
83fb1e36 | 852 | if (answered) |
f0cc3e7b | 853 | AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again |
83fb1e36 A |
854 | if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now |
855 | m->CurrentQuestion = q->next; | |
856 | } | |
857 | ||
858 | m->CurrentQuestion = mDNSNULL; | |
859 | ||
860 | // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions | |
f0cc3e7b A |
861 | if (ar->ARType == AuthRecordLocalOnly || ar->ARType == AuthRecordP2P) |
862 | AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, ar, AddRecord); | |
83fb1e36 A |
863 | |
864 | } | |
283ee3ff | 865 | |
6528fe3e | 866 | // *************************************************************************** |
c9b9ae52 | 867 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e | 868 | #pragma mark - |
8e92c31c | 869 | #pragma mark - Resource Record Utility Functions |
6528fe3e A |
870 | #endif |
871 | ||
8e92c31c | 872 | #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA) |
6528fe3e | 873 | |
f0cc3e7b A |
874 | mDNSlocal mDNSBool ResourceRecordIsValidAnswer(const AuthRecord *const rr) |
875 | { | |
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))) | |
880 | { | |
881 | return mDNStrue; | |
882 | } | |
883 | else | |
884 | { | |
885 | return mDNSfalse; | |
886 | } | |
887 | } | |
888 | ||
889 | mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *const rr, const mDNSInterfaceID InterfaceID) | |
890 | { | |
891 | if (rr->resrec.InterfaceID == mDNSInterface_Any) | |
892 | { | |
893 | return mDNSPlatformValidRecordForInterface(rr, InterfaceID); | |
894 | } | |
895 | else | |
896 | { | |
897 | return ((rr->resrec.InterfaceID == InterfaceID) ? mDNStrue : mDNSfalse); | |
898 | } | |
899 | } | |
6528fe3e | 900 | |
f0cc3e7b A |
901 | mDNSlocal mDNSBool ResourceRecordIsValidInterfaceAnswer(const AuthRecord *const rr, const mDNSInterfaceID interfaceID) |
902 | { | |
903 | return ((IsInterfaceValidForAuthRecord(rr, interfaceID) && ResourceRecordIsValidAnswer(rr)) ? mDNStrue : mDNSfalse); | |
904 | } | |
6528fe3e | 905 | |
8e92c31c A |
906 | #define DefaultProbeCountForTypeUnique ((mDNSu8)3) |
907 | #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0) | |
6528fe3e | 908 | |
f0cc3e7b A |
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. | |
912 | ||
51601d48 A |
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) | |
c9b9ae52 | 917 | |
263eeeab A |
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) | |
51601d48 | 923 | #define MAX_PROBE_RESTARTS ((mDNSu8)20) |
2682e09e | 924 | #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week |
263eeeab | 925 | |
1f519c61 A |
926 | // Number of wakeups we send if WakeOnResolve is set in the question |
927 | #define InitialWakeOnResolveCount ((mDNSu8)3) | |
928 | ||
8e92c31c A |
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) | |
6528fe3e | 936 | |
83fb1e36 A |
937 | #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \ |
938 | (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \ | |
939 | (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0) | |
6528fe3e | 940 | |
8e92c31c | 941 | #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0) |
8e92c31c A |
942 | #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond) |
943 | #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR)) | |
6528fe3e | 944 | |
51601d48 A |
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. | |
f0cc3e7b | 950 | // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds, |
51601d48 A |
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. | |
953 | ||
954 | #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2) | |
955 | #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5) | |
956 | ||
8e92c31c | 957 | #define MaxUnansweredQueries 4 |
c9b9ae52 | 958 | |
8e92c31c A |
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 | |
67c8f8a1 | 965 | |
32bb7e43 A |
966 | // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match |
967 | ||
968 | #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B)) | |
969 | ||
970 | mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2) | |
83fb1e36 A |
971 | { |
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); | |
977 | return (mDNSBool)( | |
978 | r1->resrec.rrclass == r2->resrec.rrclass && | |
979 | r1->resrec.namehash == r2->resrec.namehash && | |
980 | SameDomainName(r1->resrec.name, r2->resrec.name)); | |
981 | } | |
c9b9ae52 | 982 | |
7f0064bd A |
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. | |
32bb7e43 A |
988 | |
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 | |
8e92c31c | 991 | mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr) |
83fb1e36 A |
992 | { |
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); | |
9f221bca A |
1000 | if ((authrr->resrec.InterfaceID == mDNSInterface_Any) && |
1001 | !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse); | |
83fb1e36 A |
1002 | return (mDNSBool)( |
1003 | pktrr->resrec.rrclass == authrr->resrec.rrclass && | |
1004 | pktrr->resrec.namehash == authrr->resrec.namehash && | |
1005 | SameDomainName(pktrr->resrec.name, authrr->resrec.name)); | |
1006 | } | |
6528fe3e | 1007 | |
030b743d | 1008 | // CacheRecord *ka is the CacheRecord from the known answer list in the query. |
8e92c31c A |
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) | |
83fb1e36 A |
1016 | { |
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); | |
1019 | ||
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); | |
1030 | } | |
6528fe3e | 1031 | |
8e92c31c | 1032 | mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr) |
83fb1e36 A |
1033 | { |
1034 | if (rr->resrec.RecordType == kDNSRecordTypeUnique) | |
1035 | { | |
1036 | if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10) | |
1037 | { | |
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); | |
1040 | } | |
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; | |
1049 | } | |
1050 | else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering)) | |
1051 | { | |
1052 | if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0) | |
1053 | m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval); | |
1054 | } | |
1055 | } | |
6528fe3e | 1056 | |
32bb7e43 | 1057 | mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr) |
83fb1e36 A |
1058 | { |
1059 | // For reverse-mapping Sleep Proxy PTR records, probe interval is one second | |
1060 | rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType); | |
1061 | ||
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. | |
1072 | ||
1073 | if (rr->ProbeCount) | |
1074 | { | |
f0cc3e7b | 1075 | rr->ProbingConflictCount = 0; |
83fb1e36 A |
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) | |
1078 | { | |
1079 | // To allow us to aggregate probes when a group of services are registered together, | |
9f221bca A |
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 | |
83fb1e36 A |
1083 | // 1/4 second wait; probe |
1084 | // 1/4 second wait; probe | |
9f221bca | 1085 | // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered) |
83fb1e36 A |
1086 | m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2)); |
1087 | ||
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; | |
1093 | ||
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; | |
1099 | ||
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); | |
1103 | ||
1104 | if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8) | |
1105 | { | |
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, | |
1110 | m->SuppressSending, | |
1111 | m->SuppressSending - m->timenow); | |
1112 | m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2)); | |
1113 | } | |
1114 | } | |
1115 | rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval; | |
1116 | } | |
12c5fa7a A |
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)) | |
83fb1e36 A |
1120 | rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2; |
1121 | else | |
1122 | rr->LastAPTime = m->timenow - rr->ThisAPInterval; | |
1123 | ||
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. | |
9f221bca | 1130 | if (rr->AddressProxy.type) |
51601d48 | 1131 | rr->LastAPTime = m->timenow; |
83fb1e36 A |
1132 | |
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; | |
1137 | ||
1138 | SetNextAnnounceProbeTime(m, rr); | |
1139 | } | |
6528fe3e | 1140 | |
263eeeab | 1141 | mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr) |
83fb1e36 A |
1142 | { |
1143 | const domainname *target; | |
1144 | if (rr->AutoTarget) | |
1145 | { | |
f0cc3e7b | 1146 | rr->AutoTarget = Target_AutoHostAndNATMAP; |
83fb1e36 A |
1147 | } |
1148 | ||
1149 | target = GetServiceTarget(m, rr); | |
1150 | if (!target || target->c[0] == 0) | |
1151 | { | |
1152 | // defer registration until we've got a target | |
1153 | LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr)); | |
1154 | rr->state = regState_NoTarget; | |
1155 | return mDNSNULL; | |
1156 | } | |
1157 | else | |
1158 | { | |
1159 | LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr)); | |
1160 | return target; | |
1161 | } | |
1162 | } | |
263eeeab | 1163 | |
f0cc3e7b A |
1164 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
1165 | mDNSlocal mDNSBool AuthRecordIncludesOrIsAWDL(const AuthRecord *const ar) | |
1166 | { | |
1167 | return ((AuthRecordIncludesAWDL(ar) || mDNSPlatformInterfaceIsAWDL(ar->resrec.InterfaceID)) ? mDNStrue : mDNSfalse); | |
1168 | } | |
1169 | #endif | |
1170 | ||
67c8f8a1 A |
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 | |
c9b9ae52 | 1173 | mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr) |
83fb1e36 A |
1174 | { |
1175 | domainname *const target = GetRRDomainNameTarget(&rr->resrec); | |
f0cc3e7b | 1176 | const domainname *newname; |
83fb1e36 | 1177 | |
f0cc3e7b A |
1178 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
1179 | if (AuthRecordIncludesOrIsAWDL(rr)) | |
1180 | { | |
1181 | newname = &m->RandomizedHostname; | |
1182 | } | |
1183 | else | |
1184 | #endif | |
1185 | { | |
1186 | newname = &m->MulticastHostname; | |
1187 | } | |
83fb1e36 A |
1188 | if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype)); |
1189 | ||
1190 | if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage))) | |
1191 | { | |
1192 | const domainname *const n = SetUnicastTargetToHostName(m, rr); | |
1193 | if (n) newname = n; | |
9f221bca | 1194 | else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; } |
83fb1e36 A |
1195 | } |
1196 | ||
1197 | if (target && SameDomainName(target, newname)) | |
1198 | debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c); | |
1199 | ||
1200 | if (target && !SameDomainName(target, newname)) | |
1201 | { | |
1202 | AssignDomainName(target, newname); | |
1203 | SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash | |
1204 | ||
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); | |
1209 | ||
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)); | |
1216 | ||
1217 | rr->AnnounceCount = InitialAnnounceCount; | |
1218 | rr->RequireGoodbye = mDNSfalse; | |
51601d48 | 1219 | rr->ProbeRestartCount = 0; |
83fb1e36 A |
1220 | InitializeLastAPTime(m, rr); |
1221 | } | |
1222 | } | |
c9b9ae52 | 1223 | |
7f0064bd | 1224 | mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr) |
83fb1e36 A |
1225 | { |
1226 | if (rr->RecordCallback) | |
1227 | { | |
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 | |
1234 | } | |
1235 | } | |
263eeeab A |
1236 | |
1237 | mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr) | |
83fb1e36 A |
1238 | { |
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) | |
1244 | { | |
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; | |
1250 | if (srvRR) | |
1251 | { | |
1252 | if (srvRR->resrec.rrtype != kDNSType_SRV) | |
1253 | { | |
1254 | LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR)); | |
1255 | } | |
1256 | else | |
1257 | { | |
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; | |
1261 | } | |
1262 | } | |
1263 | } | |
1264 | ||
1265 | if (rr->state == regState_NoTarget) | |
1266 | { | |
1267 | LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr)); | |
1268 | return; | |
1269 | } | |
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) | |
1276 | { | |
1277 | LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state); | |
1278 | rr->state = regState_DeregPending; | |
1279 | } | |
1280 | else | |
1281 | { | |
1282 | LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state); | |
1283 | rr->state = regState_Pending; | |
1284 | } | |
f0cc3e7b A |
1285 | rr->ProbingConflictCount = 0; |
1286 | rr->LastConflictPktNum = 0; | |
1287 | rr->ProbeRestartCount = 0; | |
1288 | rr->ProbeCount = 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; | |
83fb1e36 A |
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) | |
1300 | { | |
1301 | mDNS_StopNATOperation_internal(m, &rr->NATinfo); | |
1302 | rr->NATinfo.clientContext = mDNSNULL; | |
1303 | } | |
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); | |
1308 | } | |
263eeeab A |
1309 | |
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 | |
67c8f8a1 | 1314 | #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \ |
83fb1e36 A |
1315 | ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \ |
1316 | ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering)) | |
263eeeab | 1317 | |
67c8f8a1 | 1318 | #define RecordIsLocalDuplicate(A,B) \ |
83fb1e36 | 1319 | ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec)) |
c9b9ae52 | 1320 | |
294beb6e | 1321 | mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr) |
83fb1e36 | 1322 | { |
9f221bca A |
1323 | const AuthGroup *a; |
1324 | AuthRecord *rp; | |
83fb1e36 | 1325 | |
12c5fa7a | 1326 | a = AuthGroupForRecord(r, &rr->resrec); |
83fb1e36 | 1327 | if (!a) return mDNSNULL; |
9f221bca A |
1328 | rp = a->members; |
1329 | while (rp) | |
83fb1e36 | 1330 | { |
9f221bca A |
1331 | if (!RecordIsLocalDuplicate(rp, rr)) |
1332 | rp = rp->next; | |
83fb1e36 A |
1333 | else |
1334 | { | |
9f221bca | 1335 | if (rp->resrec.RecordType == kDNSRecordTypeDeregistering) |
83fb1e36 | 1336 | { |
9f221bca A |
1337 | rp->AnnounceCount = 0; |
1338 | rp = rp->next; | |
83fb1e36 | 1339 | } |
9f221bca | 1340 | else return rp; |
83fb1e36 A |
1341 | } |
1342 | } | |
1343 | return (mDNSNULL); | |
1344 | } | |
294beb6e A |
1345 | |
1346 | mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr) | |
83fb1e36 | 1347 | { |
9f221bca A |
1348 | const AuthGroup *a; |
1349 | const AuthRecord *rp; | |
83fb1e36 | 1350 | |
12c5fa7a | 1351 | a = AuthGroupForRecord(r, &rr->resrec); |
83fb1e36 | 1352 | if (!a) return mDNSfalse; |
9f221bca A |
1353 | rp = a->members; |
1354 | while (rp) | |
83fb1e36 A |
1355 | { |
1356 | const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr; | |
9f221bca A |
1357 | const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp; |
1358 | if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec)) | |
83fb1e36 A |
1359 | return mDNStrue; |
1360 | else | |
9f221bca | 1361 | rp = rp->next; |
83fb1e36 A |
1362 | } |
1363 | return (mDNSfalse); | |
1364 | } | |
294beb6e A |
1365 | |
1366 | // checks to see if "rr" is already present | |
1367 | mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr) | |
83fb1e36 | 1368 | { |
9f221bca A |
1369 | const AuthGroup *a; |
1370 | AuthRecord *rp; | |
83fb1e36 | 1371 | |
12c5fa7a | 1372 | a = AuthGroupForRecord(r, &rr->resrec); |
83fb1e36 | 1373 | if (!a) return mDNSNULL; |
9f221bca A |
1374 | rp = a->members; |
1375 | while (rp) | |
83fb1e36 | 1376 | { |
9f221bca A |
1377 | if (rp != rr) |
1378 | rp = rp->next; | |
83fb1e36 A |
1379 | else |
1380 | { | |
9f221bca | 1381 | return rp; |
83fb1e36 A |
1382 | } |
1383 | } | |
1384 | return (mDNSNULL); | |
1385 | } | |
294beb6e | 1386 | |
51601d48 A |
1387 | mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr) |
1388 | { | |
9f221bca A |
1389 | if (RRLocalOnly(rr)) |
1390 | { | |
1391 | // A sanity check, this should be prevented in calling code. | |
1392 | LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr)); | |
1393 | return; | |
1394 | } | |
1395 | ||
f0cc3e7b | 1396 | if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost)) |
51601d48 | 1397 | { |
f0cc3e7b A |
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)) | |
1403 | { | |
1404 | if (AuthRecordIncludesAWDL(rr)) | |
1405 | { | |
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) | |
1411 | { | |
1412 | flags |= kDeadvertiseFlag_RandHostname; | |
1413 | if (m->AutoTargetAWDLOnlyCount == 0) flagsAWDL |= kDeadvertiseFlag_RandHostname; | |
1414 | } | |
1415 | } | |
1416 | else | |
1417 | { | |
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)) | |
1423 | { | |
1424 | flagsAWDL |= kDeadvertiseFlag_RandHostname; | |
1425 | } | |
1426 | } | |
1427 | if (flags || flagsAWDL) | |
1428 | { | |
1429 | for (intf = m->HostInterfaces; intf; intf = intf->next) | |
1430 | { | |
1431 | if (!intf->Advertise) continue; | |
1432 | if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) | |
1433 | { | |
1434 | if (flagsAWDL) DeadvertiseInterface(m, intf, flagsAWDL); | |
1435 | } | |
1436 | else | |
1437 | { | |
1438 | if (flags) DeadvertiseInterface(m, intf, flags); | |
1439 | } | |
1440 | } | |
1441 | } | |
1442 | if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0)) | |
1443 | { | |
1444 | GetRandomUUIDLocalHostname(&m->RandomizedHostname); | |
1445 | } | |
1446 | } | |
1447 | else | |
1448 | #endif | |
1449 | { | |
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) | |
1455 | { | |
1456 | for (intf = m->HostInterfaces; intf; intf = intf->next) | |
1457 | { | |
1458 | if (intf->Advertise) DeadvertiseInterface(m, intf, kDeadvertiseFlag_NormalHostname); | |
1459 | } | |
1460 | } | |
1461 | } | |
9f221bca A |
1462 | } |
1463 | ||
f0cc3e7b | 1464 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca A |
1465 | if (!AuthRecord_uDNS(rr)) |
1466 | { | |
1467 | if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) | |
1468 | m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond)); | |
1469 | m->NumAllInterfaceRecords--; | |
f0cc3e7b A |
1470 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, |
1471 | "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S, | |
9f221bca | 1472 | m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr)); |
51601d48 | 1473 | } |
f0cc3e7b A |
1474 | #endif |
1475 | } | |
1476 | ||
1477 | mDNSlocal void AdvertiseNecessaryInterfaceRecords(mDNS *const m) | |
1478 | { | |
1479 | NetworkInterfaceInfo *intf; | |
1480 | for (intf = m->HostInterfaces; intf; intf = intf->next) | |
1481 | { | |
1482 | if (intf->Advertise) AdvertiseInterfaceIfNeeded(m, intf); | |
1483 | } | |
51601d48 A |
1484 | } |
1485 | ||
1486 | mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr) | |
1487 | { | |
f0cc3e7b | 1488 | mDNSBool enablingBonjour = mDNSfalse; |
9f221bca A |
1489 | |
1490 | if (RRLocalOnly(rr)) | |
51601d48 | 1491 | { |
9f221bca A |
1492 | // A sanity check, this should be prevented in calling code. |
1493 | LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr)); | |
1494 | return; | |
1495 | } | |
1496 | ||
f0cc3e7b | 1497 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca A |
1498 | if (!AuthRecord_uDNS(rr)) |
1499 | { | |
1500 | m->NumAllInterfaceRecords++; | |
f0cc3e7b A |
1501 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, |
1502 | "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S, | |
9f221bca A |
1503 | m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr)); |
1504 | if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) | |
1505 | { | |
1506 | m->NextBonjourDisableTime = 0; | |
1507 | if (m->BonjourEnabled == 0) | |
1508 | { | |
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; | |
f0cc3e7b | 1512 | enablingBonjour = mDNStrue; |
9f221bca A |
1513 | m->NetworkChanged = m->timenow; |
1514 | } | |
1515 | } | |
1516 | } | |
f0cc3e7b | 1517 | #endif |
51601d48 | 1518 | |
f0cc3e7b | 1519 | if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost)) |
9f221bca | 1520 | { |
f0cc3e7b A |
1521 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
1522 | if (AuthRecordIncludesAWDL(rr)) | |
1523 | { | |
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)); | |
1528 | } | |
1529 | else if (mDNSPlatformInterfaceIsAWDL(rr->resrec.InterfaceID)) | |
1530 | { | |
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)); | |
1535 | } | |
1536 | else | |
1537 | #endif | |
1538 | { | |
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)); | |
1543 | } | |
9f221bca A |
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 | |
1547 | // to do it here. | |
f0cc3e7b | 1548 | if (!enablingBonjour) AdvertiseNecessaryInterfaceRecords(m); |
51601d48 A |
1549 | } |
1550 | } | |
1551 | ||
1552 | mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr) | |
1553 | { | |
9f221bca A |
1554 | mDNSAddr laddr = zeroAddr; |
1555 | mDNSEthAddr eth = zeroEthAddr; | |
1556 | mDNSIPPort lport = zeroIPPort; | |
1557 | mDNSIPPort rport = zeroIPPort; | |
1558 | mDNSu32 timeout = 0; | |
1559 | mDNSu32 seq = 0; | |
1560 | mDNSu32 ack = 0; | |
1561 | mDNSu16 win = 0; | |
51601d48 A |
1562 | |
1563 | if (mDNS_KeepaliveRecord(&rr->resrec)) | |
1564 | { | |
1565 | mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, ð, &seq, &ack, &lport, &rport, &win); | |
1566 | if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport)) | |
1567 | { | |
1568 | LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger); | |
1569 | return; | |
1570 | } | |
1571 | } | |
1572 | } | |
1573 | ||
67c8f8a1 A |
1574 | // Exported so uDNS.c can call this |
1575 | mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr) | |
83fb1e36 A |
1576 | { |
1577 | domainname *target = GetRRDomainNameTarget(&rr->resrec); | |
1578 | AuthRecord *r; | |
1579 | AuthRecord **p = &m->ResourceRecords; | |
1580 | AuthRecord **d = &m->DuplicateRecords; | |
1581 | ||
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); } | |
1584 | ||
1585 | if (!rr->resrec.RecordType) | |
1586 | { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); } | |
1587 | ||
1588 | if (m->ShutdownTime) | |
1589 | { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); } | |
1590 | ||
1591 | if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr)) | |
1592 | { | |
1593 | mDNSInterfaceID previousID = rr->resrec.InterfaceID; | |
1594 | if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P) | |
1595 | { | |
1596 | rr->resrec.InterfaceID = mDNSInterface_LocalOnly; | |
1597 | rr->ARType = AuthRecordLocalOnly; | |
1598 | } | |
1599 | if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly) | |
1600 | { | |
1601 | NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID); | |
1602 | if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; } | |
1603 | } | |
1604 | if (rr->resrec.InterfaceID != previousID) | |
1605 | LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr)); | |
1606 | } | |
1607 | ||
1608 | if (RRLocalOnly(rr)) | |
1609 | { | |
1610 | if (CheckAuthSameRecord(&m->rrauth, rr)) | |
1611 | { | |
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); | |
1615 | } | |
1616 | } | |
1617 | else | |
1618 | { | |
1619 | while (*p && *p != rr) p=&(*p)->next; | |
1620 | if (*p) | |
1621 | { | |
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); | |
1625 | } | |
1626 | } | |
1627 | ||
1628 | while (*d && *d != rr) d=&(*d)->next; | |
1629 | if (*d) | |
1630 | { | |
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); | |
1634 | } | |
1635 | ||
1636 | if (rr->DependentOn) | |
1637 | { | |
1638 | if (rr->resrec.RecordType == kDNSRecordTypeUnique) | |
1639 | rr->resrec.RecordType = kDNSRecordTypeVerified; | |
12c5fa7a | 1640 | else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique) |
83fb1e36 | 1641 | { |
12c5fa7a | 1642 | LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique", |
83fb1e36 A |
1643 | rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); |
1644 | return(mStatus_Invalid); | |
1645 | } | |
1646 | if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique))) | |
1647 | { | |
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); | |
1651 | } | |
1652 | } | |
1653 | ||
83fb1e36 A |
1654 | rr->next = mDNSNULL; |
1655 | ||
1656 | // Field Group 1: The actual information pertaining to this resource record | |
1657 | // Set up by client prior to call | |
1658 | ||
1659 | // Field Group 2: Persistent metadata for Authoritative Records | |
9f221bca A |
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 | |
83fb1e36 A |
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; | |
1671 | ||
1672 | // Field Group 3: Transient state for Authoritative Records | |
1673 | rr->Acknowledged = mDNSfalse; | |
1674 | rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType); | |
51601d48 | 1675 | rr->ProbeRestartCount = 0; |
83fb1e36 A |
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); | |
9f221bca A |
1691 | // rr->LastAPTime = Set for us in InitializeLastAPTime() |
1692 | // rr->LastMCTime = Set for us in InitializeLastAPTime() | |
1693 | // rr->LastMCInterface = Set for us in InitializeLastAPTime() | |
83fb1e36 A |
1694 | rr->NewRData = mDNSNULL; |
1695 | rr->newrdlength = 0; | |
1696 | rr->UpdateCallback = mDNSNULL; | |
1697 | rr->UpdateCredits = kMaxUpdateCredits; | |
1698 | rr->NextUpdateCredit = 0; | |
1699 | rr->UpdateBlocked = 0; | |
1700 | ||
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; | |
1703 | ||
1704 | // Field Group 4: Transient uDNS state for Authoritative Records | |
1705 | rr->state = regState_Zero; | |
1706 | rr->uselease = 0; | |
1707 | rr->expire = 0; | |
1708 | rr->Private = 0; | |
1709 | rr->updateid = zeroID; | |
1710 | rr->updateIntID = zeroOpaque64; | |
1711 | rr->zone = rr->resrec.name; | |
1712 | rr->nta = mDNSNULL; | |
1713 | rr->tcp = mDNSNULL; | |
1714 | rr->OrigRData = 0; | |
1715 | rr->OrigRDLen = 0; | |
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; | |
67c8f8a1 | 1725 | |
9f221bca A |
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 | |
6528fe3e | 1732 | |
83fb1e36 A |
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; } | |
263eeeab | 1737 | |
83fb1e36 A |
1738 | if (rr->AutoTarget) |
1739 | { | |
1740 | SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime(); | |
263eeeab | 1741 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
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) | |
1745 | { | |
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)); | |
1750 | } | |
263eeeab | 1751 | #endif |
83fb1e36 A |
1752 | } |
1753 | else | |
1754 | { | |
1755 | rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse); | |
1756 | rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue); | |
1757 | } | |
1758 | ||
1759 | if (!ValidateDomainName(rr->resrec.name)) | |
1760 | { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); } | |
1761 | ||
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); } | |
1765 | ||
1766 | rr->resrec.namehash = DomainNameHashValue(rr->resrec.name); | |
1767 | rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec); | |
1768 | ||
1769 | if (RRLocalOnly(rr)) | |
1770 | { | |
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. | |
9f221bca | 1776 | // This comment is doesn’t make any sense. -- SC |
83fb1e36 A |
1777 | if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) |
1778 | { | |
1779 | if (CheckAuthRecordConflict(&m->rrauth, rr)) | |
1780 | { | |
1781 | LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID); | |
1782 | return mStatus_NameConflict; | |
1783 | } | |
1784 | } | |
1785 | } | |
1786 | ||
1787 | // For uDNS records, we don't support duplicate checks at this time. | |
263eeeab | 1788 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
1789 | if (AuthRecord_uDNS(rr)) |
1790 | { | |
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. | |
83fb1e36 A |
1794 | while (*p) p=&(*p)->next; |
1795 | *p = rr; | |
1796 | if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified; | |
1797 | rr->ProbeCount = 0; | |
51601d48 | 1798 | rr->ProbeRestartCount = 0; |
83fb1e36 A |
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 | |
1802 | } | |
263eeeab A |
1803 | #endif |
1804 | ||
83fb1e36 A |
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)) | |
1807 | { | |
1808 | rr->ProbeCount = 0; | |
51601d48 | 1809 | rr->ProbeRestartCount = 0; |
83fb1e36 A |
1810 | rr->AnnounceCount = 0; |
1811 | r = CheckAuthIdenticalRecord(&m->rrauth, rr); | |
1812 | } | |
1813 | else | |
1814 | { | |
1815 | for (r = m->ResourceRecords; r; r=r->next) | |
1816 | if (RecordIsLocalDuplicate(r, rr)) | |
1817 | { | |
1818 | if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0; | |
1819 | else break; | |
1820 | } | |
1821 | } | |
1822 | ||
1823 | if (r) | |
1824 | { | |
9f221bca | 1825 | LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr)); |
83fb1e36 A |
1826 | *d = 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) | |
1832 | rr->ProbeCount = 0; | |
1833 | } | |
1834 | else | |
1835 | { | |
9f221bca | 1836 | LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr)); |
83fb1e36 A |
1837 | if (RRLocalOnly(rr)) |
1838 | { | |
1839 | AuthGroup *ag; | |
1840 | ag = InsertAuthRecord(m, &m->rrauth, rr); | |
9f221bca A |
1841 | if (ag && !ag->NewLocalOnlyRecords) |
1842 | { | |
83fb1e36 A |
1843 | m->NewLocalOnlyRecords = mDNStrue; |
1844 | ag->NewLocalOnlyRecords = rr; | |
1845 | } | |
9f221bca | 1846 | // No probing for LocalOnly records; acknowledge them right away |
83fb1e36 A |
1847 | if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified; |
1848 | AcknowledgeRecord(m, rr); | |
1849 | return(mStatus_NoError); | |
1850 | } | |
1851 | else | |
1852 | { | |
1853 | if (!m->NewLocalRecords) m->NewLocalRecords = rr; | |
1854 | *p = rr; | |
1855 | } | |
1856 | } | |
1857 | ||
9f221bca A |
1858 | if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above |
1859 | { | |
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); | |
1862 | ||
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); | |
1866 | ||
1867 | // Adding a record may affect whether or not we should sleep | |
1868 | mDNS_UpdateAllowSleep(m); | |
1869 | } | |
1870 | ||
1871 | // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host. | |
51601d48 | 1872 | // This is used by the in-NIC proxy to send the keepalive packets. |
9f221bca | 1873 | if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec)) |
51601d48 | 1874 | { |
9f221bca | 1875 | mDNSAddr raddr; |
51601d48 A |
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; | |
51601d48 A |
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 | |
12c5fa7a | 1883 | mDNSPlatformGetRemoteMacAddr(&raddr); |
51601d48 A |
1884 | } |
1885 | ||
83fb1e36 A |
1886 | return(mStatus_NoError); |
1887 | } | |
6528fe3e | 1888 | |
c9b9ae52 | 1889 | mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr) |
83fb1e36 A |
1890 | { |
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) | |
1901 | { | |
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)); | |
1905 | } | |
1906 | } | |
8e92c31c A |
1907 | |
1908 | mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr) | |
83fb1e36 A |
1909 | { |
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 | |
1916 | } | |
c9b9ae52 | 1917 | |
32bb7e43 | 1918 | // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list. |
6528fe3e | 1919 | // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. |
67c8f8a1 A |
1920 | // Exported so uDNS.c can call this |
1921 | mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt) | |
83fb1e36 A |
1922 | { |
1923 | AuthRecord *r2; | |
1924 | mDNSu8 RecordType = rr->resrec.RecordType; | |
1925 | AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records | |
1926 | mDNSBool dupList = mDNSfalse; | |
1927 | ||
1928 | if (RRLocalOnly(rr)) | |
1929 | { | |
1930 | AuthGroup *a; | |
83fb1e36 | 1931 | AuthRecord **rp; |
83fb1e36 | 1932 | |
12c5fa7a | 1933 | a = AuthGroupForRecord(&m->rrauth, &rr->resrec); |
83fb1e36 | 1934 | if (!a) return mDNSfalse; |
9f221bca | 1935 | rp = &a->members; |
83fb1e36 A |
1936 | while (*rp && *rp != rr) rp=&(*rp)->next; |
1937 | p = rp; | |
1938 | } | |
1939 | else | |
1940 | { | |
1941 | while (*p && *p != rr) p=&(*p)->next; | |
1942 | } | |
1943 | ||
1944 | if (*p) | |
1945 | { | |
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 | |
1948 | { | |
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; | |
1952 | } | |
1953 | else | |
1954 | { | |
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; | |
1959 | if (*d) | |
1960 | { | |
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)) | |
1966 | { | |
1967 | dup->next = mDNSNULL; | |
1968 | if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup)); | |
1969 | } | |
1970 | else | |
1971 | { | |
1972 | dup->next = rr->next; // And then... | |
1973 | rr->next = dup; // ... splice it in right after the record we're about to delete | |
1974 | } | |
1975 | dup->resrec.RecordType = rr->resrec.RecordType; | |
1976 | dup->ProbeCount = rr->ProbeCount; | |
51601d48 | 1977 | dup->ProbeRestartCount = rr->ProbeRestartCount; |
83fb1e36 A |
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; | |
1994 | } | |
1995 | } | |
1996 | } | |
1997 | else | |
1998 | { | |
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 | |
2003 | if (*p) | |
2004 | { | |
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 | |
2010 | // details. | |
51601d48 | 2011 | rr->WakeUp.HMAC = zeroEthAddr; |
83fb1e36 | 2012 | rr->RequireGoodbye = mDNSfalse; |
51601d48 | 2013 | rr->resrec.RecordType = kDNSRecordTypeDeregistering; |
83fb1e36 A |
2014 | dupList = mDNStrue; |
2015 | } | |
2016 | if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)", | |
2017 | rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); | |
2018 | } | |
2019 | ||
2020 | if (!*p) | |
2021 | { | |
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); | |
2026 | } | |
2027 | ||
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 | |
2030 | ||
2031 | // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then | |
f0cc3e7b | 2032 | // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe. |
83fb1e36 A |
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. | |
2041 | ||
67c8f8a1 | 2042 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
2043 | if (AuthRecord_uDNS(rr)) |
2044 | { | |
2045 | if (rr->RequireGoodbye) | |
2046 | { | |
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); | |
2056 | } | |
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 | |
f0cc3e7b | 2059 | // state here. |
83fb1e36 A |
2060 | rr->updateid = zeroID; |
2061 | ||
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) | |
2070 | { | |
2071 | mDNS_StopNATOperation_internal(m, &rr->NATinfo); | |
2072 | rr->NATinfo.clientContext = mDNSNULL; | |
2073 | } | |
2074 | if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; } | |
2075 | if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; } | |
2076 | } | |
32bb7e43 | 2077 | #endif // UNICAST_DISABLED |
67c8f8a1 | 2078 | |
83fb1e36 A |
2079 | if (RecordType == kDNSRecordTypeUnregistered) |
2080 | LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr)); | |
2081 | else if (RecordType == kDNSRecordTypeDeregistering) | |
2082 | { | |
2083 | LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr)); | |
2084 | return(mStatus_BadReferenceErr); | |
2085 | } | |
2086 | ||
83fb1e36 | 2087 | if (rr->WakeUp.HMAC.l[0] || |
f0cc3e7b A |
2088 | (((RecordType == kDNSRecordTypeShared) || (rr->ARType == AuthRecordLocalOnly)) && |
2089 | (rr->RequireGoodbye || rr->AnsweredLocalQ))) | |
83fb1e36 A |
2090 | { |
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); | |
2100 | } | |
2101 | else | |
2102 | { | |
2103 | if (!dupList && RRLocalOnly(rr)) | |
2104 | { | |
2105 | AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr); | |
2106 | if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next; | |
2107 | } | |
2108 | else | |
2109 | { | |
2110 | *p = rr->next; // Cut this record from the list | |
2111 | if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next; | |
51601d48 | 2112 | DecrementAutoTargetServices(m, rr); |
83fb1e36 A |
2113 | } |
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; | |
2117 | ||
83fb1e36 A |
2118 | verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr)); |
2119 | rr->resrec.RecordType = kDNSRecordTypeUnregistered; | |
2120 | ||
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)); | |
2124 | ||
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 | |
2127 | ||
2128 | ||
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) | |
2134 | { | |
2135 | mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback | |
9f221bca | 2136 | LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr)); |
83fb1e36 A |
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 | |
2140 | } | |
2141 | else | |
2142 | { | |
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; | |
2152 | while (r2) | |
2153 | { | |
2154 | if (r2->ProbeCount != 0xFF) | |
2155 | { | |
2156 | r2 = r2->next; | |
2157 | } | |
2158 | else | |
2159 | { | |
f0cc3e7b | 2160 | #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) |
9f221bca A |
2161 | // See if this record was also registered with any D2D plugins. |
2162 | D2D_stop_advertising_record(r2); | |
2163 | #endif | |
83fb1e36 A |
2164 | mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict); |
2165 | // As this is a duplicate record, it will be unlinked from the list | |
2166 | // immediately | |
2167 | r2 = m->DuplicateRecords; | |
2168 | } | |
2169 | } | |
2170 | } | |
2171 | } | |
2172 | mDNS_UpdateAllowSleep(m); | |
2173 | return(mStatus_NoError); | |
2174 | } | |
6528fe3e A |
2175 | |
2176 | // *************************************************************************** | |
c9b9ae52 | 2177 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e | 2178 | #pragma mark - |
6528fe3e A |
2179 | #pragma mark - Packet Sending Functions |
2180 | #endif | |
2181 | ||
7f0064bd | 2182 | mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add) |
83fb1e36 A |
2183 | { |
2184 | if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse) | |
2185 | { | |
2186 | **nrpp = rr; | |
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; | |
2193 | } | |
2194 | debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); | |
2195 | } | |
7f0064bd | 2196 | |
12c5fa7a A |
2197 | mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID) |
2198 | { | |
2199 | AuthRecord *rr2; | |
2200 | if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask) | |
2201 | { | |
2202 | for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next) | |
2203 | { | |
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)) | |
2211 | { | |
2212 | AddRecordToResponseList(nrpp, rr2, rr); | |
2213 | } | |
2214 | } | |
2215 | } | |
2216 | } | |
2217 | ||
7f0064bd | 2218 | mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID) |
83fb1e36 A |
2219 | { |
2220 | AuthRecord *rr, *rr2; | |
2221 | for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put | |
2222 | { | |
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)) | |
12c5fa7a | 2226 | { |
83fb1e36 | 2227 | AddRecordToResponseList(nrpp, rr->Additional1, rr); |
12c5fa7a A |
2228 | AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID); |
2229 | } | |
83fb1e36 A |
2230 | |
2231 | if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID)) | |
12c5fa7a | 2232 | { |
83fb1e36 | 2233 | AddRecordToResponseList(nrpp, rr->Additional2, rr); |
12c5fa7a A |
2234 | AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID); |
2235 | } | |
83fb1e36 A |
2236 | |
2237 | // For SRV records, automatically add the Address record(s) for the target host | |
2238 | if (rr->resrec.rrtype == kDNSType_SRV) | |
2239 | { | |
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); | |
2246 | } | |
2247 | else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional | |
2248 | { | |
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); | |
2255 | } | |
2256 | else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record | |
2257 | { | |
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); | |
2261 | } | |
2262 | } | |
2263 | } | |
7f0064bd A |
2264 | |
2265 | mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID) | |
83fb1e36 A |
2266 | { |
2267 | AuthRecord *rr; | |
2268 | AuthRecord *ResponseRecords = mDNSNULL; | |
2269 | AuthRecord **nrp = &ResponseRecords; | |
2270 | NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); | |
2271 | ||
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) | |
2274 | { | |
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; | |
2280 | ||
2281 | if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID) | |
2282 | { | |
2283 | if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) || | |
2284 | (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6))) | |
2285 | { | |
2286 | rr->ImmedAnswer = mDNSNULL; // Clear the state fields | |
2287 | rr->ImmedUnicast = mDNSfalse; | |
2288 | rr->v4Requester = zerov4Addr; | |
2289 | rr->v6Requester = zerov6Addr; | |
2290 | ||
2291 | // Only sent records registered for P2P over P2P interfaces | |
9f221bca | 2292 | if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)) |
83fb1e36 | 2293 | { |
83fb1e36 A |
2294 | continue; |
2295 | } | |
2296 | ||
2297 | if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo | |
51601d48 A |
2298 | { |
2299 | rr->NR_AnswerTo = NR_AnswerMulticast; | |
2300 | *nrp = rr; | |
2301 | nrp = &rr->NextResponse; | |
2302 | } | |
83fb1e36 A |
2303 | } |
2304 | } | |
2305 | } | |
2306 | ||
2307 | AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID); | |
2308 | ||
2309 | while (ResponseRecords) | |
2310 | { | |
2311 | mDNSu8 *responseptr = m->omsg.data; | |
2312 | mDNSu8 *newptr; | |
2313 | InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags); | |
2314 | ||
2315 | // Put answers in the packet | |
2316 | while (ResponseRecords && ResponseRecords->NR_AnswerTo) | |
2317 | { | |
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 | |
51601d48 | 2321 | |
f0cc3e7b | 2322 | newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec); |
51601d48 | 2323 | |
83fb1e36 | 2324 | rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state |
51601d48 A |
2325 | if (!newptr && m->omsg.h.numAnswers) |
2326 | { | |
2327 | break; // If packet full, send it now | |
2328 | } | |
83fb1e36 A |
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; | |
2335 | } | |
2336 | ||
2337 | // Add additionals, if there's space | |
2338 | while (ResponseRecords && !ResponseRecords->NR_AnswerTo) | |
2339 | { | |
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 | |
2345 | ||
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; | |
2353 | } | |
2354 | ||
2355 | if (m->omsg.h.numAnswers) | |
f0cc3e7b | 2356 | mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSfalse); |
83fb1e36 A |
2357 | } |
2358 | } | |
7f0064bd | 2359 | |
263eeeab A |
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 | |
67c8f8a1 | 2362 | mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr) |
83fb1e36 A |
2363 | { |
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; | |
f0cc3e7b | 2370 | if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; } |
83fb1e36 A |
2371 | mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this |
2372 | } | |
6528fe3e | 2373 | |
263eeeab A |
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. | |
6528fe3e | 2378 | // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. |
c9b9ae52 | 2379 | mDNSlocal void DiscardDeregistrations(mDNS *const m) |
83fb1e36 A |
2380 | { |
2381 | if (m->CurrentRecord) | |
2382 | LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); | |
2383 | m->CurrentRecord = m->ResourceRecords; | |
2384 | ||
2385 | while (m->CurrentRecord) | |
2386 | { | |
2387 | AuthRecord *rr = m->CurrentRecord; | |
2388 | if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering) | |
2389 | CompleteDeregistration(m, rr); // Don't touch rr after this | |
2390 | else | |
2391 | m->CurrentRecord = rr->next; | |
2392 | } | |
2393 | } | |
6528fe3e | 2394 | |
32bb7e43 | 2395 | mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst) |
83fb1e36 A |
2396 | { |
2397 | int i, val = 0; | |
2398 | if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid); | |
2399 | for (i=1; i<=src[0]; i++) | |
2400 | { | |
2401 | if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid); | |
2402 | val = val * 10 + src[i] - '0'; | |
2403 | } | |
2404 | if (val > 255) return(mStatus_Invalid); | |
2405 | *dst = (mDNSu8)val; | |
2406 | return(mStatus_NoError); | |
2407 | } | |
716635cc | 2408 | |
32bb7e43 | 2409 | mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name) |
83fb1e36 A |
2410 | { |
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); | |
2419 | } | |
c9b9ae52 | 2420 | |
32bb7e43 | 2421 | #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \ |
83fb1e36 A |
2422 | ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \ |
2423 | ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1) | |
32bb7e43 A |
2424 | |
2425 | mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name) | |
83fb1e36 A |
2426 | { |
2427 | int i, h, l; | |
2428 | const domainname *n; | |
6528fe3e | 2429 | |
83fb1e36 A |
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; } | |
c9b9ae52 | 2432 | |
83fb1e36 A |
2433 | n = SkipLeadingLabels(name, skip); |
2434 | for (i=0; i<16; i++) | |
2435 | { | |
2436 | if (n->c[0] != 1) return mStatus_Invalid; | |
2437 | l = HexVal(n->c[1]); | |
2438 | n = (const domainname *)(n->c + 2); | |
32bb7e43 | 2439 | |
83fb1e36 A |
2440 | if (n->c[0] != 1) return mStatus_Invalid; |
2441 | h = HexVal(n->c[1]); | |
2442 | n = (const domainname *)(n->c + 2); | |
32bb7e43 | 2443 | |
83fb1e36 A |
2444 | if (l<0 || h<0) return mStatus_Invalid; |
2445 | a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l); | |
2446 | } | |
32bb7e43 | 2447 | |
83fb1e36 A |
2448 | a->type = mDNSAddrType_IPv6; |
2449 | return(mStatus_NoError); | |
2450 | } | |
32bb7e43 A |
2451 | |
2452 | mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name) | |
83fb1e36 A |
2453 | { |
2454 | int skip = CountLabels(name) - 2; | |
2455 | if (skip >= 0) | |
2456 | { | |
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; | |
2460 | } | |
2461 | return(mDNSAddrType_None); | |
2462 | } | |
32bb7e43 A |
2463 | |
2464 | mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr, | |
83fb1e36 A |
2465 | const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst) |
2466 | { | |
2467 | int i; | |
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; } | |
32bb7e43 | 2471 | |
83fb1e36 A |
2472 | // 0x00 Destination address |
2473 | for (i=0; i<6; i++) *ptr++ = dst->b[i]; | |
32bb7e43 | 2474 | |
83fb1e36 A |
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]; | |
32bb7e43 | 2477 | |
83fb1e36 A |
2478 | // 0x0C ARP Ethertype (0x0806) |
2479 | *ptr++ = 0x08; *ptr++ = 0x06; | |
32bb7e43 | 2480 | |
83fb1e36 A |
2481 | // 0x0E ARP header |
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 | |
32bb7e43 | 2487 | |
83fb1e36 A |
2488 | // 0x16 Sender hardware address (our MAC address) |
2489 | for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i]; | |
32bb7e43 | 2490 | |
83fb1e36 A |
2491 | // 0x1C Sender protocol address |
2492 | for (i=0; i<4; i++) *ptr++ = spa->b[i]; | |
32bb7e43 | 2493 | |
83fb1e36 A |
2494 | // 0x20 Target hardware address |
2495 | for (i=0; i<6; i++) *ptr++ = tha->b[i]; | |
32bb7e43 | 2496 | |
83fb1e36 A |
2497 | // 0x26 Target protocol address |
2498 | for (i=0; i<4; i++) *ptr++ = tpa->b[i]; | |
32bb7e43 | 2499 | |
83fb1e36 A |
2500 | // 0x2A Total ARP Packet length 42 bytes |
2501 | mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID); | |
2502 | } | |
32bb7e43 | 2503 | |
263eeeab | 2504 | mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum) |
83fb1e36 A |
2505 | { |
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); | |
2511 | } | |
263eeeab A |
2512 | |
2513 | mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length) | |
83fb1e36 A |
2514 | { |
2515 | IPv6PseudoHeader ph; | |
2516 | ph.src = *src; | |
2517 | ph.dst = *dst; | |
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; | |
2522 | ph.pro.b[0] = 0; | |
2523 | ph.pro.b[1] = 0; | |
2524 | ph.pro.b[2] = 0; | |
2525 | ph.pro.b[3] = protocol; | |
2526 | return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0)); | |
2527 | } | |
263eeeab A |
2528 | |
2529 | mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr, | |
83fb1e36 A |
2530 | const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst) |
2531 | { | |
2532 | int i; | |
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; } | |
2542 | ||
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: | |
2550 | // *ptr++ = 0x33; | |
2551 | // *ptr++ = 0x33; | |
2552 | // *ptr++ = 0xFF; | |
2553 | // *ptr++ = tpa->b[0xD]; | |
2554 | // *ptr++ = tpa->b[0xE]; | |
2555 | // *ptr++ = tpa->b[0xF]; | |
2556 | ||
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]; | |
2559 | ||
2560 | // 0x0C IPv6 Ethertype (0x86DD) | |
2561 | *ptr++ = 0x86; *ptr++ = 0xDD; | |
2562 | ||
2563 | // 0x0E IPv6 header | |
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 | |
2568 | ||
2569 | // 0x16 Sender IPv6 address | |
2570 | for (i=0; i<16; i++) *ptr++ = spa->b[i]; | |
2571 | ||
2572 | // 0x26 Destination IPv6 address | |
2573 | for (i=0; i<16; i++) *ptr++ = v6dst->b[i]; | |
2574 | ||
2575 | // 0x36 NDP header | |
2576 | *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement | |
2577 | *ptr++ = 0x00; // Code | |
2578 | *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39) | |
2579 | *ptr++ = flags; | |
2580 | *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; | |
2581 | ||
2582 | if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek. | |
2583 | { | |
2584 | // 0x3E NDP target. | |
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)) | |
2592 | { | |
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]; | |
2596 | } | |
2597 | } | |
2598 | else // Neighbor Advertisement. The NDP "target" is the address we're giving information about. | |
2599 | { | |
2600 | // 0x3E NDP target. | |
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]; | |
2606 | } | |
2607 | ||
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]; | |
2613 | ||
2614 | mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID); | |
2615 | } | |
263eeeab | 2616 | |
51601d48 A |
2617 | mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace) |
2618 | { | |
e0b1690f A |
2619 | mDNSu32 DNS_VERS = _DNS_SD_H; |
2620 | Trace->u.tracer.platf = m->mDNS_plat; | |
2621 | Trace->u.tracer.mDNSv = DNS_VERS; | |
51601d48 A |
2622 | |
2623 | Trace->opt = kDNSOpt_Trace; | |
2624 | Trace->optlen = DNSOpt_TraceData_Space - 4; | |
2625 | } | |
2626 | ||
32bb7e43 | 2627 | mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner) |
83fb1e36 A |
2628 | { |
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; | |
2634 | ||
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; | |
2639 | } | |
32bb7e43 A |
2640 | |
2641 | mDNSlocal void GrantUpdateCredit(AuthRecord *rr) | |
83fb1e36 A |
2642 | { |
2643 | if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0; | |
2644 | else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval); | |
2645 | } | |
32bb7e43 | 2646 | |
51601d48 A |
2647 | mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr) |
2648 | { | |
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)) | |
2655 | { | |
2656 | debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr)); | |
2657 | return mDNStrue; | |
2658 | } | |
2659 | ||
2660 | if (m->SleepState != SleepState_Sleeping) | |
2661 | return mDNSfalse; | |
2662 | ||
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) | |
2666 | { | |
2667 | debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID); | |
2668 | return mDNSfalse; | |
2669 | } | |
2670 | else | |
2671 | { | |
2672 | debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID); | |
2673 | return mDNStrue; | |
2674 | } | |
2675 | } | |
2676 | ||
32bb7e43 A |
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. | |
2689 | ||
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) | |
83fb1e36 A |
2694 | { |
2695 | int pktcount = 0; | |
2696 | AuthRecord *rr, *r2; | |
2697 | mDNSs32 maxExistingAnnounceInterval = 0; | |
2698 | const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces); | |
2699 | ||
12c5fa7a | 2700 | m->NextScheduledResponse = m->timenow + FutureTime; |
83fb1e36 A |
2701 | |
2702 | if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m); | |
2703 | ||
2704 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
2705 | if (rr->ImmedUnicast) | |
2706 | { | |
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) | |
2714 | { | |
2715 | LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr)); | |
2716 | rr->ImmedUnicast = mDNSfalse; | |
2717 | } | |
2718 | } | |
2719 | ||
2720 | // *** | |
2721 | // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on | |
2722 | // *** | |
2723 | ||
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) | |
2726 | { | |
2727 | while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr); | |
2728 | if (TimeToAnnounceThisRecord(rr, m->timenow)) | |
2729 | { | |
2730 | if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) | |
2731 | { | |
2732 | if (!rr->WakeUp.HMAC.l[0]) | |
2733 | { | |
2734 | if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces | |
2735 | } | |
2736 | else | |
2737 | { | |
9f221bca | 2738 | mDNSBool unicastOnly; |
83fb1e36 | 2739 | LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); |
9f221bca A |
2740 | unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse; |
2741 | SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly); | |
83fb1e36 | 2742 | for (r2 = rr; r2; r2=r2->next) |
9f221bca A |
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)) | |
83fb1e36 A |
2745 | { |
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) | |
2749 | { | |
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); | |
2753 | } | |
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; | |
2757 | } | |
2758 | } | |
2759 | } | |
2760 | else if (ResourceRecordIsValidAnswer(rr)) | |
2761 | { | |
2762 | if (rr->AddressProxy.type) | |
2763 | { | |
51601d48 | 2764 | if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC)) |
83fb1e36 | 2765 | { |
51601d48 A |
2766 | rr->AnnounceCount--; |
2767 | rr->ThisAPInterval *= 2; | |
2768 | rr->LastAPTime = m->timenow; | |
2769 | if (rr->AddressProxy.type == mDNSAddrType_IPv4) | |
2770 | { | |
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); | |
2774 | } | |
2775 | else if (rr->AddressProxy.type == mDNSAddrType_IPv6) | |
2776 | { | |
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); | |
2780 | } | |
83fb1e36 A |
2781 | } |
2782 | } | |
2783 | else | |
2784 | { | |
2785 | rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces | |
2786 | if (maxExistingAnnounceInterval < rr->ThisAPInterval) | |
2787 | maxExistingAnnounceInterval = rr->ThisAPInterval; | |
2788 | if (rr->UpdateBlocked) rr->UpdateBlocked = 0; | |
2789 | } | |
2790 | } | |
2791 | } | |
2792 | } | |
2793 | ||
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 | |
2803 | ||
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) | |
2809 | { | |
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)) | |
2824 | { | |
2825 | if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer; | |
2826 | else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark; | |
2827 | } | |
2828 | } | |
2829 | ||
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) | |
2838 | { | |
2839 | if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked | |
2840 | { | |
2841 | for (r2 = m->ResourceRecords; r2; r2=r2->next) | |
9f221bca A |
2842 | { |
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))) | |
2847 | { | |
2848 | r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark; | |
2849 | } | |
2850 | } | |
83fb1e36 A |
2851 | } |
2852 | else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked | |
2853 | { | |
2854 | for (r2 = m->ResourceRecords; r2; r2=r2->next) | |
9f221bca A |
2855 | { |
2856 | if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) && | |
2857 | (r2->ImmedAdditional != rr->ImmedAdditional) && | |
2858 | SameResourceRecordSignature(r2, rr) && | |
2859 | IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional)) | |
2860 | { | |
2861 | r2->ImmedAdditional = rr->ImmedAdditional; | |
2862 | } | |
2863 | } | |
83fb1e36 A |
2864 | } |
2865 | } | |
2866 | ||
2867 | // Now set SendRNow state appropriately | |
2868 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
2869 | { | |
2870 | if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces | |
2871 | { | |
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; | |
9f221bca | 2876 | rr->ProbeRestartCount = 0; // Reset the probe restart count |
83fb1e36 A |
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)) | |
2879 | { | |
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); | |
2885 | } | |
2886 | } | |
2887 | else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface: | |
2888 | { | |
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; | |
2893 | } | |
2894 | SetNextAnnounceProbeTime(m, rr); | |
2895 | //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr)); | |
2896 | } | |
2897 | ||
2898 | // *** | |
2899 | // *** 2. Loop through interface list, sending records as appropriate | |
2900 | // *** | |
2901 | ||
2902 | while (intf) | |
2903 | { | |
51601d48 A |
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; | |
83fb1e36 A |
2906 | int numDereg = 0; |
2907 | int numAnnounce = 0; | |
2908 | int numAnswer = 0; | |
2909 | mDNSu8 *responseptr = m->omsg.data; | |
2910 | mDNSu8 *newptr; | |
2911 | InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags); | |
2912 | ||
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) | |
2918 | { | |
2919 | ||
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) && | |
9f221bca | 2923 | ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))) |
83fb1e36 | 2924 | { |
83fb1e36 A |
2925 | rr->SendRNow = GetNextActiveInterfaceID(intf); |
2926 | } | |
2927 | else if (rr->SendRNow == intf->InterfaceID) | |
2928 | { | |
2929 | RData *OldRData = rr->resrec.rdata; | |
2930 | mDNSu16 oldrdlength = rr->resrec.rdlength; | |
2931 | mDNSu8 active = (mDNSu8) | |
51601d48 | 2932 | (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr)); |
83fb1e36 A |
2933 | newptr = mDNSNULL; |
2934 | if (rr->NewRData && active) | |
2935 | { | |
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) | |
2938 | { | |
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 | |
2942 | } | |
2943 | SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); | |
2944 | } | |
2945 | ||
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 | |
2950 | if (newptr) | |
2951 | { | |
2952 | responseptr = newptr; | |
2953 | rr->RequireGoodbye = active; | |
2954 | if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++; | |
2955 | else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++; | |
2956 | } | |
2957 | ||
2958 | if (rr->NewRData && active) | |
2959 | SetNewRData(&rr->resrec, OldRData, oldrdlength); | |
2960 | ||
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; | |
2965 | ||
2966 | if (newptr) // If succeeded in sending, advance to next interface | |
2967 | { | |
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); | |
2971 | else | |
2972 | rr->SendRNow = mDNSNULL; | |
2973 | } | |
2974 | } | |
2975 | } | |
2976 | ||
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)) | |
2982 | { | |
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); | |
2985 | ||
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)) | |
2990 | { | |
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; } | |
2996 | } | |
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 | |
3000 | { | |
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; | |
3005 | ||
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 | |
3010 | if (newptr) | |
3011 | { | |
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; | |
3021 | } | |
3022 | } | |
3023 | } | |
3024 | ||
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) | |
3031 | { | |
3032 | AuthRecord nsec; | |
3033 | mDNSu8 *ptr; | |
3034 | int len; | |
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) | |
3043 | { | |
3044 | mDNSPlatformMemZero(ptr, nsec.resrec.rdlength); | |
3045 | AssignDomainName((domainname *)ptr, rr->resrec.name); | |
3046 | ptr += len; | |
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)) | |
3051 | { | |
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); | |
3054 | } | |
3055 | newptr = responseptr; | |
3056 | if (!r2) // If we successfully built our NSEC record, add it to the packet now | |
3057 | { | |
3058 | newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec); | |
3059 | if (newptr) responseptr = newptr; | |
3060 | } | |
3061 | } | |
3062 | else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength); | |
3063 | ||
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) | |
3067 | { | |
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; | |
3074 | } | |
3075 | } | |
3076 | ||
3077 | if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals) | |
3078 | { | |
51601d48 A |
3079 | // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet |
3080 | if (OwnerRecordSpace || TraceRecordSpace) | |
83fb1e36 A |
3081 | { |
3082 | AuthRecord opt; | |
3083 | mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); | |
3084 | opt.resrec.rrclass = NormalMaxDNSMessageData; | |
51601d48 | 3085 | opt.resrec.rdlength = sizeof(rdataOPT); |
83fb1e36 | 3086 | opt.resrec.rdestimate = sizeof(rdataOPT); |
51601d48 A |
3087 | if (OwnerRecordSpace && TraceRecordSpace) |
3088 | { | |
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]); | |
3093 | } | |
3094 | else if (OwnerRecordSpace) | |
3095 | { | |
3096 | SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]); | |
3097 | } | |
3098 | else if (TraceRecordSpace) | |
3099 | { | |
3100 | SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]); | |
3101 | } | |
83fb1e36 | 3102 | newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec); |
9f221bca A |
3103 | if (newptr) |
3104 | { | |
3105 | responseptr = newptr; | |
51601d48 | 3106 | } |
83fb1e36 | 3107 | else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1) |
51601d48 A |
3108 | { |
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)); | |
3111 | } | |
83fb1e36 | 3112 | else |
51601d48 A |
3113 | { |
3114 | LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", | |
83fb1e36 | 3115 | m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); |
51601d48 | 3116 | } |
83fb1e36 | 3117 | } |
9f221bca | 3118 | |
83fb1e36 A |
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); | |
3124 | ||
f0cc3e7b A |
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); | |
83fb1e36 A |
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. | |
3130 | } | |
3131 | else // Nothing more to send on this interface; go to next | |
3132 | { | |
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); | |
3137 | #endif | |
3138 | intf = next; | |
3139 | pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it | |
3140 | } | |
3141 | } | |
3142 | ||
3143 | // *** | |
3144 | // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables | |
3145 | // *** | |
3146 | ||
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) | |
3151 | { | |
3152 | rr = m->CurrentRecord; | |
3153 | m->CurrentRecord = rr->next; | |
3154 | ||
3155 | if (rr->SendRNow) | |
3156 | { | |
3157 | if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P) | |
b8d5688b | 3158 | LogInfo("SendResponses: No active interface %d to send: %d %02X %s", |
f0cc3e7b | 3159 | IIDPrintable(rr->SendRNow), IIDPrintable(rr->resrec.InterfaceID), rr->resrec.RecordType, ARDisplayString(m, rr)); |
83fb1e36 A |
3160 | rr->SendRNow = mDNSNULL; |
3161 | } | |
3162 | ||
3163 | if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering) | |
3164 | { | |
3165 | if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client | |
3166 | ||
3167 | if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0) | |
3168 | { | |
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 | |
3171 | } | |
3172 | else | |
3173 | { | |
3174 | rr->ImmedAnswer = mDNSNULL; | |
3175 | rr->ImmedUnicast = mDNSfalse; | |
3176 | rr->v4Requester = zerov4Addr; | |
3177 | rr->v6Requester = zerov6Addr; | |
3178 | } | |
3179 | } | |
3180 | } | |
3181 | verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow); | |
3182 | } | |
6528fe3e | 3183 | |
c9b9ae52 A |
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 | |
030b743d A |
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). | |
f0cc3e7b A |
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) | |
c9b9ae52 | 3201 | |
f0cc3e7b | 3202 | #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR)) |
263eeeab A |
3203 | |
3204 | mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event) | |
83fb1e36 A |
3205 | { |
3206 | if (m->rrcache_nextcheck[slot] - event > 0) | |
3207 | m->rrcache_nextcheck[slot] = event; | |
3208 | if (m->NextCacheCheck - event > 0) | |
3209 | m->NextCacheCheck = event; | |
3210 | } | |
263eeeab A |
3211 | |
3212 | // Note: MUST call SetNextCacheCheckTimeForRecord any time we change: | |
c9b9ae52 A |
3213 | // rr->TimeRcvd |
3214 | // rr->resrec.rroriginalttl | |
3215 | // rr->UnansweredQueries | |
3216 | // rr->CRActiveQuestion | |
83fb1e36 A |
3217 | mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr) |
3218 | { | |
3219 | rr->NextRequiredQuery = RRExpireTime(rr); | |
3220 | ||
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) | |
3224 | { | |
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)); | |
3229 | } | |
12c5fa7a | 3230 | ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr)); |
83fb1e36 | 3231 | } |
6528fe3e | 3232 | |
67c8f8a1 A |
3233 | #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5) |
3234 | #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5) | |
3235 | #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5) | |
12c5fa7a A |
3236 | |
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)) | |
6528fe3e | 3242 | |
51601d48 | 3243 | mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval) |
83fb1e36 A |
3244 | { |
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; | |
3249 | ||
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)) | |
3252 | { | |
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 | |
12c5fa7a | 3256 | if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime); |
83fb1e36 A |
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); | |
3261 | } | |
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); | |
3265 | } | |
6528fe3e | 3266 | |
c9b9ae52 A |
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. | |
9f221bca A |
3270 | mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr, |
3271 | DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast) | |
83fb1e36 | 3272 | { |
9f221bca | 3273 | mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse; |
83fb1e36 A |
3274 | mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0); |
3275 | const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData; | |
f0cc3e7b | 3276 | mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit)); |
83fb1e36 A |
3277 | if (!newptr) |
3278 | { | |
3279 | debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
3280 | return(mDNSfalse); | |
3281 | } | |
3282 | else | |
3283 | { | |
f0cc3e7b | 3284 | mDNSu32 forecast = *answerforecast; |
12c5fa7a | 3285 | const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); |
f0cc3e7b | 3286 | CacheRecord *cr; |
83fb1e36 A |
3287 | CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update |
3288 | ||
f0cc3e7b A |
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 | |
83fb1e36 A |
3296 | mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1) |
3297 | { | |
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. | |
3303 | ||
f0cc3e7b A |
3304 | *ka = cr; // Link this record into our known answer chain |
3305 | ka = &cr->NextInKAList; | |
83fb1e36 | 3306 | // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n) |
f0cc3e7b | 3307 | forecast += 12 + cr->resrec.rdestimate; |
83fb1e36 A |
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) | |
3311 | { | |
83fb1e36 | 3312 | query->h.numQuestions--; |
51601d48 A |
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); | |
83fb1e36 A |
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 | |
3318 | } | |
3319 | } | |
3320 | ||
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); | |
3326 | ||
f0cc3e7b A |
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 | |
83fb1e36 | 3331 | { |
f0cc3e7b A |
3332 | cr->UnansweredQueries++; // indicate that we're expecting a response |
3333 | cr->LastUnansweredTime = m->timenow; | |
3334 | SetNextCacheCheckTimeForRecord(m, cr); | |
83fb1e36 A |
3335 | } |
3336 | ||
3337 | return(mDNStrue); | |
3338 | } | |
3339 | } | |
6528fe3e | 3340 | |
67c8f8a1 A |
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. | |
2682e09e | 3353 | mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth) |
83fb1e36 A |
3354 | { |
3355 | mDNSu32 slot; | |
2682e09e | 3356 | const CacheGroup *cg; |
83fb1e36 A |
3357 | CacheRecord *cr; |
3358 | debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c); | |
2682e09e | 3359 | if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do. |
83fb1e36 A |
3360 | FORALL_CACHERECORDS(slot, cg, cr) |
3361 | { | |
2682e09e A |
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)) | |
83fb1e36 | 3367 | { |
2682e09e | 3368 | LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth, InterfaceID, CRDisplayString(m, cr)); |
83fb1e36 A |
3369 | mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); |
3370 | if (depth < 5) | |
2682e09e | 3371 | ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1); |
83fb1e36 A |
3372 | } |
3373 | } | |
3374 | } | |
c9b9ae52 | 3375 | |
9f29194f A |
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. | |
32bb7e43 | 3380 | mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash) |
83fb1e36 | 3381 | { |
12c5fa7a | 3382 | CacheGroup *const cg = CacheGroupForName(m, namehash, name); |
83fb1e36 A |
3383 | const CacheRecord *cr = cg ? cg->members : mDNSNULL; |
3384 | while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next; | |
3385 | return(cr); | |
3386 | } | |
9f29194f | 3387 | |
51601d48 | 3388 | |
32bb7e43 | 3389 | mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1) |
83fb1e36 | 3390 | { |
51601d48 | 3391 | #ifndef SPC_DISABLED |
12c5fa7a | 3392 | CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); |
83fb1e36 A |
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, | |
f0cc3e7b | 3398 | if (SameNameCacheRecordAnswersQuestion(cr, q)) // and answers our browse query, |
83fb1e36 A |
3399 | if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service... |
3400 | { | |
3401 | mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c); | |
3402 | if (bestmetric > metric) { bestmetric = metric; bestcr = cr; } | |
3403 | } | |
3404 | return(bestcr); | |
51601d48 | 3405 | #else // SPC_DISABLED |
9f221bca A |
3406 | (void) m; |
3407 | (void) q; | |
3408 | (void) c0; | |
3409 | (void) c1; | |
3410 | (void) c1; | |
51601d48 A |
3411 | return mDNSNULL; |
3412 | #endif // SPC_DISABLED | |
83fb1e36 A |
3413 | } |
3414 | ||
9f221bca | 3415 | mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2) |
83fb1e36 A |
3416 | { |
3417 | const CacheRecord *swap_sps; | |
3418 | mDNSu32 metric1, metric2; | |
3419 | ||
9f221bca A |
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)) | |
83fb1e36 | 3424 | { |
9f221bca A |
3425 | swap_sps = *sps1; |
3426 | *sps1 = *sps2; | |
3427 | *sps2 = swap_sps; | |
83fb1e36 A |
3428 | } |
3429 | } | |
3430 | ||
3431 | mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3]) | |
3432 | { | |
9f221bca A |
3433 | CheckAndSwapSPS(&sps[0], &sps[1]); |
3434 | CheckAndSwapSPS(&sps[0], &sps[2]); | |
3435 | CheckAndSwapSPS(&sps[1], &sps[2]); | |
83fb1e36 A |
3436 | } |
3437 | ||
32bb7e43 A |
3438 | |
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]) | |
83fb1e36 A |
3441 | { |
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]); | |
3445 | ||
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); | |
3449 | } | |
32bb7e43 | 3450 | |
c9b9ae52 A |
3451 | // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active |
3452 | mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time) | |
83fb1e36 A |
3453 | { |
3454 | int i; | |
3455 | for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL; | |
3456 | } | |
c9b9ae52 A |
3457 | |
3458 | mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID) | |
83fb1e36 A |
3459 | { |
3460 | int i; | |
3461 | for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL; | |
3462 | } | |
c9b9ae52 A |
3463 | |
3464 | mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf) | |
83fb1e36 A |
3465 | { |
3466 | int i; | |
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) | |
3471 | { | |
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); | |
3475 | } | |
3476 | return(mDNSfalse); | |
3477 | } | |
c9b9ae52 | 3478 | |
9f221bca | 3479 | mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type) |
83fb1e36 A |
3480 | { |
3481 | int i, j; | |
3482 | ||
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; | |
3485 | ||
3486 | // If not, find a slot we can re-use | |
3487 | if (i >= DupSuppressInfoSize) | |
3488 | { | |
3489 | i = 0; | |
3490 | for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++) | |
3491 | if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0) | |
3492 | i = j; | |
3493 | } | |
3494 | ||
3495 | // Record the info about this query we saw | |
3496 | ds[i].Time = Time; | |
3497 | ds[i].InterfaceID = InterfaceID; | |
3498 | ds[i].Type = Type; | |
83fb1e36 | 3499 | } |
6528fe3e | 3500 | |
1f519c61 | 3501 | mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q) |
83fb1e36 A |
3502 | { |
3503 | int len, i, cnt; | |
3504 | mDNSInterfaceID InterfaceID = q->InterfaceID; | |
3505 | domainname *d = &q->qname; | |
3506 | ||
3507 | // We can't send magic packets without knowing which interface to send it on. | |
9f221bca | 3508 | if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID)) |
83fb1e36 A |
3509 | { |
3510 | LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c); | |
3511 | return; | |
3512 | } | |
3513 | ||
3514 | // Split MAC@IPAddress and pass them separately | |
3515 | len = d->c[0]; | |
83fb1e36 A |
3516 | cnt = 0; |
3517 | for (i = 1; i < len; i++) | |
3518 | { | |
3519 | if (d->c[i] == '@') | |
3520 | { | |
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 | |
3523 | if (cnt != 5) | |
3524 | { | |
3525 | LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt); | |
3526 | return; | |
3527 | } | |
3528 | if ((i - 1) > (int) (sizeof(EthAddr) - 1)) | |
3529 | { | |
3530 | LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1); | |
3531 | return; | |
3532 | } | |
3533 | if ((len - i) > (int)(sizeof(IPAddr) - 1)) | |
3534 | { | |
3535 | LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i); | |
3536 | return; | |
3537 | } | |
3538 | mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1); | |
3539 | EthAddr[i - 1] = 0; | |
3540 | mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i); | |
3541 | IPAddr[len - i] = 0; | |
51601d48 | 3542 | m->mDNSStats.WakeOnResolves++; |
12c5fa7a | 3543 | mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount); |
83fb1e36 A |
3544 | return; |
3545 | } | |
3546 | else if (d->c[i] == ':') | |
3547 | cnt++; | |
3548 | } | |
3549 | LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c); | |
3550 | } | |
3551 | ||
1f519c61 | 3552 | |
c9b9ae52 | 3553 | mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q) |
83fb1e36 A |
3554 | { |
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)) | |
3557 | return(mDNStrue); | |
3558 | ||
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)) | |
3561 | { | |
3562 | // We forecast: qname (n) type (2) class (2) | |
3563 | mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4; | |
12c5fa7a | 3564 | const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); |
f0cc3e7b A |
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 | |
83fb1e36 A |
3571 | { |
3572 | // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n) | |
f0cc3e7b | 3573 | forecast += 12 + cr->resrec.rdestimate; |
83fb1e36 A |
3574 | if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate |
3575 | } | |
3576 | return(mDNStrue); | |
3577 | } | |
3578 | ||
3579 | return(mDNSfalse); | |
3580 | } | |
6528fe3e A |
3581 | |
3582 | // How Standard Queries are generated: | |
3583 | // 1. The Question Section contains the question | |
c9b9ae52 | 3584 | // 2. The Additional Section contains answers we already know, to suppress duplicate responses |
6528fe3e A |
3585 | |
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. | |
3593 | ||
c9b9ae52 | 3594 | mDNSlocal void SendQueries(mDNS *const m) |
83fb1e36 A |
3595 | { |
3596 | mDNSu32 slot; | |
3597 | CacheGroup *cg; | |
3598 | CacheRecord *cr; | |
3599 | AuthRecord *ar; | |
3600 | int pktcount = 0; | |
3601 | DNSQuestion *q; | |
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; | |
3606 | ||
3607 | // 1. If time for a query, work out what we need to do | |
3608 | ||
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) | |
3612 | { | |
3613 | if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries) | |
3614 | { | |
3615 | if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0) | |
3616 | { | |
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 | |
f0cc3e7b | 3622 | if (!mDNSOpaque16IsZero(q->TargetQID)) |
83fb1e36 A |
3623 | { |
3624 | q->LastQTime = m->timenow - q->ThisQInterval; | |
3625 | cr->UnansweredQueries++; | |
51601d48 | 3626 | m->mDNSStats.CacheRefreshQueries++; |
83fb1e36 A |
3627 | } |
3628 | else if (q->SendQNow == mDNSNULL) | |
3629 | { | |
3630 | q->SendQNow = cr->resrec.InterfaceID; | |
3631 | } | |
3632 | else if (q->SendQNow != cr->resrec.InterfaceID) | |
3633 | { | |
3634 | q->SendQNow = mDNSInterfaceMark; | |
3635 | } | |
51601d48 A |
3636 | |
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; | |
83fb1e36 A |
3643 | } |
3644 | } | |
3645 | } | |
3646 | ||
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) | |
3655 | { | |
3656 | q = m->CurrentQuestion; | |
f0cc3e7b | 3657 | if (mDNSOpaque16IsZero(q->TargetQID) && TimeToSendThisQuestion(q, m->timenow)) |
83fb1e36 A |
3658 | { |
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; | |
3663 | } | |
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; | |
3668 | } | |
3669 | while (m->CurrentQuestion) | |
3670 | { | |
3671 | LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); | |
3672 | m->CurrentQuestion = m->CurrentQuestion->next; | |
3673 | } | |
3674 | m->CurrentQuestion = mDNSNULL; | |
3675 | ||
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. | |
12c5fa7a | 3682 | m->NextScheduledQuery = m->timenow + FutureTime; |
83fb1e36 A |
3683 | for (q = m->Questions; q && q != m->NewQuestions; q=q->next) |
3684 | { | |
51601d48 | 3685 | if (mDNSOpaque16IsZero(q->TargetQID) |
f0cc3e7b | 3686 | && (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q)))) |
83fb1e36 A |
3687 | { |
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) | |
3692 | { | |
51601d48 A |
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. | |
9f221bca | 3697 | if (q->BrowseThreshold |
51601d48 A |
3698 | && (q->CurrentAnswers >= q->BrowseThreshold) |
3699 | && (q->CachedAnswerNeedsUpdate == mDNSfalse) | |
3700 | && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval))) | |
3701 | { | |
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); | |
3708 | } | |
3709 | else | |
3710 | { | |
3711 | // Mark this question for sending on all interfaces | |
3712 | q->SendQNow = mDNSInterfaceMark; | |
3713 | q->ThisQInterval *= QuestionIntervalStep; | |
3714 | } | |
3715 | ||
83fb1e36 A |
3716 | debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d", |
3717 | q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast); | |
51601d48 | 3718 | |
9f221bca | 3719 | if (q->ThisQInterval > MaxQuestionInterval) |
51601d48 | 3720 | { |
83fb1e36 | 3721 | q->ThisQInterval = MaxQuestionInterval; |
51601d48 | 3722 | } |
2682e09e A |
3723 | else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID && |
3724 | q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast && | |
83fb1e36 A |
3725 | !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash))) |
3726 | { | |
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 | |
2682e09e | 3735 | ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0); |
83fb1e36 A |
3736 | } |
3737 | } | |
3738 | ||
3739 | // Mark for sending. (If no active interfaces, then don't even try.) | |
3740 | q->SendOnAll = (q->SendQNow == mDNSInterfaceMark); | |
3741 | if (q->SendOnAll) | |
3742 | { | |
3743 | q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID; | |
3744 | q->LastQTime = m->timenow; | |
3745 | } | |
3746 | ||
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); | |
3750 | ||
3751 | q->LastQTxTime = m->timenow; | |
3752 | q->RecentAnswerPkts = 0; | |
3753 | if (q->RequestUnicast) q->RequestUnicast--; | |
3754 | } | |
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); | |
3758 | } | |
3759 | ||
3760 | // 2. Scan our authoritative RR list to see what probes we might need to send | |
3761 | ||
12c5fa7a | 3762 | m->NextScheduledProbe = m->timenow + FutureTime; |
83fb1e36 A |
3763 | |
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) | |
3768 | { | |
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... | |
3772 | { | |
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) | |
3775 | { | |
3776 | SetNextAnnounceProbeTime(m, ar); | |
3777 | } | |
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) | |
3780 | { | |
3781 | if (ar->AddressProxy.type == mDNSAddrType_IPv4) | |
3782 | { | |
9f221bca A |
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 | |
83fb1e36 A |
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); | |
3790 | } | |
3791 | else if (ar->AddressProxy.type == mDNSAddrType_IPv6) | |
3792 | { | |
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); | |
3799 | } | |
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; | |
3807 | ar->ProbeCount--; | |
3808 | SetNextAnnounceProbeTime(m, ar); | |
3809 | if (ar->ProbeCount == 0) | |
3810 | { | |
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... | |
3813 | AuthRecord *r2; | |
3814 | for (r2 = m->DuplicateRecords; r2; r2=r2->next) | |
3815 | if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar)) | |
3816 | r2->ProbeCount = 0; | |
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); | |
3826 | } | |
3827 | } | |
3828 | // else, if it has now finished probing, move it to state Verified, | |
3829 | // and update m->NextScheduledResponse so it will be announced | |
3830 | else | |
3831 | { | |
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); | |
3837 | } | |
3838 | } | |
3839 | } | |
3840 | m->CurrentRecord = m->DuplicateRecords; | |
3841 | while (m->CurrentRecord) | |
3842 | { | |
3843 | ar = m->CurrentRecord; | |
3844 | m->CurrentRecord = ar->next; | |
3845 | if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged) | |
3846 | AcknowledgeRecord(m, ar); | |
3847 | } | |
3848 | ||
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 | |
3851 | while (intf) | |
3852 | { | |
51601d48 A |
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; | |
83fb1e36 A |
3855 | mDNSu8 *queryptr = m->omsg.data; |
3856 | mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class | |
3857 | ||
3858 | InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags); | |
3859 | if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet"); | |
3860 | if (!KnownAnswerList) | |
3861 | { | |
3862 | // Start a new known-answer list | |
3863 | CacheRecord **kalistptr = &KnownAnswerList; | |
51601d48 | 3864 | mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option |
83fb1e36 A |
3865 | |
3866 | // Put query questions in this packet | |
3867 | for (q = m->Questions; q && q != m->NewQuestions; q=q->next) | |
3868 | { | |
3869 | if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID)) | |
3870 | { | |
51601d48 | 3871 | mDNSBool Suppress = mDNSfalse; |
83fb1e36 A |
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); | |
3875 | ||
3876 | // If interface is P2P type, verify that query should be sent over it. | |
3877 | if (!mDNSPlatformValidQuestionForInterface(q, intf)) | |
3878 | { | |
83fb1e36 A |
3879 | q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf); |
3880 | } | |
3881 | // If we're suppressing this question, or we successfully put it, update its SendQNow state | |
51601d48 | 3882 | else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) || |
9f221bca | 3883 | BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast)) |
83fb1e36 | 3884 | { |
51601d48 A |
3885 | if (Suppress) |
3886 | m->mDNSStats.DupQuerySuppressions++; | |
3887 | ||
83fb1e36 A |
3888 | q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf); |
3889 | if (q->WakeOnResolveCount) | |
3890 | { | |
3891 | mDNSSendWakeOnResolve(m, q); | |
3892 | q->WakeOnResolveCount--; | |
3893 | } | |
3894 | ||
9f221bca | 3895 | // use background traffic class if any included question requires it |
f0cc3e7b | 3896 | if (q->UseBackgroundTraffic) |
83fb1e36 A |
3897 | { |
3898 | useBackgroundTrafficClass = mDNStrue; | |
3899 | } | |
3900 | } | |
3901 | } | |
3902 | } | |
3903 | ||
3904 | // Put probe questions in this packet | |
3905 | for (ar = m->ResourceRecords; ar; ar=ar->next) | |
9f221bca A |
3906 | { |
3907 | if (ar->SendRNow != intf->InterfaceID) | |
3908 | continue; | |
3909 | ||
3910 | // If interface is a P2P variant, verify that the probe should be sent over it. | |
3911 | if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID)) | |
83fb1e36 | 3912 | { |
9f221bca A |
3913 | ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf); |
3914 | ar->IncludeInProbe = mDNSfalse; | |
3915 | } | |
3916 | else | |
3917 | { | |
3918 | mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse; | |
83fb1e36 A |
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; | |
9f221bca A |
3923 | mDNSBool putProbe = mDNStrue; |
3924 | mDNSu16 qclass = ar->resrec.rrclass | ucbit; | |
3925 | ||
3926 | {// Determine if this probe question is already in packet's dns message | |
3927 | const mDNSu8 *questionptr = m->omsg.data; | |
3928 | DNSQuestion question; | |
3929 | mDNSu16 n; | |
3930 | for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++) | |
3931 | { | |
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)) | |
3935 | { | |
3936 | putProbe = mDNSfalse; // set to false if already in message | |
3937 | break; | |
3938 | } | |
3939 | } | |
3940 | } | |
3941 | ||
3942 | if (putProbe) | |
3943 | { | |
3944 | mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass); | |
3945 | if (newptr) | |
3946 | { | |
3947 | queryptr = newptr; | |
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); | |
3953 | } | |
3954 | } | |
3955 | else | |
83fb1e36 | 3956 | { |
83fb1e36 A |
3957 | ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf); |
3958 | ar->IncludeInProbe = mDNStrue; | |
83fb1e36 A |
3959 | } |
3960 | } | |
9f221bca | 3961 | } |
83fb1e36 A |
3962 | } |
3963 | ||
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) | |
3966 | { | |
3967 | CacheRecord *ka = KnownAnswerList; | |
3968 | mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond; | |
51601d48 A |
3969 | mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, |
3970 | m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace); | |
83fb1e36 A |
3971 | if (newptr) |
3972 | { | |
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); | |
3975 | queryptr = newptr; | |
3976 | KnownAnswerList = ka->NextInKAList; | |
3977 | ka->NextInKAList = mDNSNULL; | |
3978 | } | |
3979 | else | |
3980 | { | |
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; | |
3986 | break; | |
3987 | } | |
3988 | } | |
3989 | ||
3990 | for (ar = m->ResourceRecords; ar; ar=ar->next) | |
51601d48 | 3991 | { |
83fb1e36 A |
3992 | if (ar->IncludeInProbe) |
3993 | { | |
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)); | |
3998 | } | |
51601d48 A |
3999 | } |
4000 | ||
83fb1e36 A |
4001 | if (queryptr > m->omsg.data) |
4002 | { | |
51601d48 A |
4003 | // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet |
4004 | if (OwnerRecordSpace || TraceRecordSpace) | |
83fb1e36 A |
4005 | { |
4006 | AuthRecord opt; | |
4007 | mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); | |
4008 | opt.resrec.rrclass = NormalMaxDNSMessageData; | |
9f221bca | 4009 | opt.resrec.rdlength = sizeof(rdataOPT); |
83fb1e36 | 4010 | opt.resrec.rdestimate = sizeof(rdataOPT); |
51601d48 A |
4011 | if (OwnerRecordSpace && TraceRecordSpace) |
4012 | { | |
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]); | |
4017 | } | |
4018 | else if (OwnerRecordSpace) | |
4019 | { | |
4020 | SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]); | |
4021 | } | |
4022 | else if (TraceRecordSpace) | |
4023 | { | |
4024 | SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]); | |
4025 | } | |
83fb1e36 A |
4026 | queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals, |
4027 | &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData); | |
4028 | if (!queryptr) | |
9f221bca | 4029 | { |
51601d48 | 4030 | LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", |
83fb1e36 | 4031 | m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); |
51601d48 | 4032 | } |
83fb1e36 | 4033 | if (queryptr > m->omsg.data + NormalMaxDNSMessageData) |
51601d48 | 4034 | { |
83fb1e36 | 4035 | if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1) |
9f221bca A |
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, | |
51601d48 A |
4038 | m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); |
4039 | } | |
83fb1e36 A |
4040 | } |
4041 | ||
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); | |
f0cc3e7b | 4044 | debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)", |
83fb1e36 A |
4045 | m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s", |
4046 | m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s", | |
f0cc3e7b A |
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); | |
83fb1e36 A |
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. | |
4055 | } | |
4056 | else // Nothing more to send on this interface; go to next | |
4057 | { | |
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); | |
4062 | #endif | |
4063 | intf = next; | |
4064 | } | |
4065 | } | |
4066 | ||
4067 | // 4. Final housekeeping | |
4068 | ||
4069 | // 4a. Debugging check: Make sure we announced all our records | |
4070 | for (ar = m->ResourceRecords; ar; ar=ar->next) | |
4071 | if (ar->SendRNow) | |
4072 | { | |
4073 | if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P) | |
b8d5688b | 4074 | LogInfo("SendQueries: No active interface %d to send probe: %d %s", |
f0cc3e7b | 4075 | IIDPrintable(ar->SendRNow), IIDPrintable(ar->resrec.InterfaceID), ARDisplayString(m, ar)); |
83fb1e36 A |
4076 | ar->SendRNow = mDNSNULL; |
4077 | } | |
4078 | ||
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) | |
4085 | { | |
4086 | if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries) | |
4087 | { | |
4088 | if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0) | |
4089 | { | |
4090 | cr->UnansweredQueries++; | |
4091 | cr->CRActiveQuestion->SendQNow = mDNSNULL; | |
4092 | SetNextCacheCheckTimeForRecord(m, cr); | |
4093 | } | |
4094 | } | |
4095 | } | |
4096 | ||
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) | |
51601d48 | 4101 | { |
83fb1e36 A |
4102 | if (q->SendQNow) |
4103 | { | |
4104 | DNSQuestion *x; | |
4105 | for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion | |
9f221bca A |
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)", | |
f0cc3e7b | 4110 | IIDPrintable(q->SendQNow), x ? "new" : "old", IIDPrintable(q->InterfaceID), q->qname.c, DNSTypeName(q->qtype)); |
83fb1e36 A |
4111 | q->SendQNow = mDNSNULL; |
4112 | } | |
51601d48 A |
4113 | q->CachedAnswerNeedsUpdate = mDNSfalse; |
4114 | } | |
83fb1e36 | 4115 | } |
6528fe3e | 4116 | |
9f221bca | 4117 | mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly) |
83fb1e36 A |
4118 | { |
4119 | int i, j; | |
9f221bca | 4120 | |
83fb1e36 A |
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; } | |
32bb7e43 | 4124 | |
83fb1e36 A |
4125 | // 0x00 Destination address |
4126 | for (i=0; i<6; i++) *ptr++ = EthAddr->b[i]; | |
32bb7e43 | 4127 | |
83fb1e36 A |
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]; | |
32bb7e43 | 4130 | |
83fb1e36 A |
4131 | // 0x0C Ethertype (0x0842) |
4132 | *ptr++ = 0x08; | |
4133 | *ptr++ = 0x42; | |
32bb7e43 | 4134 | |
83fb1e36 A |
4135 | // 0x0E Wakeup sync sequence |
4136 | for (i=0; i<6; i++) *ptr++ = 0xFF; | |
32bb7e43 | 4137 | |
83fb1e36 A |
4138 | // 0x14 Wakeup data |
4139 | for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i]; | |
32bb7e43 | 4140 | |
83fb1e36 A |
4141 | // 0x74 Password |
4142 | for (i=0; i<6; i++) *ptr++ = password->b[i]; | |
32bb7e43 | 4143 | |
83fb1e36 | 4144 | mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID); |
32bb7e43 | 4145 | |
9f221bca A |
4146 | if (!unicastOnly) |
4147 | { | |
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); | |
4155 | } | |
83fb1e36 | 4156 | } |
32bb7e43 | 4157 | |
6528fe3e | 4158 | // *************************************************************************** |
c9b9ae52 | 4159 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e A |
4160 | #pragma mark - |
4161 | #pragma mark - RR List Management & Task Management | |
4162 | #endif | |
4163 | ||
4a95efb2 A |
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) | |
83fb1e36 A |
4168 | { |
4169 | q->LastQTime = m->timenow; | |
4170 | q->LastQTxTime = m->timenow; | |
4171 | q->RecentAnswerPkts = 0; | |
4172 | q->ThisQInterval = MaxQuestionInterval; | |
51601d48 | 4173 | q->RequestUnicast = 0; |
19fa75a9 | 4174 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 A |
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; | |
19fa75a9 | 4178 | #endif |
83fb1e36 A |
4179 | debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); |
4180 | } | |
4a95efb2 | 4181 | |
f0cc3e7b A |
4182 | mDNSlocal void AdjustUnansweredQueries(mDNS *const m, CacheRecord *const rr) |
4183 | { | |
4184 | const mDNSs32 expireTime = RRExpireTime(rr); | |
4185 | const mDNSu32 interval = TicksTTL(rr) / 20; // Calculate 5% of the cache record's TTL. | |
4186 | mDNSu32 rem; | |
4187 | ||
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; | |
4190 | ||
4191 | if (interval == 0) | |
4192 | { | |
4193 | LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr), CRDisplayString(m, rr)); | |
4194 | return; | |
4195 | } | |
4196 | ||
4197 | // Calculate the number of whole 5% TTL intervals between now and expiration time. | |
4198 | rem = ((mDNSu32)(expireTime - m->timenow)) / interval; | |
4199 | ||
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; | |
4203 | ||
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) | |
4214 | { | |
4215 | if (rem == 0) rem++; | |
4216 | rr->UnansweredQueries = (mDNSu8)(MaxUnansweredQueries - rem); | |
4217 | } | |
4218 | } | |
4219 | ||
32bb7e43 | 4220 | // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list. |
67c8f8a1 A |
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) | |
83fb1e36 A |
4225 | { |
4226 | DNSQuestion *const q = m->CurrentQuestion; | |
9f221bca | 4227 | const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord); |
83fb1e36 | 4228 | |
2682e09e A |
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)); | |
83fb1e36 | 4232 | |
83fb1e36 A |
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) | |
4238 | { | |
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); | |
4242 | return; | |
4243 | } | |
4244 | ||
f0cc3e7b | 4245 | if (q->Suppressed && (AddRecord != QC_suppressed)) |
83fb1e36 A |
4246 | { |
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 | |
51601d48 | 4249 | // that are timing out, which we know are answered with negative cache record when timing out. |
83fb1e36 A |
4250 | if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0)) |
4251 | return; | |
4252 | } | |
2682e09e A |
4253 | |
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 | |
4257 | ||
f0cc3e7b | 4258 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
19fa75a9 | 4259 | if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname && !q->metrics.answered) |
9f221bca | 4260 | { |
19fa75a9 A |
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)) | |
9f221bca | 4264 | { |
19fa75a9 A |
4265 | skipUpdate = mDNStrue; |
4266 | } | |
4267 | #endif | |
4268 | if (!skipUpdate) | |
4269 | { | |
4270 | const domainname * queryName; | |
4271 | mDNSu32 responseLatencyMs, querySendCount; | |
4272 | mDNSBool isForCellular; | |
4273 | ||
4274 | queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname; | |
4275 | querySendCount = q->metrics.querySendCount; | |
4276 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
4277 | if (q->querier) | |
4278 | { | |
4279 | querySendCount += mdns_querier_get_send_count(q->querier); | |
4280 | } | |
4281 | isForCellular = mdns_dns_service_interface_is_cellular(q->dnsservice); | |
4282 | #else | |
4283 | isForCellular = (q->qDNSServer && q->qDNSServer->isCell); | |
4284 | #endif | |
9f221bca A |
4285 | if (q->metrics.querySendCount > 0) |
4286 | { | |
4287 | responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond; | |
4288 | } | |
4289 | else | |
4290 | { | |
4291 | responseLatencyMs = 0; | |
4292 | } | |
19fa75a9 A |
4293 | MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, querySendCount, q->metrics.expiredAnswerState, |
4294 | q->metrics.dnsOverTCPState, responseLatencyMs, isForCellular); | |
9f221bca | 4295 | } |
19fa75a9 | 4296 | q->metrics.answered = mDNStrue; |
9f221bca A |
4297 | } |
4298 | #endif | |
83fb1e36 A |
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. | |
4302 | ||
2682e09e | 4303 | if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost) |
83fb1e36 | 4304 | { |
83fb1e36 A |
4305 | debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d", |
4306 | rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers); | |
f0cc3e7b A |
4307 | if (!rr->CRActiveQuestion) |
4308 | { | |
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 | |
4311 | } | |
4312 | rr->CRActiveQuestion = q; // We know q is non-null | |
83fb1e36 A |
4313 | SetNextCacheCheckTimeForRecord(m, rr); |
4314 | } | |
4315 | ||
4316 | // If this is: | |
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)) | |
4326 | { | |
4327 | ResetQuestionState(m, q); | |
4328 | } | |
4329 | ||
4330 | if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us | |
4331 | ||
f0cc3e7b | 4332 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) |
12c5fa7a A |
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; | |
4335 | #endif | |
4336 | ||
9f221bca A |
4337 | #ifdef USE_LIBIDN |
4338 | if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) // If negative answer, check if we need to try Punycode conversion | |
4339 | { | |
4340 | domainname newname; | |
4341 | if (PerformNextPunycodeConversion(q, &newname)) // Itertative Punycode conversion succeeded, so reissue question with new name | |
4342 | { | |
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 | |
4350 | ||
4351 | if (sock) // Transplant saved socket, if appropriate | |
4352 | { | |
4353 | if (q->DuplicateOf) mDNSPlatformUDPClose(sock); | |
4354 | else { q->LocalSocket = sock; q->TargetQID = id; } | |
4355 | } | |
4356 | return; // All done for now; wait until we get the next answer | |
4357 | } | |
4358 | } | |
4359 | #endif // USE_LIBIDN | |
4360 | ||
83fb1e36 | 4361 | // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response |
51601d48 | 4362 | // for the purpose of retrying search domains/timeout OR the question is suppressed |
83fb1e36 | 4363 | if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))) |
51601d48 | 4364 | if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return; |
83fb1e36 A |
4365 | |
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)) | |
4368 | { | |
4369 | mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls | |
4370 | if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)) | |
4371 | { | |
19fa75a9 A |
4372 | if (mDNSOpaque16IsZero(q->TargetQID)) |
4373 | { | |
4374 | CacheRecord neg; | |
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); | |
4378 | #else | |
4379 | MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer); | |
4380 | #endif | |
4381 | q->QuestionCallback(m, q, &neg.resrec, AddRecord); | |
4382 | } | |
83fb1e36 A |
4383 | } |
4384 | else | |
12c5fa7a | 4385 | { |
f0cc3e7b | 4386 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) |
12c5fa7a A |
4387 | if (DNS64ShouldAnswerQuestion(q, &rr->resrec)) |
4388 | { | |
672757b6 | 4389 | DNS64AnswerCurrentQuestion(m, &rr->resrec, AddRecord); |
12c5fa7a A |
4390 | } |
4391 | else | |
4392 | #endif | |
4393 | { | |
19fa75a9 A |
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) | |
12c5fa7a A |
4398 | q->QuestionCallback(m, q, &rr->resrec, AddRecord); |
4399 | } | |
4400 | } | |
83fb1e36 A |
4401 | mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again |
4402 | } | |
f0cc3e7b A |
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. | |
4407 | ||
19fa75a9 | 4408 | if (m->CurrentQuestion == q) |
2682e09e A |
4409 | { |
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); | |
4414 | ||
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) | |
4417 | { | |
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 | |
4421 | } | |
4422 | } | |
83fb1e36 | 4423 | } |
7f0064bd | 4424 | |
f0cc3e7b | 4425 | mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *cr) |
83fb1e36 | 4426 | { |
f0cc3e7b | 4427 | cr->DelayDelivery = 0; |
83fb1e36 A |
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) | |
4433 | { | |
4434 | DNSQuestion *q = m->CurrentQuestion; | |
f0cc3e7b A |
4435 | if (CacheRecordAnswersQuestion(cr, q)) |
4436 | AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add); | |
83fb1e36 A |
4437 | if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now |
4438 | m->CurrentQuestion = q->next; | |
4439 | } | |
4440 | m->CurrentQuestion = mDNSNULL; | |
4441 | } | |
7f0064bd | 4442 | |
564f2ae2 | 4443 | mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash) |
83fb1e36 | 4444 | { |
564f2ae2 | 4445 | const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second |
83fb1e36 A |
4446 | const mDNSs32 start = m->timenow - 0x10000000; |
4447 | mDNSs32 delay = start; | |
12c5fa7a | 4448 | CacheGroup *cg = CacheGroupForName(m, namehash, name); |
83fb1e36 | 4449 | const CacheRecord *rr; |
51601d48 | 4450 | |
83fb1e36 | 4451 | for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) |
51601d48 | 4452 | { |
564f2ae2 | 4453 | if (threshold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second |
51601d48 | 4454 | { |
83fb1e36 A |
4455 | if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted |
4456 | delay = RRExpireTime(rr); | |
51601d48 A |
4457 | } |
4458 | } | |
4459 | if (delay - start > 0) | |
4460 | return(NonZeroTime(delay)); | |
4461 | else | |
4462 | return(0); | |
83fb1e36 | 4463 | } |
6528fe3e | 4464 | |
263eeeab | 4465 | // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call. |
6528fe3e A |
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. | |
c9b9ae52 A |
4468 | // rr is a new CacheRecord just received into our cache |
4469 | // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique). | |
32bb7e43 | 4470 | // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback, |
c9b9ae52 | 4471 | // which may change the record list and/or question list. |
6528fe3e | 4472 | // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. |
f0cc3e7b | 4473 | mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *cr) |
83fb1e36 A |
4474 | { |
4475 | DNSQuestion *q; | |
4476 | ||
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) | |
4480 | { | |
f0cc3e7b | 4481 | if (CacheRecordAnswersQuestion(cr, q)) |
83fb1e36 A |
4482 | { |
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) | |
4490 | { | |
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) | |
4494 | { | |
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); | |
4500 | } | |
4501 | } | |
f0cc3e7b A |
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); | |
83fb1e36 | 4506 | q->CurrentAnswers++; |
51601d48 | 4507 | |
19fa75a9 | 4508 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 | 4509 | q->unansweredQueries = 0; |
19fa75a9 | 4510 | #endif |
f0cc3e7b A |
4511 | if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++; |
4512 | if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++; | |
83fb1e36 A |
4513 | if (q->CurrentAnswers > 4000) |
4514 | { | |
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); | |
f0cc3e7b A |
4519 | cr->resrec.rroriginalttl = 0; |
4520 | cr->UnansweredQueries = MaxUnansweredQueries; | |
83fb1e36 A |
4521 | } |
4522 | } | |
4523 | } | |
4524 | ||
f0cc3e7b | 4525 | if (!cr->DelayDelivery) |
83fb1e36 A |
4526 | { |
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) | |
4531 | { | |
4532 | q = m->CurrentQuestion; | |
f0cc3e7b A |
4533 | if (CacheRecordAnswersQuestion(cr, q)) |
4534 | AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add); | |
83fb1e36 A |
4535 | if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now |
4536 | m->CurrentQuestion = q->next; | |
4537 | } | |
4538 | m->CurrentQuestion = mDNSNULL; | |
4539 | } | |
4540 | ||
f0cc3e7b | 4541 | SetNextCacheCheckTimeForRecord(m, cr); |
83fb1e36 | 4542 | } |
6528fe3e | 4543 | |
283ee3ff A |
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. | |
32bb7e43 | 4551 | // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback, |
283ee3ff A |
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. | |
f0cc3e7b | 4554 | mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *cr) |
83fb1e36 A |
4555 | { |
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) | |
4563 | { | |
4564 | DNSQuestion *q = m->CurrentQuestion; | |
f0cc3e7b A |
4565 | if (CacheRecordAnswersQuestion(cr, q)) |
4566 | AnswerCurrentQuestionWithResourceRecord(m, cr, QC_addnocache); // QC_addnocache means "don't expect remove events for this" | |
83fb1e36 A |
4567 | if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now |
4568 | m->CurrentQuestion = q->next; | |
4569 | } | |
4570 | m->CurrentQuestion = mDNSNULL; | |
4571 | } | |
283ee3ff | 4572 | |
5e65c77f A |
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. | |
c9b9ae52 A |
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. | |
f0cc3e7b | 4577 | // cr is an existing cache CacheRecord that just expired and is being deleted |
c9b9ae52 | 4578 | // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique). |
32bb7e43 | 4579 | // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback, |
c9b9ae52 A |
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. | |
f0cc3e7b | 4582 | mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *cr) |
83fb1e36 A |
4583 | { |
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; | |
4588 | ||
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) | |
4592 | { | |
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. | |
f0cc3e7b A |
4598 | if (!q->Suppressed && CacheRecordAnswersQuestion(cr, q) && |
4599 | (q->allowExpired == AllowExpired_None || cr->resrec.mortality == Mortality_Mortal)) | |
83fb1e36 | 4600 | { |
f0cc3e7b | 4601 | verbosedebugf("CacheRecordRmv %p %s", cr, CRDisplayString(m, cr)); |
83fb1e36 A |
4602 | q->FlappingInterface1 = mDNSNULL; |
4603 | q->FlappingInterface2 = mDNSNULL; | |
4604 | ||
4605 | if (q->CurrentAnswers == 0) | |
19fa75a9 A |
4606 | { |
4607 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
83fb1e36 A |
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)); | |
19fa75a9 A |
4611 | #endif |
4612 | } | |
83fb1e36 A |
4613 | else |
4614 | { | |
4615 | q->CurrentAnswers--; | |
f0cc3e7b A |
4616 | if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--; |
4617 | if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--; | |
83fb1e36 | 4618 | } |
51601d48 A |
4619 | |
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)) | |
4623 | { | |
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); | |
4629 | } | |
f0cc3e7b | 4630 | if (cr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results |
83fb1e36 | 4631 | { |
2682e09e | 4632 | if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID)) |
83fb1e36 A |
4633 | { |
4634 | LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents", | |
4635 | q->qname.c, DNSTypeName(q->qtype)); | |
f0cc3e7b | 4636 | ReconfirmAntecedents(m, &q->qname, q->qnamehash, cr->resrec.InterfaceID, 0); |
83fb1e36 | 4637 | } |
f0cc3e7b | 4638 | AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv); |
83fb1e36 A |
4639 | } |
4640 | } | |
4641 | if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now | |
4642 | m->CurrentQuestion = q->next; | |
4643 | } | |
4644 | m->CurrentQuestion = mDNSNULL; | |
4645 | } | |
6528fe3e | 4646 | |
283ee3ff | 4647 | mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e) |
83fb1e36 | 4648 | { |
f0cc3e7b | 4649 | #if MDNS_MALLOC_DEBUGGING >= 1 |
83fb1e36 A |
4650 | unsigned int i; |
4651 | for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF; | |
283ee3ff | 4652 | #endif |
83fb1e36 A |
4653 | e->next = m->rrcache_free; |
4654 | m->rrcache_free = e; | |
4655 | m->rrcache_totalused--; | |
4656 | } | |
6528fe3e | 4657 | |
283ee3ff | 4658 | mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp) |
83fb1e36 A |
4659 | { |
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)) | |
9f221bca | 4665 | // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage)); |
83fb1e36 A |
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); | |
4670 | } | |
4671 | ||
51601d48 | 4672 | mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp) |
83fb1e36 | 4673 | { |
83fb1e36 A |
4674 | while (*rp) |
4675 | { | |
4676 | CacheRecord *rr = *rp; | |
4677 | *rp = (*rp)->next; // Cut record from list | |
4678 | if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage) | |
4679 | { | |
4680 | mDNSPlatformMemFree(rr->resrec.rdata); | |
4681 | rr->resrec.rdata = mDNSNULL; | |
4682 | } | |
51601d48 | 4683 | // NSEC or SOA records that are not added to the CacheGroup do not share the name |
83fb1e36 A |
4684 | // of the CacheGroup. |
4685 | if (rr->resrec.name) | |
4686 | { | |
51601d48 | 4687 | debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); |
83fb1e36 A |
4688 | mDNSPlatformMemFree((void *)rr->resrec.name); |
4689 | rr->resrec.name = mDNSNULL; | |
4690 | } | |
51601d48 A |
4691 | // Don't count the NSEC3 records used by anonymous browse/reg |
4692 | if (!rr->resrec.InterfaceID) | |
4693 | { | |
4694 | m->rrcache_totalused_unicast -= rr->resrec.rdlength; | |
51601d48 | 4695 | } |
83fb1e36 A |
4696 | ReleaseCacheEntity(m, (CacheEntity *)rr); |
4697 | } | |
83fb1e36 | 4698 | } |
283ee3ff | 4699 | |
51601d48 A |
4700 | mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r) |
4701 | { | |
4702 | CacheGroup *cg; | |
51601d48 A |
4703 | |
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; | |
19fa75a9 A |
4707 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
4708 | mdns_forget(&r->resrec.dnsservice); | |
4709 | #endif | |
4710 | ||
4711 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
4712 | release_denial_records_in_cache_record(r); | |
4713 | #endif | |
51601d48 | 4714 | |
12c5fa7a | 4715 | cg = CacheGroupForRecord(m, &r->resrec); |
9f221bca | 4716 | |
51601d48 A |
4717 | if (!cg) |
4718 | { | |
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)); | |
4721 | } | |
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) | |
4726 | { | |
4727 | debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype)); | |
4728 | mDNSPlatformMemFree((void *)r->resrec.name); | |
4729 | } | |
4730 | r->resrec.name = mDNSNULL; | |
4731 | ||
51601d48 A |
4732 | if (!r->resrec.InterfaceID) |
4733 | { | |
4734 | m->rrcache_totalused_unicast -= r->resrec.rdlength; | |
51601d48 A |
4735 | } |
4736 | ||
51601d48 A |
4737 | ReleaseAdditionalCacheRecords(m, &r->soa); |
4738 | ||
4739 | ReleaseCacheEntity(m, (CacheEntity *)r); | |
4740 | } | |
4741 | ||
4742 | // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering | |
67c8f8a1 A |
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. | |
263eeeab | 4745 | mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg) |
83fb1e36 A |
4746 | { |
4747 | CacheRecord **rp = &cg->members; | |
4748 | ||
4749 | if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; } | |
4750 | m->lock_rrcache = 1; | |
4751 | ||
4752 | while (*rp) | |
4753 | { | |
4754 | CacheRecord *const rr = *rp; | |
2682e09e | 4755 | mDNSBool recordReleased = mDNSfalse; |
83fb1e36 A |
4756 | mDNSs32 event = RRExpireTime(rr); |
4757 | if (m->timenow - event >= 0) // If expired, delete it | |
4758 | { | |
83fb1e36 A |
4759 | if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away |
4760 | { | |
4761 | DNSQuestion *q = rr->CRActiveQuestion; | |
2682e09e A |
4762 | verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s", |
4763 | m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr)); | |
83fb1e36 A |
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 | |
f0cc3e7b A |
4771 | if (((mDNSOpaque16IsZero(q->TargetQID) && (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) || |
4772 | (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived)) && ActiveQuestion(q)) | |
83fb1e36 A |
4773 | { |
4774 | q->ThisQInterval = InitialQuestionInterval; | |
4775 | q->LastQTime = m->timenow - q->ThisQInterval; | |
4776 | SetNextQueryTime(m, q); | |
4777 | } | |
4778 | CacheRecordRmv(m, rr); | |
4779 | m->rrcache_active--; | |
4780 | } | |
2682e09e A |
4781 | |
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 | |
19fa75a9 | 4784 | rr->resrec.rroriginalttl == 0 || // Non-mortal record that is set to be purged |
2682e09e A |
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; | |
4793 | } | |
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) | |
4797 | { | |
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)); | |
4802 | } | |
4803 | } | |
83fb1e36 | 4804 | } |
2682e09e | 4805 | else // else, not expired; see if we need to query |
83fb1e36 A |
4806 | { |
4807 | // If waiting to delay delivery, do nothing until then | |
4808 | if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0) | |
4809 | event = rr->DelayDelivery; | |
4810 | else | |
4811 | { | |
4812 | if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr); | |
4813 | if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries) | |
4814 | { | |
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 | |
4818 | { | |
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. | |
12c5fa7a | 4824 | event = m->timenow + FutureTime; |
83fb1e36 A |
4825 | } |
4826 | } | |
4827 | } | |
2682e09e A |
4828 | } |
4829 | ||
4830 | if (!recordReleased) // Schedule if we did not release the record | |
4831 | { | |
83fb1e36 A |
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; | |
4836 | rp = &rr->next; | |
4837 | } | |
4838 | } | |
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; | |
4842 | } | |
6528fe3e | 4843 | |
51601d48 A |
4844 | // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q". |
4845 | // | |
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. | |
4848 | // | |
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) | |
4852 | { | |
51601d48 A |
4853 | AuthRecord *lr; |
4854 | AuthGroup *ag; | |
4855 | ||
4856 | if (m->CurrentRecord) | |
4857 | LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); | |
4858 | ||
12c5fa7a | 4859 | ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); |
51601d48 A |
4860 | if (ag) |
4861 | { | |
4862 | m->CurrentRecord = ag->members; | |
4863 | while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords) | |
4864 | { | |
4865 | AuthRecord *rr = m->CurrentRecord; | |
4866 | m->CurrentRecord = rr->next; | |
4867 | // | |
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. | |
4870 | // | |
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. | |
4874 | ||
9f221bca | 4875 | if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE))) |
51601d48 A |
4876 | if (LocalOnlyRecordAnswersQuestion(rr, q)) |
4877 | { | |
4878 | if (checkOnly) | |
4879 | { | |
4880 | LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype), | |
4881 | ARDisplayString(m, rr)); | |
4882 | m->CurrentRecord = mDNSNULL; | |
4883 | return mDNStrue; | |
4884 | } | |
f0cc3e7b | 4885 | AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add); |
51601d48 A |
4886 | if (m->CurrentQuestion != q) |
4887 | break; // If callback deleted q, then we're finished here | |
4888 | } | |
4889 | } | |
4890 | } | |
4891 | m->CurrentRecord = mDNSNULL; | |
4892 | ||
4893 | if (m->CurrentQuestion != q) | |
4894 | { | |
4895 | LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers"); | |
4896 | return mDNStrue; | |
4897 | } | |
4898 | ||
4899 | if (q->LOAddressAnswers) | |
4900 | { | |
4901 | LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d", | |
4902 | q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers); | |
4903 | return mDNStrue; | |
4904 | } | |
4905 | ||
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. | |
4911 | if (ag) | |
4912 | { | |
4913 | lr = ag->NewLocalOnlyRecords; | |
4914 | while (lr) | |
4915 | { | |
4916 | if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q)) | |
4917 | { | |
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); | |
4920 | return mDNStrue; | |
4921 | } | |
4922 | lr = lr->next; | |
4923 | } | |
4924 | } | |
4925 | return mDNSfalse; | |
4926 | } | |
4927 | ||
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 | |
f0cc3e7b | 4930 | // DNS requests. |
51601d48 A |
4931 | mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q) |
4932 | { | |
f0cc3e7b A |
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) | |
4936 | { | |
4937 | GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed); | |
4938 | } | |
4939 | else | |
12c5fa7a A |
4940 | { |
4941 | q->ThisQInterval = 0; | |
12c5fa7a | 4942 | } |
51601d48 A |
4943 | } |
4944 | ||
c9b9ae52 | 4945 | mDNSlocal void AnswerNewQuestion(mDNS *const m) |
83fb1e36 A |
4946 | { |
4947 | mDNSBool ShouldQueryImmediately = mDNStrue; | |
4948 | DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer | |
f0cc3e7b | 4949 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) |
12c5fa7a A |
4950 | if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q); |
4951 | #endif | |
4952 | CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); | |
83fb1e36 A |
4953 | |
4954 | verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
4955 | ||
12c5fa7a | 4956 | if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg); |
83fb1e36 A |
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. | |
4961 | // | |
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). | |
4970 | // | |
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. | |
4975 | ||
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; | |
f0cc3e7b A |
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), | |
19fa75a9 | 4986 | DM_NAME_PARAM(&m->CurrentQuestion->qname), DNSTypeName(m->CurrentQuestion->qtype)); |
f0cc3e7b A |
4987 | } |
4988 | ||
83fb1e36 A |
4989 | m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted |
4990 | ||
4991 | if (q->NoAnswer == NoAnswer_Fail) | |
4992 | { | |
f0cc3e7b A |
4993 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, |
4994 | "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME " (" PUB_S ")", | |
19fa75a9 | 4995 | q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); |
f0cc3e7b | 4996 | |
19fa75a9 A |
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); | |
4999 | #else | |
83fb1e36 | 5000 | MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer); |
19fa75a9 | 5001 | #endif |
83fb1e36 A |
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 | |
5007 | } | |
83fb1e36 | 5008 | |
51601d48 | 5009 | if (m->CurrentQuestion != q) |
83fb1e36 | 5010 | { |
51601d48 | 5011 | LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); |
83fb1e36 A |
5012 | goto exit; |
5013 | } | |
5014 | ||
51601d48 A |
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)) | |
5018 | goto exit; | |
83fb1e36 | 5019 | |
83fb1e36 A |
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. | |
f0cc3e7b | 5023 | if (q->Suppressed) |
51601d48 A |
5024 | { |
5025 | AnswerSuppressedQuestion(m, q); | |
5026 | } | |
19fa75a9 | 5027 | else |
83fb1e36 | 5028 | { |
f0cc3e7b A |
5029 | CacheRecord *cr; |
5030 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) | |
5031 | if (SameNameCacheRecordAnswersQuestion(cr, q)) | |
83fb1e36 A |
5032 | { |
5033 | // SecsSinceRcvd is whole number of elapsed seconds, rounded down | |
f0cc3e7b A |
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 | |
83fb1e36 A |
5037 | |
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 | |
f0cc3e7b | 5040 | if ((cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique)) |
83fb1e36 A |
5041 | ShouldQueryImmediately = mDNSfalse; |
5042 | q->CurrentAnswers++; | |
f0cc3e7b A |
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; | |
19fa75a9 A |
5047 | #endif |
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); | |
2682e09e | 5051 | #endif |
f0cc3e7b | 5052 | AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add); |
83fb1e36 A |
5053 | if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here |
5054 | } | |
f0cc3e7b | 5055 | else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(cr->resrec.rrtype) && RRTypeIsAddressType(q->qtype)) |
83fb1e36 A |
5056 | ShouldQueryImmediately = mDNSfalse; |
5057 | } | |
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; } | |
5061 | ||
19fa75a9 A |
5062 | #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) |
5063 | dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_miss); | |
5064 | #endif | |
f0cc3e7b | 5065 | q->InitialCacheMiss = mDNStrue; // Initial cache check is done, so mark as a miss from now on |
2682e09e A |
5066 | if (q->allowExpired == AllowExpired_AllowExpiredAnswers) |
5067 | { | |
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 | |
5070 | { | |
f0cc3e7b A |
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", | |
19fa75a9 | 5073 | q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->firstExpiredQname)); |
2682e09e | 5074 | mDNS_StopQuery_internal(m, q); // Stop old query |
19fa75a9 A |
5075 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
5076 | if (!SameDomainName(&q->qname, &q->firstExpiredQname)) | |
5077 | { | |
5078 | Querier_PrepareQuestionForUnwindRestart(q); | |
5079 | } | |
5080 | #endif | |
2682e09e A |
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 | |
5086 | } | |
5087 | } | |
5088 | ||
83fb1e36 A |
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)) | |
5092 | { | |
f0cc3e7b | 5093 | debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->request_id, mDNSVal16(q->TargetQID), q->qname.c, DNSTypeName(q->qtype)); |
83fb1e36 A |
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 | |
5097 | { | |
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; | |
5102 | } | |
5103 | } | |
5104 | ||
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); | |
263eeeab A |
5111 | |
5112 | exit: | |
83fb1e36 A |
5113 | m->CurrentQuestion = mDNSNULL; |
5114 | m->lock_rrcache = 0; | |
5115 | } | |
6528fe3e | 5116 | |
67c8f8a1 | 5117 | // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any |
294beb6e | 5118 | // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord |
c9b9ae52 | 5119 | mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m) |
83fb1e36 | 5120 | { |
83fb1e36 A |
5121 | AuthGroup *ag; |
5122 | DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer | |
9f221bca | 5123 | mDNSBool retEv = mDNSfalse; |
12c5fa7a | 5124 | m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any) |
83fb1e36 A |
5125 | |
5126 | debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
5127 | ||
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 | |
5132 | ||
5133 | if (m->CurrentRecord) | |
5134 | LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); | |
5135 | ||
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 | |
12c5fa7a | 5139 | ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); |
83fb1e36 A |
5140 | if (ag) |
5141 | { | |
5142 | m->CurrentRecord = ag->members; | |
5143 | while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords) | |
5144 | { | |
5145 | AuthRecord *rr = m->CurrentRecord; | |
5146 | m->CurrentRecord = rr->next; | |
5147 | if (LocalOnlyRecordAnswersQuestion(rr, q)) | |
5148 | { | |
9f221bca | 5149 | retEv = mDNStrue; |
f0cc3e7b | 5150 | AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add); |
83fb1e36 A |
5151 | if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here |
5152 | } | |
5153 | } | |
5154 | } | |
5155 | ||
5156 | if (m->CurrentQuestion == q) | |
5157 | { | |
5158 | m->CurrentRecord = m->ResourceRecords; | |
5159 | ||
5160 | while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords) | |
5161 | { | |
f0cc3e7b A |
5162 | AuthRecord *ar = m->CurrentRecord; |
5163 | m->CurrentRecord = ar->next; | |
5164 | if (AuthRecordAnswersQuestion(ar, q)) | |
83fb1e36 | 5165 | { |
9f221bca | 5166 | retEv = mDNStrue; |
f0cc3e7b | 5167 | AnswerLocalQuestionWithLocalAuthRecord(m, ar, QC_add); |
83fb1e36 A |
5168 | if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here |
5169 | } | |
5170 | } | |
5171 | } | |
5172 | ||
9f221bca A |
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); | |
5177 | ||
83fb1e36 A |
5178 | m->CurrentQuestion = mDNSNULL; |
5179 | m->CurrentRecord = mDNSNULL; | |
5180 | } | |
6528fe3e | 5181 | |
283ee3ff | 5182 | mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG) |
83fb1e36 A |
5183 | { |
5184 | CacheEntity *e = mDNSNULL; | |
5185 | ||
5186 | if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); } | |
5187 | m->lock_rrcache = 1; | |
5188 | ||
5189 | // If we have no free records, ask the client layer to give us some more memory | |
5190 | if (!m->rrcache_free && m->MainCallback) | |
5191 | { | |
5192 | if (m->rrcache_totalused != m->rrcache_size) | |
f0cc3e7b A |
5193 | { |
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); | |
5197 | } | |
83fb1e36 A |
5198 | |
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) | |
f0cc3e7b A |
5205 | { |
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); | |
5209 | } | |
83fb1e36 A |
5210 | else |
5211 | { | |
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 | |
5215 | } | |
5216 | } | |
5217 | ||
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) | |
5221 | { | |
5222 | mDNSu32 oldtotalused = m->rrcache_totalused; | |
5223 | mDNSu32 slot; | |
5224 | for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) | |
5225 | { | |
5226 | CacheGroup **cp = &m->rrcache_hash[slot]; | |
5227 | while (*cp) | |
5228 | { | |
5229 | CacheRecord **rp = &(*cp)->members; | |
5230 | while (*rp) | |
5231 | { | |
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) | |
5235 | rp=&(*rp)->next; | |
5236 | else | |
5237 | { | |
5238 | CacheRecord *rr = *rp; | |
5239 | *rp = (*rp)->next; // Cut record from list | |
5240 | ReleaseCacheRecord(m, rr); | |
5241 | } | |
5242 | } | |
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); | |
5248 | } | |
5249 | } | |
f0cc3e7b A |
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); | |
83fb1e36 A |
5252 | } |
5253 | ||
5254 | if (m->rrcache_free) // If there are records in the free list, take one | |
5255 | { | |
5256 | e = m->rrcache_free; | |
5257 | m->rrcache_free = e->next; | |
5258 | if (++m->rrcache_totalused >= m->rrcache_report) | |
5259 | { | |
f0cc3e7b | 5260 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "RR Cache now using %u objects", m->rrcache_totalused); |
83fb1e36 A |
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; | |
5264 | } | |
5265 | mDNSPlatformMemZero(e, sizeof(*e)); | |
5266 | } | |
5267 | ||
5268 | m->lock_rrcache = 0; | |
5269 | ||
5270 | return(e); | |
5271 | } | |
283ee3ff A |
5272 | |
5273 | mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength) | |
83fb1e36 A |
5274 | { |
5275 | CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg); | |
5276 | if (r) | |
5277 | { | |
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 | |
5280 | { | |
f0cc3e7b | 5281 | r->resrec.rdata = (RData*) mDNSPlatformMemAllocateClear(sizeofRDataHeader + RDLength); |
83fb1e36 A |
5282 | if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength; |
5283 | else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; } | |
5284 | } | |
5285 | } | |
5286 | return(r); | |
5287 | } | |
6528fe3e | 5288 | |
283ee3ff | 5289 | mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr) |
83fb1e36 A |
5290 | { |
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; | |
9f221bca | 5298 | if (namelen > sizeof(cg->namestorage)) |
f0cc3e7b | 5299 | cg->name = (domainname *) mDNSPlatformMemAllocate(namelen); |
83fb1e36 A |
5300 | else |
5301 | cg->name = (domainname*)cg->namestorage; | |
5302 | if (!cg->name) | |
5303 | { | |
5304 | LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c); | |
5305 | ReleaseCacheEntity(m, (CacheEntity*)cg); | |
5306 | return(mDNSNULL); | |
5307 | } | |
5308 | AssignDomainName(cg->name, rr->name); | |
5309 | ||
12c5fa7a | 5310 | if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c); |
83fb1e36 | 5311 | m->rrcache_hash[slot] = cg; |
12c5fa7a | 5312 | if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c); |
83fb1e36 A |
5313 | |
5314 | return(cg); | |
5315 | } | |
6528fe3e | 5316 | |
67c8f8a1 | 5317 | mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr) |
83fb1e36 | 5318 | { |
51601d48 A |
5319 | mDNS_CheckLock(m); |
5320 | ||
83fb1e36 A |
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); | |
5330 | } | |
6528fe3e | 5331 | |
7f0064bd | 5332 | mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m) |
83fb1e36 A |
5333 | { |
5334 | mDNSs32 time; | |
5335 | mDNSPlatformLock(m); | |
5336 | if (m->mDNS_busy) | |
5337 | { | |
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); | |
5340 | } | |
5341 | ||
5342 | if (m->timenow) time = m->timenow; | |
5343 | else time = mDNS_TimeNow_NoLock(m); | |
5344 | mDNSPlatformUnlock(m); | |
5345 | return(time); | |
5346 | } | |
6528fe3e | 5347 | |
32bb7e43 A |
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 { \ | |
12c5fa7a | 5352 | if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \ |
83fb1e36 | 5353 | m->SPSProxyListChanged = (X); } while(0) |
32bb7e43 A |
5354 | |
5355 | // Called from mDNS_Execute() to expire stale proxy records | |
5356 | mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list) | |
83fb1e36 A |
5357 | { |
5358 | m->CurrentRecord = list; | |
5359 | while (m->CurrentRecord) | |
5360 | { | |
5361 | AuthRecord *rr = m->CurrentRecord; | |
5362 | if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0]) | |
5363 | { | |
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 | |
5367 | { | |
5368 | if (m->NextScheduledSPS - rr->TimeExpire > 0) | |
5369 | m->NextScheduledSPS = rr->TimeExpire; | |
5370 | } | |
5371 | else // else proxy record expired, so remove it | |
5372 | { | |
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 | |
5378 | } | |
5379 | } | |
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; | |
5384 | } | |
5385 | } | |
294beb6e A |
5386 | |
5387 | mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m) | |
83fb1e36 A |
5388 | { |
5389 | while (m->CurrentRecord) | |
5390 | { | |
5391 | AuthRecord *rr = m->CurrentRecord; | |
5392 | if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering) | |
5393 | { | |
5394 | debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr)); | |
5395 | rr->resrec.RecordType = kDNSRecordTypeShared; | |
f0cc3e7b | 5396 | AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); |
83fb1e36 A |
5397 | if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now |
5398 | { | |
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); | |
5404 | } | |
5405 | } | |
5406 | if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now | |
5407 | m->CurrentRecord = rr->next; | |
5408 | } | |
5409 | } | |
294beb6e | 5410 | |
12c5fa7a | 5411 | mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID) |
83fb1e36 | 5412 | { |
83fb1e36 A |
5413 | if (m->CurrentQuestion) |
5414 | LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, | |
5415 | DNSTypeName(m->CurrentQuestion->qtype)); | |
12c5fa7a | 5416 | m->CurrentQuestion = questions; |
83fb1e36 A |
5417 | while (m->CurrentQuestion) |
5418 | { | |
5419 | DNSQuestion *const q = m->CurrentQuestion; | |
5420 | if (q->StopTime) | |
5421 | { | |
51601d48 A |
5422 | if (!q->TimeoutQuestion) |
5423 | LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
5424 | ||
83fb1e36 A |
5425 | if (m->timenow - q->StopTime >= 0) |
5426 | { | |
51601d48 | 5427 | LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime); |
12c5fa7a A |
5428 | q->LOAddressAnswers = 0; // unset since timing out the question |
5429 | GenerateNegativeResponse(m, InterfaceID, QC_forceresponse); | |
83fb1e36 A |
5430 | if (m->CurrentQuestion == q) q->StopTime = 0; |
5431 | } | |
5432 | else | |
5433 | { | |
5434 | if (m->NextScheduledStopTime - q->StopTime > 0) | |
5435 | m->NextScheduledStopTime = q->StopTime; | |
5436 | } | |
5437 | } | |
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; | |
5443 | } | |
5444 | m->CurrentQuestion = mDNSNULL; | |
5445 | } | |
5446 | ||
12c5fa7a A |
5447 | mDNSlocal void TimeoutQuestions(mDNS *const m) |
5448 | { | |
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); | |
5452 | } | |
5453 | ||
83fb1e36 A |
5454 | mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m) |
5455 | { | |
341ce4f4 A |
5456 | AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL; |
5457 | LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__); | |
341ce4f4 | 5458 | while (rrPtr) |
83fb1e36 | 5459 | { |
341ce4f4 A |
5460 | rrNext = rrPtr->next; |
5461 | mDNSPlatformMemFree(rrPtr); | |
5462 | rrPtr = rrNext; | |
83fb1e36 | 5463 | } |
341ce4f4 | 5464 | m->SPSRRSet = mDNSNULL; |
83fb1e36 | 5465 | } |
32bb7e43 | 5466 | |
c9b9ae52 | 5467 | mDNSexport mDNSs32 mDNS_Execute(mDNS *const m) |
83fb1e36 A |
5468 | { |
5469 | mDNS_Lock(m); // Must grab lock before trying to read m->timenow | |
5470 | ||
5471 | if (m->timenow - m->NextScheduledEvent >= 0) | |
5472 | { | |
5473 | int i; | |
5474 | AuthRecord *head, *tail; | |
5475 | mDNSu32 slot; | |
5476 | AuthGroup *ag; | |
5477 | ||
5478 | verbosedebugf("mDNS_Execute"); | |
5479 | ||
5480 | if (m->CurrentQuestion) | |
5481 | LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)", | |
5482 | m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); | |
5483 | ||
5484 | if (m->CurrentRecord) | |
5485 | LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord)); | |
5486 | ||
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; | |
5489 | ||
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; | |
5492 | ||
5493 | // 3. Purge our cache of stale old records | |
5494 | if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0) | |
5495 | { | |
5496 | mDNSu32 numchecked = 0; | |
12c5fa7a | 5497 | m->NextCacheCheck = m->timenow + FutureTime; |
83fb1e36 A |
5498 | for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) |
5499 | { | |
5500 | if (m->timenow - m->rrcache_nextcheck[slot] >= 0) | |
5501 | { | |
5502 | CacheGroup **cp = &m->rrcache_hash[slot]; | |
12c5fa7a | 5503 | m->rrcache_nextcheck[slot] = m->timenow + FutureTime; |
83fb1e36 A |
5504 | while (*cp) |
5505 | { | |
5506 | debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL"); | |
5507 | numchecked++; | |
5508 | CheckCacheExpiration(m, slot, *cp); | |
5509 | if ((*cp)->members) cp=&(*cp)->next; | |
5510 | else ReleaseCacheGroup(m, cp); | |
5511 | } | |
5512 | } | |
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]; | |
5517 | } | |
5518 | debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow); | |
5519 | } | |
5520 | ||
5521 | if (m->timenow - m->NextScheduledSPS >= 0) | |
5522 | { | |
12c5fa7a | 5523 | m->NextScheduledSPS = m->timenow + FutureTime; |
83fb1e36 A |
5524 | CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords |
5525 | CheckProxyRecords(m, m->ResourceRecords); | |
5526 | } | |
5527 | ||
5528 | SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now | |
5529 | ||
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) | |
5533 | { | |
12c5fa7a | 5534 | m->NextScheduledKA = m->timenow + FutureTime; |
83fb1e36 A |
5535 | mDNS_SendKeepalives(m); |
5536 | } | |
5537 | ||
f0cc3e7b | 5538 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca A |
5539 | if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0)) |
5540 | { | |
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; | |
5546 | ||
5547 | LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group."); | |
5548 | } | |
f0cc3e7b | 5549 | #endif |
9f221bca | 5550 | |
83fb1e36 A |
5551 | // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().) |
5552 | if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0) | |
5553 | { | |
5554 | m->AnnounceOwner = 0; | |
341ce4f4 | 5555 | } |
83fb1e36 A |
5556 | |
5557 | if (m->DelaySleep && m->timenow - m->DelaySleep >= 0) | |
5558 | { | |
5559 | m->DelaySleep = 0; | |
5560 | if (m->SleepState == SleepState_Transferring) | |
5561 | { | |
5562 | LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers"); | |
5563 | BeginSleepProcessing(m); | |
5564 | } | |
5565 | } | |
5566 | ||
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++) | |
5569 | { | |
5570 | if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break; | |
5571 | AnswerNewQuestion(m); | |
5572 | } | |
5573 | if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit"); | |
5574 | ||
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++) | |
5578 | { | |
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) | |
5585 | { | |
5586 | m->CurrentRecord = ag->members; | |
5587 | if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m); | |
5588 | } | |
5589 | } | |
5590 | ||
5591 | if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit"); | |
5592 | ||
5593 | for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m); | |
5594 | if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit"); | |
5595 | ||
5596 | head = tail = mDNSNULL; | |
5597 | for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++) | |
5598 | { | |
5599 | AuthRecord *rr = m->NewLocalRecords; | |
5600 | m->NewLocalRecords = m->NewLocalRecords->next; | |
5601 | if (LocalRecordReady(rr)) | |
5602 | { | |
5603 | debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr)); | |
f0cc3e7b | 5604 | AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add); |
83fb1e36 A |
5605 | } |
5606 | else if (!rr->next) | |
5607 | { | |
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); | |
5614 | ||
5615 | head = rr; | |
5616 | } | |
5617 | else | |
5618 | { | |
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; } | |
5626 | if (!head) | |
5627 | { | |
5628 | while (*p) p=&(*p)->next; | |
5629 | *p = rr; | |
5630 | head = tail = rr; | |
5631 | } | |
5632 | else | |
5633 | { | |
5634 | tail->next = rr; | |
5635 | tail = rr; | |
5636 | } | |
5637 | rr->next = mDNSNULL; | |
5638 | } | |
5639 | } | |
5640 | m->NewLocalRecords = head; | |
5641 | debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL")); | |
5642 | ||
5643 | if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit"); | |
5644 | ||
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) | |
5648 | { | |
5649 | m->NewLocalOnlyRecords = mDNSfalse; | |
5650 | for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) | |
f0cc3e7b | 5651 | { |
83fb1e36 A |
5652 | for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next) |
5653 | { | |
5654 | for (i=0; i<100 && ag->NewLocalOnlyRecords; i++) | |
5655 | { | |
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)) | |
5660 | { | |
5661 | debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr)); | |
f0cc3e7b | 5662 | AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add); |
83fb1e36 A |
5663 | } |
5664 | else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr)); | |
5665 | } | |
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"); | |
5668 | } | |
f0cc3e7b | 5669 | } |
83fb1e36 A |
5670 | } |
5671 | ||
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)) | |
5676 | { | |
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; | |
5684 | ||
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) | |
5688 | { | |
5689 | DNSQuestion *q; | |
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)); | |
5696 | } | |
5697 | if (m->timenow - m->NextScheduledProbe >= 0) | |
5698 | { | |
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; | |
5702 | } | |
5703 | ||
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) | |
5707 | { | |
5708 | LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second"); | |
5709 | m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond; | |
5710 | } | |
5711 | } | |
5712 | ||
5713 | // Clear RandomDelay values, ready to pick a new different value next time | |
5714 | m->RandomQueryDelay = 0; | |
5715 | m->RandomReconfirmDelay = 0; | |
5716 | ||
12c5fa7a | 5717 | // See if any questions (or local-only questions) have timed out |
83fb1e36 | 5718 | if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m); |
263eeeab | 5719 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
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); | |
263eeeab | 5723 | #endif |
12c5fa7a | 5724 | #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR |
9f221bca A |
5725 | extern void serviceBLE(); |
5726 | if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE(); | |
12c5fa7a | 5727 | #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR |
83fb1e36 A |
5728 | } |
5729 | ||
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. | |
5733 | // | |
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. | |
5743 | // | |
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). | |
5749 | ||
5750 | mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value | |
5751 | return(m->NextScheduledEvent); | |
5752 | } | |
6528fe3e | 5753 | |
51601d48 | 5754 | #ifndef UNICAST_DISABLED |
96f69b28 | 5755 | mDNSlocal void SuspendLLQs(mDNS *m) |
83fb1e36 A |
5756 | { |
5757 | DNSQuestion *q; | |
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); } | |
5761 | } | |
51601d48 | 5762 | #endif // UNICAST_DISABLED |
96f69b28 | 5763 | |
294beb6e | 5764 | mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q) |
83fb1e36 A |
5765 | { |
5766 | AuthRecord *rr; | |
83fb1e36 A |
5767 | AuthGroup *ag; |
5768 | ||
12c5fa7a | 5769 | ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); |
83fb1e36 A |
5770 | if (ag) |
5771 | { | |
5772 | for (rr = ag->members; rr; rr=rr->next) | |
5773 | // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME | |
51601d48 | 5774 | if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q)) |
83fb1e36 A |
5775 | { |
5776 | LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr)); | |
5777 | return mDNStrue; | |
5778 | } | |
5779 | } | |
5780 | return mDNSfalse; | |
5781 | } | |
294beb6e | 5782 | |
5e65c77f A |
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) | |
83fb1e36 | 5790 | { |
83fb1e36 A |
5791 | if (!question->DuplicateOf) |
5792 | { | |
f0cc3e7b A |
5793 | debugf("ActivateUnicastQuery: %##s %s%s", |
5794 | question->qname.c, DNSTypeName(question->qtype), ScheduleImmediately ? " ScheduleImmediately" : ""); | |
83fb1e36 A |
5795 | question->CNAMEReferrals = 0; |
5796 | if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; } | |
5797 | if (question->LongLived) | |
5798 | { | |
f0cc3e7b | 5799 | question->state = LLQ_Init; |
83fb1e36 A |
5800 | question->id = zeroOpaque64; |
5801 | question->servPort = zeroIPPort; | |
5802 | if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; } | |
5803 | } | |
5804 | // If the question has local answers, then we don't want answers from outside | |
5805 | if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question)) | |
5806 | { | |
5807 | question->ThisQInterval = InitialQuestionInterval; | |
5808 | question->LastQTime = m->timenow - question->ThisQInterval; | |
5809 | SetNextQueryTime(m, question); | |
5810 | } | |
5811 | } | |
5812 | } | |
96f69b28 | 5813 | |
294beb6e A |
5814 | // Caller should hold the lock |
5815 | mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords, | |
83fb1e36 A |
5816 | CallbackBeforeStartQuery BeforeStartCallback, void *context) |
5817 | { | |
5818 | DNSQuestion *q; | |
5819 | DNSQuestion *restart = mDNSNULL; | |
5820 | ||
51601d48 | 5821 | mDNS_CheckLock(m); |
83fb1e36 A |
5822 | |
5823 | // 1. Flush the cache records | |
5824 | if (flushCacheRecords) flushCacheRecords(m); | |
5825 | ||
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. | |
5829 | // | |
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 | |
5835 | ||
5836 | if (m->RestartQuestion) | |
5837 | LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)", | |
5838 | m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype)); | |
5839 | ||
5840 | m->RestartQuestion = m->Questions; | |
5841 | while (m->RestartQuestion) | |
5842 | { | |
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. | |
5850 | ||
5851 | if (IsGetZoneDataQuestion(q)) | |
5852 | { | |
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 | |
5856 | while (refq) | |
5857 | { | |
5858 | if (q == &refq->nta->question) | |
5859 | { | |
5860 | LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q); | |
5861 | } | |
5862 | refq = refq->next; | |
5863 | } | |
5864 | continue; | |
5865 | } | |
5866 | ||
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; | |
5869 | ||
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) | |
5874 | { | |
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. | |
5883 | ||
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; } | |
5886 | ||
f0cc3e7b | 5887 | // Suppressed status does not affect questions that are answered using local records |
83fb1e36 A |
5888 | if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; } |
5889 | ||
f0cc3e7b A |
5890 | LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q, |
5891 | q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains); | |
83fb1e36 | 5892 | mDNS_StopQuery_internal(m, q); |
f0cc3e7b | 5893 | if (q->ResetHandler) q->ResetHandler(q); |
83fb1e36 A |
5894 | q->next = restart; |
5895 | restart = q; | |
5896 | } | |
5897 | } | |
5898 | ||
5899 | // 3. Callback before we start the query | |
5900 | if (BeforeStartCallback) BeforeStartCallback(m, context); | |
5901 | ||
5902 | // 4. Restart all the stopped queries | |
5903 | while (restart) | |
5904 | { | |
5905 | q = restart; | |
5906 | restart = restart->next; | |
5907 | q->next = mDNSNULL; | |
5908 | LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype)); | |
5909 | mDNS_StartQuery_internal(m, q); | |
5910 | } | |
5911 | } | |
294beb6e | 5912 | |
32bb7e43 | 5913 | mDNSexport void mDNSCoreRestartQueries(mDNS *const m) |
83fb1e36 A |
5914 | { |
5915 | DNSQuestion *q; | |
6528fe3e | 5916 | |
7f0064bd | 5917 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
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) | |
5924 | { | |
5925 | q = m->CurrentQuestion; | |
5926 | m->CurrentQuestion = m->CurrentQuestion->next; | |
19fa75a9 A |
5927 | if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) |
5928 | { | |
5929 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
5930 | mdns_querier_forget(&q->querier); | |
5931 | #endif | |
5932 | ActivateUnicastQuery(m, q, mDNStrue); | |
5933 | } | |
83fb1e36 | 5934 | } |
32bb7e43 | 5935 | #endif |
c9b9ae52 | 5936 | |
83fb1e36 A |
5937 | // Retrigger all our mDNS questions |
5938 | for (q = m->Questions; q; q=q->next) // Scan our list of questions | |
5939 | mDNSCoreRestartQuestion(m, q); | |
5940 | } | |
5941 | ||
5942 | // restart question if it's multicast and currently active | |
5943 | mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q) | |
5944 | { | |
5945 | if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) | |
5946 | { | |
5947 | q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question | |
9f221bca | 5948 | q->RequestUnicast = kDefaultRequestUnicastCount; |
83fb1e36 A |
5949 | q->LastQTime = m->timenow - q->ThisQInterval; |
5950 | q->RecentAnswerPkts = 0; | |
5951 | ExpireDupSuppressInfo(q->DupSuppress, m->timenow); | |
5952 | m->NextScheduledQuery = m->timenow; | |
5953 | } | |
5954 | } | |
5955 | ||
5956 | // restart the probe/announce cycle for multicast record | |
9f221bca | 5957 | mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount) |
83fb1e36 A |
5958 | { |
5959 | if (!AuthRecord_uDNS(rr)) | |
5960 | { | |
5961 | if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique; | |
5962 | rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType); | |
5963 | ||
51601d48 | 5964 | if (mDNS_KeepaliveRecord(&rr->resrec)) |
9f221bca A |
5965 | { |
5966 | rr->AnnounceCount = 0; // Do not announce keepalive records | |
5967 | } | |
51601d48 | 5968 | else |
9f221bca A |
5969 | { |
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; | |
5975 | } | |
5976 | ||
83fb1e36 A |
5977 | rr->SendNSECNow = mDNSNULL; |
5978 | InitializeLastAPTime(m, rr); | |
5979 | } | |
5980 | } | |
32bb7e43 A |
5981 | |
5982 | // *************************************************************************** | |
5983 | #if COMPILER_LIKES_PRAGMA_MARK | |
5984 | #pragma mark - | |
5985 | #pragma mark - Power Management (Sleep/Wake) | |
7f0064bd | 5986 | #endif |
6528fe3e | 5987 | |
263eeeab | 5988 | mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m) |
83fb1e36 | 5989 | { |
263eeeab | 5990 | #ifndef IDLESLEEPCONTROL_DISABLED |
83fb1e36 A |
5991 | mDNSBool allowSleep = mDNStrue; |
5992 | char reason[128]; | |
5993 | ||
5994 | reason[0] = 0; | |
5995 | ||
5996 | if (m->SystemSleepOnlyIfWakeOnLAN) | |
5997 | { | |
5998 | // Don't sleep if we are a proxy for any services | |
5999 | if (m->ProxyRecords) | |
6000 | { | |
6001 | allowSleep = mDNSfalse; | |
6002 | mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords); | |
51601d48 | 6003 | LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords); |
83fb1e36 A |
6004 | } |
6005 | ||
6006 | if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m)) | |
6007 | { | |
6008 | // Scan the list of active interfaces | |
6009 | NetworkInterfaceInfo *intf; | |
6010 | for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) | |
6011 | { | |
51601d48 | 6012 | if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID)) |
83fb1e36 A |
6013 | { |
6014 | // Disallow sleep if this interface doesn't support NetWake | |
6015 | if (!intf->NetWake) | |
6016 | { | |
6017 | allowSleep = mDNSfalse; | |
6018 | mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname); | |
51601d48 | 6019 | LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname); |
83fb1e36 A |
6020 | break; |
6021 | } | |
6022 | ||
9f221bca A |
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)) | |
6028 | #endif | |
f9f18293 | 6029 | { |
9f221bca A |
6030 | // Disallow sleep if there is no sleep proxy server |
6031 | const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL); | |
6032 | if ( cr == mDNSNULL) | |
f9f18293 A |
6033 | { |
6034 | allowSleep = mDNSfalse; | |
9f221bca A |
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); | |
f9f18293 A |
6037 | break; |
6038 | } | |
9f221bca A |
6039 | else if (m->SPSType != 0) |
6040 | { | |
6041 | mDNSu32 mymetric = LocalSPSMetric(m); | |
6042 | mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c); | |
6043 | if (metric >= mymetric) | |
6044 | { | |
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); | |
6048 | break; | |
6049 | } | |
6050 | } | |
f9f18293 | 6051 | } |
83fb1e36 A |
6052 | } |
6053 | } | |
6054 | } | |
6055 | } | |
6056 | ||
6057 | // Call the platform code to enable/disable sleep | |
12c5fa7a | 6058 | mDNSPlatformSetAllowSleep(allowSleep, reason); |
51601d48 | 6059 | #else |
f9f18293 | 6060 | (void) m; |
294beb6e | 6061 | #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */ |
83fb1e36 A |
6062 | } |
6063 | ||
6064 | mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid) | |
6065 | { | |
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 | |
6068 | // to send. | |
9f221bca | 6069 | if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) || |
51601d48 A |
6070 | m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0) |
6071 | { | |
83fb1e36 | 6072 | return mDNSfalse; |
51601d48 | 6073 | } |
83fb1e36 A |
6074 | |
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. | |
6079 | // | |
6080 | // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the | |
9f221bca | 6081 | // platform function to extract the value from "intf" every time. |
83fb1e36 A |
6082 | |
6083 | if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) && | |
6084 | (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)) | |
6085 | return mDNStrue; | |
6086 | ||
6087 | return mDNSfalse; | |
6088 | } | |
6089 | ||
9f221bca | 6090 | mDNSexport void UpdateRMAC(mDNS *const m, void *context) |
51601d48 A |
6091 | { |
6092 | IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ; | |
6093 | m->CurrentRecord = m->ResourceRecords; | |
6094 | ||
6095 | if (!addrmap) | |
6096 | { | |
9f221bca | 6097 | LogMsg("UpdateRMAC: Address mapping is NULL"); |
51601d48 A |
6098 | return; |
6099 | } | |
6100 | ||
6101 | while (m->CurrentRecord) | |
6102 | { | |
6103 | AuthRecord *rr = m->CurrentRecord; | |
9f221bca A |
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)) | |
51601d48 A |
6106 | { |
6107 | mDNSAddr raddr; | |
6108 | getKeepaliveRaddr(m, rr, &raddr); | |
6109 | if (mDNSSameAddress(&raddr, &addrmap->ipaddr)) | |
6110 | { | |
9f221bca A |
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)) | |
6115 | { | |
6116 | UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr)); | |
6117 | } | |
51601d48 A |
6118 | } |
6119 | } | |
6120 | m->CurrentRecord = rr->next; | |
6121 | } | |
6122 | ||
6123 | if (addrmap) | |
51601d48 | 6124 | mDNSPlatformMemFree(addrmap); |
9f221bca | 6125 | |
51601d48 A |
6126 | } |
6127 | ||
6128 | mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr) | |
83fb1e36 A |
6129 | { |
6130 | mDNSu16 newrdlength; | |
9f221bca A |
6131 | mDNSAddr laddr = zeroAddr; |
6132 | mDNSAddr raddr = zeroAddr; | |
6133 | mDNSEthAddr eth = zeroEthAddr; | |
6134 | mDNSIPPort lport = zeroIPPort; | |
6135 | mDNSIPPort rport = zeroIPPort; | |
6136 | mDNSu32 timeout = 0; | |
6137 | mDNSu32 seq = 0; | |
6138 | mDNSu32 ack = 0; | |
6139 | mDNSu16 win = 0; | |
83fb1e36 A |
6140 | UTF8str255 txt; |
6141 | int rdsize; | |
6142 | RData *newrd; | |
6143 | mDNSTCPInfo mti; | |
6144 | mStatus ret; | |
6145 | ||
83fb1e36 A |
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. | |
51601d48 | 6148 | mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); |
9f221bca | 6149 | if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport)) |
83fb1e36 A |
6150 | { |
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; | |
6153 | } | |
6154 | ||
51601d48 | 6155 | if (updateMac) |
83fb1e36 | 6156 | { |
51601d48 A |
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); | |
6159 | else | |
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); | |
83fb1e36 | 6161 | |
83fb1e36 | 6162 | } |
83fb1e36 | 6163 | else |
51601d48 A |
6164 | { |
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)); | |
12c5fa7a | 6169 | ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti); |
51601d48 A |
6170 | if (ret != mStatus_NoError) |
6171 | { | |
6172 | LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret); | |
6173 | return ret; | |
6174 | } | |
6175 | if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID)) | |
6176 | { | |
ecbd2ee4 | 6177 | LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID); |
51601d48 A |
6178 | return mStatus_BadParamErr; |
6179 | } | |
6180 | ||
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); | |
6183 | else | |
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); | |
6185 | } | |
83fb1e36 A |
6186 | |
6187 | // Did we insert a null byte at the end ? | |
6188 | if (newrdlength == (sizeof(txt.c) - 1)) | |
6189 | { | |
6190 | LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr)); | |
6191 | return mStatus_NoMemoryErr; | |
6192 | } | |
6193 | ||
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 | |
6197 | newrdlength += 2; | |
6198 | ||
6199 | rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody); | |
f0cc3e7b | 6200 | newrd = (RData *) mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize); |
83fb1e36 A |
6201 | if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; } |
6202 | ||
6203 | newrd->MaxRDLength = (mDNSu16) rdsize; | |
6204 | mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength); | |
6205 | ||
51601d48 A |
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) | |
83fb1e36 | 6211 | { |
51601d48 | 6212 | LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr)); |
9f221bca | 6213 | mDNSPlatformMemFree(rr->resrec.rdata); |
83fb1e36 | 6214 | } |
51601d48 | 6215 | SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata |
83fb1e36 A |
6216 | |
6217 | LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr)); | |
6218 | return mStatus_NoError; | |
6219 | } | |
263eeeab | 6220 | |
294beb6e | 6221 | mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner) |
83fb1e36 A |
6222 | { |
6223 | const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC); | |
6224 | const int sps = intf->NextSPSAttempt / 3; | |
6225 | AuthRecord *rr; | |
6226 | mDNSOpaque16 msgid; | |
6227 | mDNSu32 scopeid; | |
6228 | ||
6229 | scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue); | |
6230 | if (!intf->SPSAddr[sps].type) | |
6231 | { | |
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); | |
6236 | goto exit; | |
6237 | } | |
6238 | ||
6239 | // Mark our mDNS records (not unicast records) for transfer to SPS | |
6240 | if (mDNSOpaque16IsZero(id)) | |
6241 | { | |
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. | |
6246 | // | |
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) | |
51601d48 A |
6252 | { |
6253 | if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering) | |
6254 | { | |
83fb1e36 | 6255 | if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name)))) |
51601d48 | 6256 | { |
83fb1e36 A |
6257 | if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner))) |
6258 | { | |
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; | |
6265 | else | |
6266 | msgid = rr->updateid; | |
6267 | } | |
51601d48 A |
6268 | } |
6269 | } | |
6270 | } | |
83fb1e36 A |
6271 | } |
6272 | else | |
6273 | msgid = id; | |
6274 | ||
6275 | while (1) | |
6276 | { | |
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); | |
6283 | ||
6284 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
6285 | if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid)) | |
6286 | { | |
6287 | if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner))) | |
6288 | { | |
6289 | mDNSu8 *newptr; | |
6290 | const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace; | |
6291 | ||
6292 | // If we can't update the keepalive record, don't send it | |
51601d48 | 6293 | if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError)) |
83fb1e36 A |
6294 | { |
6295 | if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY)) | |
6296 | { | |
6297 | bit_clr_opaque64(rr->updateIntID, scopeid); | |
6298 | } | |
51601d48 | 6299 | rr->SendRNow = mDNSNULL; |
83fb1e36 A |
6300 | continue; |
6301 | } | |
6302 | ||
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 | |
6307 | if (!newptr) | |
6308 | LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr)); | |
6309 | else | |
6310 | { | |
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); | |
6319 | p = newptr; | |
6320 | } | |
6321 | } | |
6322 | } | |
6323 | ||
6324 | if (!m->omsg.h.mDNS_numUpdates) break; | |
6325 | else | |
6326 | { | |
6327 | AuthRecord opt; | |
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 | |
6338 | { | |
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; | |
6342 | } | |
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); | |
6345 | if (!p) | |
6346 | LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt)); | |
6347 | else | |
6348 | { | |
6349 | mStatus err; | |
6350 | ||
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])); | |
9f221bca | 6353 | // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss |
f0cc3e7b | 6354 | err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSfalse); |
83fb1e36 | 6355 | if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err); |
341ce4f4 | 6356 | if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1) |
83fb1e36 | 6357 | { |
341ce4f4 A |
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; | |
83fb1e36 A |
6360 | mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]); |
6361 | return; | |
6362 | } | |
6363 | } | |
6364 | } | |
6365 | } | |
6366 | ||
6367 | intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime | |
32bb7e43 A |
6368 | |
6369 | exit: | |
83fb1e36 A |
6370 | if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++; |
6371 | } | |
6528fe3e | 6372 | |
294beb6e | 6373 | mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr) |
83fb1e36 A |
6374 | { |
6375 | AuthRecord *ar; | |
6376 | for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next) | |
6377 | if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse; | |
6378 | return mDNStrue; | |
6379 | } | |
6380 | ||
6381 | mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr) | |
6382 | { | |
f0cc3e7b | 6383 | AuthRecord *newRR = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(*newRR)); |
341ce4f4 | 6384 | if (newRR == mDNSNULL) |
83fb1e36 | 6385 | { |
341ce4f4 | 6386 | LogSPS("%s : could not allocate memory for new resource record", __func__); |
83fb1e36 A |
6387 | return; |
6388 | } | |
6389 | ||
83fb1e36 A |
6390 | mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype, |
6391 | rr->resrec.rroriginalttl, rr->resrec.RecordType, | |
6392 | rr->ARType, mDNSNULL, mDNSNULL); | |
6393 | ||
6394 | AssignDomainName(&newRR->namestorage, &rr->namestorage); | |
341ce4f4 A |
6395 | newRR->resrec.rdlength = DomainNameLength(rr->resrec.name); |
6396 | newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name); | |
6397 | newRR->resrec.rrclass = rr->resrec.rrclass; | |
83fb1e36 | 6398 | |
341ce4f4 | 6399 | if (rr->resrec.rrtype == kDNSType_A) |
83fb1e36 A |
6400 | { |
6401 | newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4; | |
6402 | } | |
341ce4f4 | 6403 | else if (rr->resrec.rrtype == kDNSType_AAAA) |
83fb1e36 A |
6404 | { |
6405 | newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6; | |
6406 | } | |
6407 | SetNewRData(&newRR->resrec, mDNSNULL, 0); | |
6408 | ||
6409 | // Insert the new node at the head of the list. | |
341ce4f4 A |
6410 | newRR->next = m->SPSRRSet; |
6411 | m->SPSRRSet = newRR; | |
341ce4f4 | 6412 | LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr)); |
83fb1e36 A |
6413 | } |
6414 | ||
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 | |
51601d48 | 6420 | mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService) |
83fb1e36 A |
6421 | { |
6422 | AuthRecord *ar; | |
6423 | LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]); | |
9f221bca | 6424 | |
51601d48 | 6425 | *WakeOnlyService = mDNSfalse; |
341ce4f4 | 6426 | |
83fb1e36 A |
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); | |
6430 | ||
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) | |
6434 | { | |
51601d48 A |
6435 | ar->updateIntID = zeroOpaque64; |
6436 | ar->updateid = zeroID; | |
83fb1e36 A |
6437 | if (AuthRecord_uDNS(ar)) |
6438 | { | |
6439 | continue; | |
6440 | } | |
51601d48 A |
6441 | if (ar->AuthFlags & AuthFlagsWakeOnly) |
6442 | { | |
6443 | if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye) | |
6444 | { | |
6445 | ar->ImmedAnswer = mDNSInterfaceMark; | |
6446 | *WakeOnlyService = mDNStrue; | |
6447 | continue; | |
6448 | } | |
6449 | } | |
83fb1e36 A |
6450 | if (!ar->resrec.InterfaceID) |
6451 | { | |
6452 | LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar)); | |
6453 | ar->updateIntID = updateIntID; | |
6454 | } | |
6455 | else | |
6456 | { | |
6457 | // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures | |
6458 | // exactly this. | |
6459 | mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue); | |
6460 | if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid)) | |
6461 | { | |
83fb1e36 | 6462 | bit_set_opaque64(ar->updateIntID, scopeid); |
51601d48 A |
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)); | |
83fb1e36 A |
6465 | } |
6466 | else | |
6467 | { | |
6468 | LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid); | |
6469 | } | |
6470 | } | |
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) | |
6474 | { | |
6475 | mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar); | |
6476 | } | |
6477 | } | |
6478 | } | |
294beb6e A |
6479 | |
6480 | mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id) | |
83fb1e36 A |
6481 | { |
6482 | AuthRecord *ar; | |
6483 | OwnerOptData owner = zeroOwner; | |
6484 | ||
6485 | SendSPSRegistrationForOwner(m, intf, id, &owner); | |
6486 | ||
6487 | for (ar = m->ResourceRecords; ar; ar=ar->next) | |
6488 | { | |
6489 | if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar)) | |
6490 | { | |
6491 | owner = ar->WakeUp; | |
6492 | SendSPSRegistrationForOwner(m, intf, id, &owner); | |
6493 | } | |
6494 | } | |
6495 | } | |
294beb6e | 6496 | |
32bb7e43 A |
6497 | // RetrySPSRegistrations is called from SendResponses, with the lock held |
6498 | mDNSlocal void RetrySPSRegistrations(mDNS *const m) | |
83fb1e36 A |
6499 | { |
6500 | AuthRecord *rr; | |
6501 | NetworkInterfaceInfo *intf; | |
6502 | ||
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++; | |
6507 | ||
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) | |
6511 | { | |
6512 | for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) | |
6513 | { | |
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)) | |
6518 | { | |
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); | |
6521 | } | |
6522 | } | |
6523 | } | |
6524 | ||
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++; | |
6529 | } | |
32bb7e43 A |
6530 | |
6531 | mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord) | |
83fb1e36 A |
6532 | { |
6533 | NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext; | |
6534 | int sps = (int)(question - intf->NetWakeResolve); | |
6535 | (void)m; // Unused | |
6536 | LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer)); | |
6537 | ||
6538 | if (!AddRecord) return; // Don't care about REMOVE events | |
6539 | if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs | |
6540 | ||
9f221bca | 6541 | // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address |
83fb1e36 A |
6542 | |
6543 | if (answer->rrtype == kDNSType_SRV) | |
6544 | { | |
51601d48 | 6545 | // 1. Got the SRV record; now look up the target host's IP address |
83fb1e36 A |
6546 | mDNS_StopQuery(m, question); |
6547 | intf->SPSPort[sps] = answer->rdata->u.srv.port; | |
6548 | AssignDomainName(&question->qname, &answer->rdata->u.srv.target); | |
341ce4f4 | 6549 | question->qtype = kDNSType_A; |
83fb1e36 A |
6550 | mDNS_StartQuery(m, question); |
6551 | } | |
341ce4f4 | 6552 | else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr)) |
83fb1e36 | 6553 | { |
341ce4f4 | 6554 | // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate |
83fb1e36 A |
6555 | mDNS_StopQuery(m, question); |
6556 | question->ThisQInterval = -1; | |
341ce4f4 A |
6557 | intf->SPSAddr[sps].type = mDNSAddrType_IPv4; |
6558 | intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4; | |
83fb1e36 A |
6559 | mDNS_Lock(m); |
6560 | if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now | |
6561 | mDNS_Unlock(m); | |
6562 | } | |
341ce4f4 | 6563 | else if (answer->rrtype == kDNSType_A && answer->rdlength == 0) |
83fb1e36 | 6564 | { |
51601d48 | 6565 | // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead |
83fb1e36 | 6566 | mDNS_StopQuery(m, question); |
341ce4f4 A |
6567 | LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c); |
6568 | question->qtype = kDNSType_AAAA; | |
83fb1e36 A |
6569 | mDNS_StartQuery(m, question); |
6570 | } | |
341ce4f4 | 6571 | else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6)) |
83fb1e36 | 6572 | { |
341ce4f4 | 6573 | // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate |
83fb1e36 A |
6574 | mDNS_StopQuery(m, question); |
6575 | question->ThisQInterval = -1; | |
341ce4f4 A |
6576 | intf->SPSAddr[sps].type = mDNSAddrType_IPv6; |
6577 | intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6; | |
83fb1e36 A |
6578 | mDNS_Lock(m); |
6579 | if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now | |
6580 | mDNS_Unlock(m); | |
6581 | } | |
6582 | } | |
32bb7e43 A |
6583 | |
6584 | mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m) | |
83fb1e36 A |
6585 | { |
6586 | AuthRecord *rr; | |
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))) | |
6589 | return mDNStrue; | |
6590 | return mDNSfalse; | |
6591 | } | |
32bb7e43 | 6592 | |
9f221bca A |
6593 | #define WAKE_ONLY_SERVICE 1 |
6594 | #define AC_ONLY_SERVICE 2 | |
6595 | ||
51601d48 | 6596 | #ifdef APPLE_OSX_mDNSResponder |
9f221bca | 6597 | mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType) |
83fb1e36 A |
6598 | { |
6599 | AuthRecord *rr; | |
9f221bca | 6600 | *servicePresent = mDNSfalse; |
1a175162 | 6601 | |
83fb1e36 A |
6602 | // Mark all the records we need to deregister and send them |
6603 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
51601d48 | 6604 | { |
9f221bca A |
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))) | |
51601d48 | 6611 | { |
83fb1e36 | 6612 | rr->ImmedAnswer = mDNSInterfaceMark; |
9f221bca | 6613 | *servicePresent = mDNStrue; |
51601d48 A |
6614 | } |
6615 | } | |
83fb1e36 | 6616 | } |
9f221bca A |
6617 | #endif |
6618 | ||
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) | |
6624 | { | |
6625 | return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE); | |
6626 | } | |
6627 | #endif // APPLE_OSX_mDNSResponder | |
6628 | ||
1a175162 | 6629 | |
51601d48 A |
6630 | mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast) |
6631 | { | |
6632 | AuthRecord *rr; | |
6633 | m->SleepState = SleepState_Sleeping; | |
6634 | ||
6635 | // If AllInterfaces is not set, the caller has already marked it appropriately | |
6636 | // on which interfaces this should be sent. | |
6637 | if (AllInterfaces) | |
6638 | { | |
6639 | NetworkInterfaceInfo *intf; | |
6640 | for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) | |
6641 | { | |
6642 | intf->SendGoodbyes = 1; | |
6643 | } | |
6644 | } | |
6645 | if (unicast) | |
6646 | { | |
6647 | #ifndef UNICAST_DISABLED | |
6648 | SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records | |
6649 | #endif /* UNICAST_DISABLED */ | |
6650 | } | |
6651 | ||
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; | |
6656 | SendResponses(m); | |
6657 | } | |
6658 | ||
6659 | /* | |
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 | |
6664 | * | |
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 | |
6668 | */ | |
e257a343 A |
6669 | mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid) |
6670 | { | |
6671 | NetworkInterfaceInfo *intf; | |
6672 | NetworkInterfaceInfo *newIntf; | |
6673 | mDNSu32 i; | |
6674 | ||
509d285a | 6675 | for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next) |
e257a343 | 6676 | { |
509d285a A |
6677 | if ((newIntf->InterfaceID != intfid) || |
6678 | (newIntf->ip.type != mDNSAddrType_IPv4)) | |
e257a343 | 6679 | { |
509d285a | 6680 | continue; |
e257a343 | 6681 | } |
509d285a | 6682 | for ( i = 0; i < count; i++) |
e257a343 | 6683 | { |
509d285a A |
6684 | for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next) |
6685 | { | |
6686 | if ((intf->InterfaceID != regID[i]) || | |
6687 | (intf->ip.type != mDNSAddrType_IPv4)) | |
6688 | { | |
6689 | continue; | |
6690 | } | |
6691 | if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger)) | |
6692 | { | |
6693 | LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname); | |
6694 | return (mDNStrue); | |
6695 | } | |
6696 | } | |
e257a343 A |
6697 | } |
6698 | } | |
6699 | return (mDNSfalse); | |
6700 | } | |
6701 | ||
51601d48 A |
6702 | mDNSlocal void DoKeepaliveCallbacks(mDNS *m) |
6703 | { | |
6704 | // Loop through the keepalive records and callback with an error | |
6705 | m->CurrentRecord = m->ResourceRecords; | |
6706 | while (m->CurrentRecord) | |
6707 | { | |
6708 | AuthRecord *const rr = m->CurrentRecord; | |
6709 | if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering)) | |
6710 | { | |
6711 | LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr)); | |
6712 | if (rr->RecordCallback) | |
6713 | rr->RecordCallback(m, rr, mStatus_BadStateErr); | |
6714 | } | |
6715 | if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now | |
6716 | m->CurrentRecord = rr->next; | |
6717 | } | |
6718 | } | |
6719 | ||
32bb7e43 A |
6720 | // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep |
6721 | mDNSlocal void BeginSleepProcessing(mDNS *const m) | |
83fb1e36 A |
6722 | { |
6723 | mDNSBool SendGoodbyes = mDNStrue; | |
51601d48 A |
6724 | mDNSBool WakeOnlyService = mDNSfalse; |
6725 | mDNSBool invokeKACallback = mDNStrue; | |
83fb1e36 A |
6726 | const CacheRecord *sps[3] = { mDNSNULL }; |
6727 | mDNSOpaque64 updateIntID = zeroOpaque64; | |
9f221bca | 6728 | mDNSInterfaceID registeredIntfIDS[128] = { 0 }; |
e257a343 | 6729 | mDNSu32 registeredCount = 0; |
51601d48 | 6730 | int skippedRegistrations = 0; |
83fb1e36 A |
6731 | |
6732 | m->NextScheduledSPRetry = m->timenow; | |
6733 | ||
12c5fa7a A |
6734 | // Clear out the SCDynamic entry that stores the external SPS information |
6735 | mDNSPlatformClearSPSData(); | |
6736 | ||
83fb1e36 A |
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 | |
6740 | { | |
6741 | NetworkInterfaceInfo *intf; | |
6742 | for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) | |
6743 | { | |
ecbd2ee4 | 6744 | mDNSBool skipFullSleepProxyRegistration = mDNSfalse; |
51601d48 A |
6745 | // Intialize it to false. These values make sense only when SleepState is set to Sleeping. |
6746 | intf->SendGoodbyes = 0; | |
6747 | ||
6748 | // If it is not multicast capable, we could not have possibly discovered sleep proxy | |
6749 | // servers. | |
6750 | if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID)) | |
6751 | { | |
6752 | LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname); | |
6753 | continue; | |
6754 | } | |
6755 | ||
6756 | // If we are not capable of WOMP, then don't register with sleep proxy. | |
6757 | // | |
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. | |
6763 | if (!intf->NetWake) | |
6764 | { | |
6765 | LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname); | |
6766 | intf->SendGoodbyes = 1; | |
6767 | skippedRegistrations++; | |
6768 | continue; | |
6769 | } | |
e257a343 | 6770 | |
ecbd2ee4 A |
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. | |
e257a343 A |
6774 | if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID)) |
6775 | { | |
ecbd2ee4 A |
6776 | LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname); |
6777 | skipFullSleepProxyRegistration = mDNStrue; | |
e257a343 A |
6778 | } |
6779 | ||
1a175162 | 6780 | #if APPLE_OSX_mDNSResponder |
ecbd2ee4 | 6781 | if (SupportsInNICProxy(intf)) |
83fb1e36 | 6782 | { |
9f221bca | 6783 | mDNSBool keepaliveOnly = mDNSfalse; |
ecbd2ee4 A |
6784 | const mStatus err = ActivateLocalProxy(intf, skipFullSleepProxyRegistration, &keepaliveOnly); |
6785 | if (!skipFullSleepProxyRegistration && !err) | |
51601d48 A |
6786 | { |
6787 | SendGoodbyesForWakeOnlyService(m, &WakeOnlyService); | |
9f221bca A |
6788 | |
6789 | // Send goodbyes for all advertised services if the only record offloaded was the keepalive record. | |
6790 | SendGoodbyes = (keepaliveOnly) ? mDNStrue: mDNSfalse; | |
6791 | invokeKACallback = mDNSfalse; | |
51601d48 A |
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 | |
6796 | ||
6797 | registeredIntfIDS[registeredCount] = intf->InterfaceID; | |
6798 | registeredCount++; | |
6799 | } | |
ecbd2ee4 | 6800 | continue; |
83fb1e36 | 6801 | } |
1a175162 | 6802 | #endif // APPLE_OSX_mDNSResponder |
ecbd2ee4 | 6803 | if (!skipFullSleepProxyRegistration) |
83fb1e36 | 6804 | { |
51601d48 A |
6805 | #if APPLE_OSX_mDNSResponder |
6806 | // If on battery, do not attempt to offload to external sleep proxies | |
6807 | if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery) | |
6808 | { | |
6809 | LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy."); | |
6810 | return; | |
6811 | } | |
6812 | #endif // APPLE_OSX_mDNSResponder | |
83fb1e36 A |
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); | |
6816 | else | |
6817 | { | |
6818 | int i; | |
6819 | mDNSu32 scopeid; | |
6820 | SendGoodbyes = mDNSfalse; | |
6821 | intf->NextSPSAttempt = 0; | |
6822 | intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond; | |
6823 | ||
83fb1e36 A |
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); | |
6828 | ||
6829 | // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above | |
6830 | for (i=0; i<3; i++) | |
6831 | { | |
32bb7e43 | 6832 | #if ForceAlerts |
83fb1e36 | 6833 | if (intf->SPSAddr[i].type) |
9f221bca | 6834 | LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); |
83fb1e36 | 6835 | if (intf->NetWakeResolve[i].ThisQInterval >= 0) |
9f221bca | 6836 | LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); |
32bb7e43 | 6837 | #endif |
83fb1e36 A |
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; | |
6841 | if (sps[i]) | |
6842 | { | |
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]); | |
e257a343 A |
6847 | |
6848 | // If we are registering with a Sleep Proxy for a new subnet, add it to our list | |
6849 | registeredIntfIDS[registeredCount] = intf->InterfaceID; | |
6850 | registeredCount++; | |
83fb1e36 A |
6851 | } |
6852 | } | |
6853 | } | |
6854 | } | |
6855 | } | |
6856 | } | |
6857 | ||
6858 | // If we have at least one interface on which we are registering with an external sleep proxy, | |
6859 | // initialize all the records appropriately. | |
51601d48 A |
6860 | if (!mDNSOpaque64IsZero(&updateIntID)) |
6861 | SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService); | |
83fb1e36 | 6862 | |
51601d48 A |
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) | |
6866 | { | |
6867 | LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records"); | |
6868 | DoKeepaliveCallbacks(m); | |
6869 | } | |
6870 | ||
6871 | // SendSleepGoodbyes last two arguments control whether we send goodbyes on all | |
6872 | // interfaces and also deregister unicast registrations. | |
6873 | // | |
6874 | // - If there are no sleep proxy servers, then send goodbyes on all interfaces | |
6875 | // for both multicast and unicast. | |
9f221bca | 6876 | // |
51601d48 A |
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. | |
6880 | // | |
6881 | // - If we are not planning to send any goodbyes, then check for WakeOnlyServices. | |
6882 | // | |
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. | |
6886 | if (SendGoodbyes) | |
83fb1e36 A |
6887 | { |
6888 | LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server"); | |
51601d48 A |
6889 | SendSleepGoodbyes(m, mDNStrue, mDNStrue); |
6890 | } | |
6891 | else if (skippedRegistrations) | |
6892 | { | |
6893 | LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces"); | |
6894 | SendSleepGoodbyes(m, mDNSfalse, mDNSfalse); | |
6895 | } | |
6896 | else if (WakeOnlyService) | |
6897 | { | |
6898 | // If we saw WakeOnly service above, send the goodbyes now. | |
9f221bca | 6899 | LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService"); |
51601d48 | 6900 | SendResponses(m); |
83fb1e36 A |
6901 | } |
6902 | } | |
32bb7e43 A |
6903 | |
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) | |
83fb1e36 A |
6908 | { |
6909 | AuthRecord *rr; | |
6910 | ||
f0cc3e7b A |
6911 | LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_INFO, |
6912 | PUB_S " (old state %d) at %d", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow); | |
83fb1e36 A |
6913 | |
6914 | if (sleep && !m->SleepState) // Going to sleep | |
6915 | { | |
6916 | mDNS_Lock(m); | |
6917 | // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server | |
6918 | if (m->SPSSocket) | |
6919 | { | |
6920 | mDNSu8 oldstate = m->SPSState; | |
6921 | mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here | |
6922 | m->SPSState = 2; | |
51601d48 | 6923 | #ifndef SPC_DISABLED |
83fb1e36 | 6924 | if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords); |
51601d48 | 6925 | #else |
9f221bca | 6926 | (void)oldstate; |
51601d48 | 6927 | #endif |
83fb1e36 A |
6928 | mDNS_ReclaimLockAfterCallback(); |
6929 | } | |
564f2ae2 A |
6930 | #ifdef _LEGACY_NAT_TRAVERSAL_ |
6931 | if (m->SSDPSocket) | |
6932 | { | |
6933 | mDNSPlatformUDPClose(m->SSDPSocket); | |
6934 | m->SSDPSocket = mDNSNULL; | |
6935 | } | |
6936 | #endif | |
83fb1e36 A |
6937 | m->SleepState = SleepState_Transferring; |
6938 | if (m->SystemWakeOnLANEnabled && m->DelaySleep) | |
6939 | { | |
6940 | // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep | |
f0cc3e7b A |
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); | |
83fb1e36 A |
6943 | m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10); |
6944 | } | |
6945 | else | |
6946 | { | |
6947 | m->DelaySleep = 0; | |
6948 | m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10); | |
51601d48 | 6949 | m->mDNSStats.Sleeps++; |
19fa75a9 A |
6950 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
6951 | Querier_HandleSleep(); | |
6952 | #endif | |
83fb1e36 A |
6953 | BeginSleepProcessing(m); |
6954 | } | |
32bb7e43 A |
6955 | |
6956 | #ifndef UNICAST_DISABLED | |
83fb1e36 | 6957 | SuspendLLQs(m); |
263eeeab | 6958 | #endif |
f0cc3e7b A |
6959 | LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S ") seq %d", |
6960 | m->SleepState, | |
6961 | m->SleepState == SleepState_Transferring ? "Transferring" : | |
6962 | m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum); | |
83fb1e36 A |
6963 | mDNS_Unlock(m); |
6964 | } | |
6965 | else if (!sleep) // Waking up | |
6966 | { | |
6967 | mDNSu32 slot; | |
6968 | CacheGroup *cg; | |
6969 | CacheRecord *cr; | |
6970 | NetworkInterfaceInfo *intf; | |
51601d48 | 6971 | mDNSs32 currtime, diff; |
83fb1e36 A |
6972 | |
6973 | mDNS_Lock(m); | |
6974 | // Reset SleepLimit back to 0 now that we're awake again. | |
6975 | m->SleepLimit = 0; | |
6976 | ||
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) | |
6979 | { | |
6980 | m->SleepState = SleepState_Awake; | |
6981 | m->SleepSeqNum++; | |
6982 | // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake) | |
9f221bca | 6983 | // then we enforce a minimum delay of five seconds before we begin sleep processing. |
83fb1e36 A |
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. | |
9f221bca | 6986 | m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep); |
83fb1e36 A |
6987 | } |
6988 | ||
6989 | if (m->SPSState == 3) | |
6990 | { | |
6991 | m->SPSState = 0; | |
6992 | mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags); | |
6993 | } | |
51601d48 | 6994 | m->mDNSStats.Wakes++; |
83fb1e36 A |
6995 | // ... and the same for NextSPSAttempt |
6996 | for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1; | |
6997 | ||
19fa75a9 A |
6998 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
6999 | Querier_HandleWake(); | |
7000 | #endif | |
83fb1e36 A |
7001 | // Restart unicast and multicast queries |
7002 | mDNSCoreRestartQueries(m); | |
7003 | ||
7004 | // and reactivtate service registrations | |
7005 | m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond); | |
f0cc3e7b A |
7006 | LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, |
7007 | "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow); | |
83fb1e36 A |
7008 | |
7009 | // 2. Re-validate our cache records | |
51601d48 A |
7010 | currtime = mDNSPlatformUTC(); |
7011 | ||
51601d48 | 7012 | diff = currtime - m->TimeSlept; |
83fb1e36 A |
7013 | FORALL_CACHERECORDS(slot, cg, cr) |
7014 | { | |
51601d48 A |
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. | |
7021 | // | |
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) | |
7028 | { | |
7029 | if (diff > 0) | |
7030 | { | |
7031 | mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl); | |
7032 | const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond; | |
7033 | ||
9f221bca | 7034 | // -if we have slept longer than the remaining TTL, purge and start fresh. |
51601d48 A |
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. | |
7040 | ||
7041 | if (diff >= remain || diff > (2 * 24 * 3600)) | |
7042 | { | |
f0cc3e7b A |
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); | |
51601d48 A |
7046 | mDNS_PurgeCacheResourceRecord(m, cr); |
7047 | continue; | |
7048 | } | |
7049 | cr->TimeRcvd -= (diff * mDNSPlatformOneSecond); | |
7050 | if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0) | |
7051 | { | |
f0cc3e7b A |
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); | |
51601d48 A |
7055 | mDNS_PurgeCacheResourceRecord(m, cr); |
7056 | } | |
7057 | else | |
7058 | { | |
f0cc3e7b A |
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); | |
51601d48 A |
7062 | } |
7063 | } | |
7064 | } | |
7065 | else | |
7066 | { | |
7067 | mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake); | |
7068 | } | |
83fb1e36 A |
7069 | } |
7070 | ||
7071 | // 3. Retrigger probing and announcing for all our authoritative records | |
7072 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
51601d48 | 7073 | { |
83fb1e36 A |
7074 | if (AuthRecord_uDNS(rr)) |
7075 | { | |
7076 | ActivateUnicastRegistration(m, rr); | |
7077 | } | |
7078 | else | |
7079 | { | |
7080 | mDNSCoreRestartRegistration(m, rr, -1); | |
7081 | } | |
51601d48 | 7082 | } |
83fb1e36 A |
7083 | |
7084 | // 4. Refresh NAT mappings | |
7085 | // We don't want to have to assume that all hardware can necessarily keep accurate | |
51601d48 | 7086 | // track of passage of time while asleep, so on wake we refresh our NAT mappings. |
83fb1e36 | 7087 | // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address. |
51601d48 A |
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. | |
f0cc3e7b | 7091 | LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds"); |
51601d48 | 7092 | RecreateNATMappings(m, mDNSPlatformOneSecond * 5); |
83fb1e36 A |
7093 | mDNS_Unlock(m); |
7094 | } | |
7095 | } | |
32bb7e43 | 7096 | |
1a175162 | 7097 | mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now) |
83fb1e36 A |
7098 | { |
7099 | DNSQuestion *q; | |
7100 | AuthRecord *rr; | |
7101 | NetworkInterfaceInfo *intf; | |
7102 | ||
7103 | mDNS_Lock(m); | |
7104 | ||
7105 | if (m->DelaySleep) goto notready; | |
7106 | ||
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; | |
7109 | ||
7110 | m->NextScheduledSPRetry = now + 0x40000000UL; | |
7111 | ||
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) | |
7115 | { | |
7116 | if (now - intf->NextSPSAttemptTime >= 0) | |
7117 | { | |
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. | |
7123 | } | |
7124 | else | |
7125 | if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0) | |
7126 | m->NextScheduledSPRetry = intf->NextSPSAttemptTime; | |
7127 | } | |
7128 | ||
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)) | |
7131 | { | |
7132 | int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3; | |
7133 | if (intf->NetWakeResolve[sps].ThisQInterval >= 0) | |
7134 | { | |
7135 | LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)", | |
7136 | intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype)); | |
7137 | goto spsnotready; | |
7138 | } | |
7139 | } | |
7140 | ||
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; } | |
7146 | ||
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) | |
7150 | { | |
7151 | LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
7152 | goto notready; | |
7153 | } | |
7154 | ||
7155 | // Scan list of registered records | |
7156 | for (rr = m->ResourceRecords; rr; rr = rr->next) | |
7157 | if (AuthRecord_uDNS(rr)) | |
7158 | { | |
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; } | |
83fb1e36 A |
7161 | } |
7162 | ||
7163 | mDNS_Unlock(m); | |
7164 | return mDNStrue; | |
32bb7e43 | 7165 | |
1a175162 A |
7166 | spsnotready: |
7167 | ||
83fb1e36 A |
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) | |
7171 | { | |
7172 | LogMsg("Failed to register with SPS, now sending goodbyes"); | |
7173 | ||
7174 | for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) | |
7175 | if (intf->NetWakeBrowse.ThisQInterval >= 0) | |
7176 | { | |
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); | |
7180 | } | |
7181 | ||
7182 | for (rr = m->ResourceRecords; rr; rr = rr->next) | |
7183 | if (!AuthRecord_uDNS(rr)) | |
7184 | if (!mDNSOpaque64IsZero(&rr->updateIntID)) | |
7185 | { | |
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; | |
7188 | } | |
7189 | ||
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; | |
7197 | ||
51601d48 | 7198 | SendSleepGoodbyes(m, mDNStrue, mDNStrue); |
83fb1e36 | 7199 | } |
1a175162 | 7200 | |
32bb7e43 | 7201 | notready: |
83fb1e36 A |
7202 | mDNS_Unlock(m); |
7203 | return mDNSfalse; | |
7204 | } | |
32bb7e43 | 7205 | |
19fa75a9 | 7206 | mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now, mDNSNextWakeReason *outReason) |
83fb1e36 A |
7207 | { |
7208 | AuthRecord *ar; | |
7209 | ||
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 | |
19fa75a9 | 7215 | mDNSNextWakeReason reason = mDNSNextWakeReason_UpkeepWake; |
83fb1e36 A |
7216 | |
7217 | NATTraversalInfo *nat; | |
7218 | for (nat = m->NATTraversals; nat; nat=nat->next) | |
19fa75a9 | 7219 | { |
83fb1e36 A |
7220 | if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4) |
7221 | { | |
7222 | mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time | |
19fa75a9 A |
7223 | if ((e - t) > 0) |
7224 | { | |
7225 | e = t; | |
7226 | reason = mDNSNextWakeReason_NATPortMappingRenewal; | |
7227 | } | |
83fb1e36 A |
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); | |
7235 | } | |
19fa75a9 | 7236 | } |
83fb1e36 A |
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) | |
19fa75a9 | 7240 | { |
83fb1e36 A |
7241 | if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4) |
7242 | { | |
7243 | mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time | |
19fa75a9 A |
7244 | if ((e - t) > 0) |
7245 | { | |
7246 | e = t; | |
7247 | reason = mDNSNextWakeReason_RecordRegistrationRenewal; | |
7248 | } | |
83fb1e36 A |
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)); | |
7254 | } | |
19fa75a9 A |
7255 | } |
7256 | if (outReason) | |
7257 | { | |
7258 | *outReason = reason; | |
7259 | } | |
83fb1e36 A |
7260 | return(e - now); |
7261 | } | |
32bb7e43 A |
7262 | |
7263 | // *************************************************************************** | |
7264 | #if COMPILER_LIKES_PRAGMA_MARK | |
7265 | #pragma mark - | |
7266 | #pragma mark - Packet Reception Functions | |
7267 | #endif | |
7268 | ||
7269 | #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo) | |
7270 | ||
7271 | mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end, | |
83fb1e36 A |
7272 | const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords) |
7273 | { | |
7274 | mDNSu8 *responseptr = response->data; | |
7275 | const mDNSu8 *const limit = response->data + sizeof(response->data); | |
7276 | const mDNSu8 *ptr = query->data; | |
7277 | AuthRecord *rr; | |
f0cc3e7b | 7278 | mDNSu32 maxttl = (!InterfaceID) ? mDNSMaximumUnicastTTLSeconds : mDNSMaximumMulticastTTLSeconds; |
83fb1e36 A |
7279 | int i; |
7280 | ||
7281 | // Initialize the response fields so we can answer the questions | |
7282 | InitializeDNSMessage(&response->h, query->h.id, ResponseFlags); | |
7283 | ||
7284 | // *** | |
7285 | // *** 1. Write out the list of questions we are actually going to answer with this packet | |
7286 | // *** | |
7287 | if (LegacyQuery) | |
7288 | { | |
7289 | maxttl = kStaticCacheTTL; | |
7290 | for (i=0; i<query->h.numQuestions; i++) // For each question... | |
7291 | { | |
7292 | DNSQuestion q; | |
7293 | ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question... | |
7294 | if (!ptr) return(mDNSNULL); | |
7295 | ||
7296 | for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers | |
7297 | { | |
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 | |
7303 | } | |
7304 | } | |
7305 | } | |
7306 | ||
7307 | if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); } | |
7308 | } | |
7309 | ||
7310 | // *** | |
7311 | // *** 2. Write Answers | |
7312 | // *** | |
7313 | for (rr=ResponseRecords; rr; rr=rr->NextResponse) | |
7314 | if (rr->NR_AnswerTo) | |
7315 | { | |
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; } | |
7320 | } | |
7321 | ||
7322 | // *** | |
7323 | // *** 3. Write Additionals | |
7324 | // *** | |
7325 | for (rr=ResponseRecords; rr; rr=rr->NextResponse) | |
7326 | if (rr->NR_AdditionalTo && !rr->NR_AnswerTo) | |
7327 | { | |
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"); | |
7332 | } | |
7333 | ||
7334 | return(responseptr); | |
7335 | } | |
6528fe3e | 7336 | |
c9b9ae52 A |
7337 | // AuthRecord *our is our Resource Record |
7338 | // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network | |
6528fe3e A |
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 | |
32bb7e43 | 7342 | mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt) |
83fb1e36 A |
7343 | { |
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); } | |
7348 | ||
f0cc3e7b A |
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); | |
7354 | #endif | |
83fb1e36 A |
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 | |
7359 | ||
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 | |
7364 | ||
7365 | LogMsg("CompareRData ERROR: Invalid state"); | |
7366 | return(-1); | |
7367 | } | |
6528fe3e | 7368 | |
f0cc3e7b A |
7369 | mDNSlocal mDNSBool PacketRecordMatches(const AuthRecord *const rr, const CacheRecord *const pktrr, const AuthRecord *const master) |
7370 | { | |
7371 | if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec)) | |
7372 | { | |
7373 | const AuthRecord *r2 = rr; | |
7374 | while (r2->DependentOn) r2 = r2->DependentOn; | |
7375 | if (r2 == master) return(mDNStrue); | |
7376 | } | |
7377 | return(mDNSfalse); | |
7378 | } | |
7379 | ||
c9b9ae52 A |
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. | |
6528fe3e A |
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 | |
c9b9ae52 A |
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 | |
6528fe3e A |
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 | |
c9b9ae52 | 7389 | mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master) |
83fb1e36 A |
7390 | { |
7391 | const AuthRecord *r1; | |
7392 | for (r1 = m->ResourceRecords; r1; r1=r1->next) | |
7393 | { | |
f0cc3e7b | 7394 | if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue); |
83fb1e36 A |
7395 | } |
7396 | for (r1 = m->DuplicateRecords; r1; r1=r1->next) | |
7397 | { | |
f0cc3e7b | 7398 | if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue); |
83fb1e36 A |
7399 | } |
7400 | return(mDNSfalse); | |
7401 | } | |
6528fe3e A |
7402 | |
7403 | // Find the canonical RRSet pointer for this RR received in a packet. | |
c9b9ae52 | 7404 | // If we find any identical AuthRecord in our authoritative list, then follow its RRSet |
6528fe3e A |
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 | |
c9b9ae52 | 7407 | mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr) |
83fb1e36 A |
7408 | { |
7409 | const AuthRecord *rr; | |
7410 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
7411 | { | |
7412 | if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec)) | |
7413 | { | |
e9410223 | 7414 | return(rr->RRSet ? rr->RRSet : rr); |
83fb1e36 A |
7415 | } |
7416 | } | |
7417 | return(mDNSNULL); | |
7418 | } | |
6528fe3e A |
7419 | |
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. | |
c9b9ae52 | 7429 | mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr) |
83fb1e36 A |
7430 | { |
7431 | // If not supposed to be unique, not a conflict | |
7432 | if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse); | |
7433 | ||
7434 | // If a dependent record, not a conflict | |
7435 | if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse); | |
7436 | else | |
7437 | { | |
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); | |
7442 | ||
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); | |
7447 | } | |
7448 | ||
7449 | // Okay, this is a conflict | |
7450 | return(mDNStrue); | |
7451 | } | |
6528fe3e | 7452 | |
32bb7e43 | 7453 | // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change |
6528fe3e A |
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, | |
83fb1e36 A |
7457 | DNSQuestion *q, AuthRecord *our) |
7458 | { | |
7459 | int i; | |
7460 | const mDNSu8 *ptr = LocateAuthorities(query, end); | |
7461 | mDNSBool FoundUpdate = mDNSfalse; | |
7462 | ||
7463 | for (i = 0; i < query->h.numAuthorities; i++) | |
7464 | { | |
7465 | ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec); | |
7466 | if (!ptr) break; | |
f0cc3e7b | 7467 | if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && CacheRecordAnswersQuestion(&m->rec.r, q)) |
83fb1e36 A |
7468 | { |
7469 | FoundUpdate = mDNStrue; | |
7470 | if (PacketRRConflict(m, our, &m->rec.r)) | |
7471 | { | |
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); | |
7475 | if (result) | |
7476 | { | |
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)); | |
7480 | } | |
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. | |
7484 | if (result < 0) | |
7485 | { | |
7486 | m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond); | |
7487 | our->ProbeCount = DefaultProbeCountForTypeUnique; | |
7488 | our->AnnounceCount = InitialAnnounceCount; | |
7489 | InitializeLastAPTime(m, our); | |
7490 | goto exit; | |
7491 | } | |
7492 | } | |
32bb7e43 | 7493 | #if 0 |
83fb1e36 A |
7494 | else |
7495 | { | |
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)); | |
7498 | } | |
32bb7e43 | 7499 | #endif |
83fb1e36 A |
7500 | } |
7501 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it | |
7502 | } | |
7503 | if (!FoundUpdate) | |
7504 | LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype)); | |
7f0064bd | 7505 | exit: |
83fb1e36 A |
7506 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it |
7507 | } | |
c9b9ae52 | 7508 | |
030b743d | 7509 | mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr) |
83fb1e36 | 7510 | { |
12c5fa7a | 7511 | CacheGroup *cg = CacheGroupForRecord(m, pktrr); |
83fb1e36 A |
7512 | CacheRecord *rr; |
7513 | mDNSBool match; | |
7514 | for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) | |
7515 | { | |
7516 | if (!pktrr->InterfaceID) | |
7517 | { | |
19fa75a9 A |
7518 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
7519 | match = (pktrr->dnsservice == rr->resrec.dnsservice) ? mDNStrue : mDNSfalse; | |
7520 | #else | |
672757b6 A |
7521 | const mDNSu32 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0); |
7522 | const mDNSu32 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0); | |
83fb1e36 | 7523 | match = (id1 == id2); |
19fa75a9 | 7524 | #endif |
83fb1e36 A |
7525 | } |
7526 | else match = (pktrr->InterfaceID == rr->resrec.InterfaceID); | |
7527 | ||
7528 | if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break; | |
7529 | } | |
7530 | return(rr); | |
7531 | } | |
51601d48 A |
7532 | mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr) |
7533 | { | |
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); | |
7538 | } | |
7539 | ||
7540 | mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID) | |
7541 | { | |
7542 | if (m->CurrentRecord) | |
9f221bca | 7543 | LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); |
51601d48 A |
7544 | m->CurrentRecord = thelist; |
7545 | ||
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) | |
7549 | { | |
7550 | AuthRecord *const rr = m->CurrentRecord; | |
7551 | if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC)) | |
7552 | { | |
7553 | if (mDNS_KeepaliveRecord(&m->rec.r.resrec)) | |
7554 | { | |
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); | |
7558 | } | |
7559 | } | |
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; | |
7564 | } | |
7565 | } | |
6528fe3e | 7566 | |
263eeeab A |
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) | |
83fb1e36 A |
7570 | { |
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) | |
7575 | { | |
7576 | AuthRecord *const rr = m->CurrentRecord; | |
7577 | if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC)) | |
51601d48 | 7578 | if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec)) |
83fb1e36 A |
7579 | { |
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)); | |
51601d48 | 7582 | DeregisterProxyRecord(m, rr); |
83fb1e36 A |
7583 | } |
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; | |
7588 | } | |
7589 | } | |
263eeeab | 7590 | |
32bb7e43 A |
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) | |
83fb1e36 A |
7593 | { |
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) | |
7598 | { | |
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) | |
7602 | { | |
7603 | if (rr->AddressProxy.type == mDNSAddrType_IPv6) | |
7604 | { | |
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); | |
7612 | #endif | |
7613 | } | |
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); | |
7622 | } | |
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; | |
7627 | } | |
7628 | } | |
32bb7e43 | 7629 | |
6528fe3e A |
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, | |
83fb1e36 A |
7632 | const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast, |
7633 | mDNSBool QueryWasLocalUnicast, DNSMessage *const response) | |
7634 | { | |
f0cc3e7b | 7635 | const mDNSBool FromLocalSubnet = mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr); |
83fb1e36 A |
7636 | AuthRecord *ResponseRecords = mDNSNULL; |
7637 | AuthRecord **nrp = &ResponseRecords; | |
341ce4f4 A |
7638 | |
7639 | #if POOF_ENABLED | |
2682e09e | 7640 | mDNSBool notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID); // We don't run the POOF algorithm on D2D interfaces. |
83fb1e36 A |
7641 | CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated |
7642 | CacheRecord **eap = &ExpectedAnswers; | |
341ce4f4 A |
7643 | #endif // POOF_ENABLED |
7644 | ||
83fb1e36 A |
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; | |
7649 | const mDNSu8 *ptr; | |
7650 | mDNSu8 *responseptr = mDNSNULL; | |
7651 | AuthRecord *rr; | |
7652 | int i; | |
7653 | ||
7654 | // *** | |
7655 | // *** 1. Look in Additional Section for an OPT record | |
7656 | // *** | |
7657 | ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space); | |
7658 | if (ptr) | |
7659 | { | |
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) | |
7662 | { | |
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]) | |
7669 | { | |
7670 | ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords); | |
7671 | ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords); | |
7672 | } | |
7673 | } | |
7674 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it | |
7675 | } | |
7676 | ||
7677 | // *** | |
7678 | // *** 2. Parse Question Section and mark potential answers | |
7679 | // *** | |
7680 | ptr = query->data; | |
7681 | for (i=0; i<query->h.numQuestions; i++) // For each question... | |
7682 | { | |
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; | |
7689 | ||
7690 | // The only queries that *need* a multicast response are: | |
7691 | // * Queries sent via multicast | |
7692 | // * from port 5353 | |
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); | |
51601d48 A |
7700 | |
7701 | if (pktq.qclass & kDNSQClass_UnicastResponse) | |
7702 | m->mDNSStats.UnicastBitInQueries++; | |
7703 | else | |
7704 | m->mDNSStats.NormalQueries++; | |
7705 | ||
83fb1e36 A |
7706 | // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later |
7707 | pktq.qclass &= ~kDNSQClass_UnicastResponse; | |
7708 | ||
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) | |
7718 | { | |
7719 | rr = m->CurrentRecord; | |
7720 | m->CurrentRecord = rr->next; | |
f0cc3e7b | 7721 | if (AnyTypeRecordAnswersQuestion(rr, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery)) |
83fb1e36 | 7722 | { |
51601d48 | 7723 | m->mDNSStats.MatchingAnswersForQueries++; |
83fb1e36 A |
7724 | if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype)) |
7725 | { | |
7726 | if (rr->resrec.RecordType == kDNSRecordTypeUnique) | |
7727 | ResolveSimultaneousProbe(m, query, end, &pktq, rr); | |
7728 | else if (ResourceRecordIsValidAnswer(rr)) | |
7729 | { | |
7730 | NumAnswersForThisQuestion++; | |
51601d48 | 7731 | |
83fb1e36 A |
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. | |
7734 | ||
7735 | // Notes: | |
7736 | // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast) | |
51601d48 A |
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) | |
83fb1e36 A |
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)) | |
7743 | { | |
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. | |
12c5fa7a | 7747 | if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond || |
83fb1e36 | 7748 | (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID)) |
51601d48 | 7749 | rr->NR_AnswerTo = NR_AnswerMulticast; |
83fb1e36 | 7750 | } |
51601d48 | 7751 | else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast; |
83fb1e36 A |
7752 | } |
7753 | } | |
7754 | else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr)) | |
7755 | { | |
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; | |
7759 | } | |
7760 | } | |
7761 | } | |
7762 | ||
7763 | if (NumAnswersForThisQuestion == 0 && NSECAnswer) | |
7764 | { | |
7765 | NumAnswersForThisQuestion++; | |
7766 | NSECAnswer->SendNSECNow = InterfaceID; | |
7767 | m->NextScheduledResponse = m->timenow; | |
7768 | } | |
7769 | ||
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 | |
7f0064bd | 7773 | |
51601d48 A |
7774 | if (query->h.flags.b[0] & kDNSFlag0_TC) |
7775 | m->mDNSStats.KnownAnswerMultiplePkts++; | |
83fb1e36 A |
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)) | |
83fb1e36 | 7782 | { |
341ce4f4 | 7783 | #if POOF_ENABLED |
2682e09e A |
7784 | if (notD2D) |
7785 | { | |
7786 | CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname); | |
7787 | CacheRecord *cr; | |
7788 | ||
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) | |
f0cc3e7b A |
7792 | { |
7793 | if (SameNameCacheRecordAnswersQuestion(cr, &pktq) && cr->resrec.rdlength <= SmallRecordLimit) | |
7794 | { | |
2682e09e A |
7795 | if (!cr->NextInKAList && eap != &cr->NextInKAList) |
7796 | { | |
7797 | *eap = cr; | |
7798 | eap = &cr->NextInKAList; | |
7799 | } | |
f0cc3e7b A |
7800 | } |
7801 | } | |
2682e09e | 7802 | } |
341ce4f4 | 7803 | #endif // POOF_ENABLED |
83fb1e36 A |
7804 | |
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. | |
f0cc3e7b | 7809 | for (q = m->Questions; q; q=q->next) |
51601d48 | 7810 | { |
f0cc3e7b A |
7811 | if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4) |
7812 | { | |
7813 | if (!q->InterfaceID || q->InterfaceID == InterfaceID) | |
7814 | { | |
7815 | if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList) | |
7816 | { | |
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; } | |
7821 | } | |
7822 | } | |
7823 | } | |
51601d48 A |
7824 | } |
7825 | } | |
83fb1e36 A |
7826 | } |
7827 | ||
7828 | // *** | |
7829 | // *** 3. Now we can safely build the list of marked answers | |
7830 | // *** | |
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 | |
7834 | ||
7835 | // *** | |
7836 | // *** 4. Add additional records | |
7837 | // *** | |
7838 | AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID); | |
7839 | ||
7840 | // *** | |
7841 | // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list | |
7842 | // *** | |
7843 | for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section... | |
7844 | { | |
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) | |
7850 | { | |
7851 | // See if this Known-Answer suppresses any of our currently planned answers | |
7852 | for (rr=ResponseRecords; rr; rr=rr->NextResponse) | |
51601d48 | 7853 | { |
83fb1e36 | 7854 | if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr)) |
51601d48 A |
7855 | { |
7856 | m->mDNSStats.KnownAnswerSuppressions++; | |
7857 | rr->NR_AnswerTo = mDNSNULL; | |
7858 | rr->NR_AdditionalTo = mDNSNULL; | |
7859 | } | |
7860 | } | |
83fb1e36 A |
7861 | |
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) | |
7864 | { | |
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)) | |
7867 | { | |
7868 | if (srcaddr->type == mDNSAddrType_IPv4) | |
7869 | { | |
7870 | if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr; | |
7871 | } | |
7872 | else if (srcaddr->type == mDNSAddrType_IPv6) | |
7873 | { | |
7874 | if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr; | |
7875 | } | |
7876 | if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester)) | |
7877 | { | |
51601d48 | 7878 | m->mDNSStats.KnownAnswerSuppressions++; |
83fb1e36 A |
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)); | |
7883 | #endif | |
7884 | } | |
7885 | } | |
7886 | } | |
7887 | ||
7888 | ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec); | |
7889 | ||
341ce4f4 | 7890 | #if POOF_ENABLED |
2682e09e | 7891 | if (notD2D) |
83fb1e36 | 7892 | { |
2682e09e A |
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; | |
7896 | while (*eap) | |
7897 | { | |
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; | |
7902 | } | |
83fb1e36 | 7903 | } |
341ce4f4 | 7904 | #endif // POOF_ENABLED |
83fb1e36 A |
7905 | |
7906 | // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query. | |
7907 | if (!ourcacherr) | |
7908 | { | |
7909 | dqp = &DupQuestions; | |
7910 | while (*dqp) | |
7911 | { | |
7912 | DNSQuestion *q = *dqp; | |
f0cc3e7b | 7913 | if (CacheRecordAnswersQuestion(&m->rec.r, q)) |
83fb1e36 A |
7914 | { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; } |
7915 | else dqp = &q->NextInDQList; | |
7916 | } | |
7917 | } | |
7918 | } | |
7919 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it | |
7920 | } | |
7921 | ||
7922 | // *** | |
7923 | // *** 6. Cancel any additionals that were added because of now-deleted records | |
7924 | // *** | |
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; } | |
7928 | ||
7929 | // *** | |
7930 | // *** 7. Mark the send flags on the records we plan to send | |
7931 | // *** | |
7932 | for (rr=ResponseRecords; rr; rr=rr->NextResponse) | |
7933 | { | |
7934 | if (rr->NR_AnswerTo) | |
7935 | { | |
7936 | mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response | |
7937 | mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response) | |
7938 | ||
51601d48 A |
7939 | // If it's been one TTL/4 since we multicast this, then send a multicast response |
7940 | // for conflict detection, etc. | |
12c5fa7a | 7941 | if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4) |
83fb1e36 A |
7942 | { |
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. | |
51601d48 A |
7947 | if (rr->NR_AnswerTo == NR_AnswerUnicast) |
7948 | { | |
7949 | m->mDNSStats.UnicastDemotedToMulticast++; | |
7950 | rr->NR_AnswerTo = NR_AnswerMulticast; | |
7951 | } | |
83fb1e36 A |
7952 | } |
7953 | ||
7954 | // If the client insists on a multicast response, then we'd better send one | |
51601d48 A |
7955 | if (rr->NR_AnswerTo == NR_AnswerMulticast) |
7956 | { | |
7957 | m->mDNSStats.MulticastResponses++; | |
7958 | SendMulticastResponse = mDNStrue; | |
7959 | } | |
7960 | else if (rr->NR_AnswerTo == NR_AnswerUnicast) | |
7961 | { | |
7962 | m->mDNSStats.UnicastResponses++; | |
7963 | SendUnicastResponse = mDNStrue; | |
7964 | } | |
7965 | else if (rr->NR_AnswerTo) | |
7966 | { | |
7967 | SendLegacyResponse = mDNStrue; | |
7968 | } | |
83fb1e36 A |
7969 | |
7970 | if (SendMulticastResponse || SendUnicastResponse) | |
7971 | { | |
8e92c31c | 7972 | #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES |
83fb1e36 | 7973 | rr->ImmedAnswerMarkTime = m->timenow; |
8e92c31c | 7974 | #endif |
83fb1e36 A |
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; | |
7979 | else | |
7980 | { | |
7981 | rr->ImmedAnswer = InterfaceID; // Record interface to send it on | |
7982 | if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue; | |
7983 | if (srcaddr->type == mDNSAddrType_IPv4) | |
7984 | { | |
7985 | if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4; | |
7986 | else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr; | |
7987 | } | |
7988 | else if (srcaddr->type == mDNSAddrType_IPv6) | |
7989 | { | |
7990 | if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6; | |
7991 | else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr; | |
7992 | } | |
7993 | } | |
7994 | } | |
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 | |
8001 | } | |
51601d48 | 8002 | else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast) |
83fb1e36 A |
8003 | { |
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 | |
8010 | } | |
8011 | } | |
8012 | ||
8013 | // *** | |
8014 | // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer | |
8015 | // *** | |
8016 | if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50)) | |
8017 | { | |
8e92c31c | 8018 | #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES |
83fb1e36 A |
8019 | mDNSs32 oldss = m->SuppressSending; |
8020 | if (oldss && delayresponse) | |
8021 | LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50); | |
8e92c31c | 8022 | #endif |
83fb1e36 A |
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; | |
8e92c31c | 8038 | #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES |
83fb1e36 A |
8039 | if (oldss && delayresponse) |
8040 | LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow); | |
8e92c31c | 8041 | #endif |
83fb1e36 | 8042 | } |
6528fe3e | 8043 | |
83fb1e36 A |
8044 | // *** |
8045 | // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too | |
8046 | // *** | |
8047 | if (SendLegacyResponse) | |
8048 | responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords); | |
6528fe3e A |
8049 | |
8050 | exit: | |
83fb1e36 A |
8051 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it |
8052 | ||
8053 | // *** | |
8054 | // *** 10. Finally, clear our link chains ready for use next time | |
8055 | // *** | |
8056 | while (ResponseRecords) | |
8057 | { | |
8058 | rr = ResponseRecords; | |
8059 | ResponseRecords = rr->NextResponse; | |
8060 | rr->NextResponse = mDNSNULL; | |
8061 | rr->NR_AnswerTo = mDNSNULL; | |
8062 | rr->NR_AdditionalTo = mDNSNULL; | |
8063 | } | |
8064 | ||
341ce4f4 | 8065 | #if POOF_ENABLED |
2682e09e | 8066 | while (ExpectedAnswers && notD2D) |
83fb1e36 A |
8067 | { |
8068 | CacheRecord *cr = ExpectedAnswers; | |
8069 | ExpectedAnswers = cr->NextInKAList; | |
8070 | cr->NextInKAList = mDNSNULL; | |
8071 | ||
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)) | |
9f221bca | 8075 | if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4) |
83fb1e36 A |
8076 | { |
8077 | cr->UnansweredQueries++; | |
8078 | cr->LastUnansweredTime = m->timenow; | |
83fb1e36 | 8079 | if (cr->UnansweredQueries > 1) |
9f221bca | 8080 | debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr)); |
83fb1e36 A |
8081 | SetNextCacheCheckTimeForRecord(m, cr); |
8082 | } | |
c9b9ae52 | 8083 | |
83fb1e36 A |
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) | |
8087 | { | |
83fb1e36 | 8088 | // Only show debugging message if this record was not about to expire anyway |
9f221bca | 8089 | if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond) |
12c5fa7a A |
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)); | |
9f221bca | 8092 | |
51601d48 | 8093 | m->mDNSStats.PoofCacheDeletions++; |
83fb1e36 A |
8094 | mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); |
8095 | } | |
83fb1e36 | 8096 | } |
341ce4f4 | 8097 | #endif // POOF_ENABLED |
83fb1e36 A |
8098 | |
8099 | while (DupQuestions) | |
8100 | { | |
8101 | DNSQuestion *q = DupQuestions; | |
8102 | DupQuestions = q->NextInDQList; | |
8103 | q->NextInDQList = mDNSNULL; | |
9f221bca A |
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"); | |
83fb1e36 | 8107 | } |
83fb1e36 A |
8108 | return(responseptr); |
8109 | } | |
6528fe3e A |
8110 | |
8111 | mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, | |
83fb1e36 A |
8112 | const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport, |
8113 | const mDNSInterfaceID InterfaceID) | |
8114 | { | |
8115 | mDNSu8 *responseend = mDNSNULL; | |
8116 | mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr && | |
9f221bca | 8117 | !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr); |
83fb1e36 | 8118 | |
9f221bca | 8119 | if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr))) |
83fb1e36 | 8120 | { |
9f221bca | 8121 | const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID"; |
83fb1e36 | 8122 | LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with " |
9f221bca | 8123 | "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)", |
83fb1e36 A |
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,", | |
9f221bca | 8128 | msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data, reason); |
83fb1e36 A |
8129 | return; |
8130 | } | |
8131 | ||
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); | |
8139 | ||
8140 | responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID, | |
8141 | !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg); | |
8142 | ||
8143 | if (responseend) // If responseend is non-null, that means we built a unicast response packet | |
8144 | { | |
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); | |
f0cc3e7b | 8150 | mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSfalse); |
83fb1e36 A |
8151 | } |
8152 | } | |
67c8f8a1 | 8153 | |
9f29194f | 8154 | #if 0 |
67c8f8a1 | 8155 | mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr) |
83fb1e36 A |
8156 | { |
8157 | DNSServer *s; | |
8158 | (void)m; // Unused | |
8159 | (void)srcaddr; // Unused | |
8160 | for (s = m->DNSServers; s; s = s->next) | |
8161 | if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue); | |
8162 | return(mDNSfalse); | |
8163 | } | |
9f29194f A |
8164 | #endif |
8165 | ||
8166 | struct UDPSocket_struct | |
83fb1e36 A |
8167 | { |
8168 | mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port | |
8169 | }; | |
67c8f8a1 | 8170 | |
19fa75a9 A |
8171 | mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, |
8172 | const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp) | |
83fb1e36 A |
8173 | { |
8174 | DNSQuestion *q; | |
8175 | for (q = m->Questions; q; q=q->next) | |
8176 | { | |
8177 | if (!tcp && !q->LocalSocket) continue; | |
fc8aa221 | 8178 | if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) && |
83fb1e36 A |
8179 | q->qtype == question->qtype && |
8180 | q->qclass == question->qclass && | |
8181 | q->qnamehash == question->qnamehash && | |
8182 | SameDomainName(&q->qname, &question->qname)) | |
fc8aa221 A |
8183 | { |
8184 | if (mDNSSameOpaque16(q->TargetQID, id)) return(q); | |
8185 | else | |
8186 | { | |
fc8aa221 A |
8187 | return(mDNSNULL); |
8188 | } | |
8189 | } | |
83fb1e36 A |
8190 | } |
8191 | return(mDNSNULL); | |
8192 | } | |
67c8f8a1 | 8193 | |
3c3ba2cc A |
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) | |
263eeeab | 8196 | mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m, |
83fb1e36 A |
8197 | const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp) |
8198 | { | |
8199 | DNSQuestion *q; | |
8200 | (void)id; | |
83fb1e36 A |
8201 | |
8202 | for (q = m->Questions; q; q=q->next) | |
8203 | { | |
8204 | if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q)) | |
8205 | { | |
8206 | if (!mDNSOpaque16IsZero(q->TargetQID)) | |
8207 | { | |
8208 | debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr)); | |
8209 | ||
8210 | if (mDNSSameOpaque16(q->TargetQID, id)) | |
8211 | { | |
8212 | mDNSIPPort srcp; | |
8213 | if (!tcp) | |
8214 | { | |
8215 | srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort; | |
8216 | } | |
8217 | else | |
8218 | { | |
8219 | srcp = q->tcpSrcPort; | |
8220 | } | |
8221 | if (mDNSSameIPPort(srcp, port)) return(q); | |
8222 | ||
9f221bca A |
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); | |
f0cc3e7b A |
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)); | |
83fb1e36 A |
8228 | return(mDNSNULL); |
8229 | } | |
8230 | } | |
8231 | else | |
8232 | { | |
8233 | if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2)) | |
8234 | return(q); | |
8235 | } | |
8236 | } | |
8237 | } | |
8238 | return(mDNSNULL); | |
8239 | } | |
67c8f8a1 | 8240 | |
32bb7e43 A |
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. | |
32bb7e43 | 8244 | mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr) |
83fb1e36 A |
8245 | { |
8246 | switch (rr->rrtype) | |
8247 | { | |
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; | |
8252 | } | |
8253 | } | |
8254 | ||
8255 | mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress) | |
8256 | { | |
8257 | CacheRecord *rr = mDNSNULL; | |
8258 | mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec); | |
8259 | ||
8260 | if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r)); | |
8261 | ||
8262 | //if (RDLength > InlineCacheRDSize) | |
9f221bca | 8263 | // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r)); |
83fb1e36 A |
8264 | |
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); | |
8268 | else | |
8269 | { | |
19fa75a9 A |
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); | |
8274 | #endif | |
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. | |
8280 | #endif | |
51601d48 | 8281 | |
83fb1e36 A |
8282 | rr->DelayDelivery = delay; |
8283 | ||
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); | |
8291 | ||
8292 | rr->next = mDNSNULL; // Clear 'next' pointer | |
51601d48 | 8293 | rr->soa = mDNSNULL; |
83fb1e36 A |
8294 | |
8295 | if (sourceAddress) | |
8296 | rr->sourceAddress = *sourceAddress; | |
8297 | ||
51601d48 A |
8298 | if (!rr->resrec.InterfaceID) |
8299 | { | |
8300 | m->rrcache_totalused_unicast += rr->resrec.rdlength; | |
51601d48 A |
8301 | } |
8302 | ||
19fa75a9 A |
8303 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) |
8304 | if (rr != mDNSNULL) | |
8305 | { | |
8306 | rr->denial_of_existence_records = mDNSNULL; | |
8307 | } | |
8308 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
8309 | ||
83fb1e36 A |
8310 | if (Add) |
8311 | { | |
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 | |
8315 | } | |
8316 | else | |
8317 | { | |
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 | |
f0cc3e7b | 8320 | domainname *name = (domainname *) mDNSPlatformMemAllocate(DomainNameLength(cg->name)); |
83fb1e36 A |
8321 | if (name) |
8322 | { | |
8323 | AssignDomainName(name, cg->name); | |
8324 | rr->resrec.name = name; | |
8325 | } | |
8326 | else | |
8327 | { | |
8328 | ReleaseCacheRecord(m, rr); | |
8329 | NoCacheAnswer(m, &m->rec.r); | |
8330 | rr = mDNSNULL; | |
8331 | } | |
8332 | } | |
8333 | } | |
8334 | return(rr); | |
8335 | } | |
67c8f8a1 | 8336 | |
e9410223 A |
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 | |
8340 | { | |
8341 | CacheRecord **rp; | |
8342 | for (rp = &cg->members; *rp; rp = &(*rp)->next) | |
8343 | { | |
8344 | if (*rp == cr) // This item points to this record | |
8345 | { | |
8346 | *rp = cr->next; // Remove this record | |
8347 | break; | |
8348 | } | |
8349 | } | |
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 | |
8353 | } | |
8354 | } | |
8355 | ||
67c8f8a1 | 8356 | mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl) |
83fb1e36 A |
8357 | { |
8358 | rr->TimeRcvd = m->timenow; | |
8359 | rr->resrec.rroriginalttl = ttl; | |
8360 | rr->UnansweredQueries = 0; | |
2682e09e | 8361 | if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal; |
83fb1e36 A |
8362 | SetNextCacheCheckTimeForRecord(m, rr); |
8363 | } | |
67c8f8a1 A |
8364 | |
8365 | mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease) | |
83fb1e36 A |
8366 | { |
8367 | CacheRecord *rr; | |
12c5fa7a | 8368 | CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname); |
83fb1e36 A |
8369 | for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) |
8370 | if (rr->CRActiveQuestion == q) | |
8371 | { | |
8372 | //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr)); | |
8373 | RefreshCacheRecord(m, rr, lease); | |
8374 | } | |
8375 | } | |
8376 | ||
8377 | mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds | |
8378 | { | |
8379 | if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease; | |
8380 | else if (LLQType == uDNS_LLQ_Events) | |
8381 | { | |
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; | |
8385 | } | |
8386 | else // else not LLQ (standard uDNS response) | |
8387 | { | |
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; | |
8391 | ||
51601d48 | 8392 | ttl = RRAdjustTTL(ttl); |
83fb1e36 A |
8393 | |
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; | |
8407 | } | |
8408 | ||
8409 | return ttl; | |
8410 | } | |
8411 | ||
8412 | // When the response does not match the question directly, we still want to cache them sometimes. The current response is | |
8413 | // in m->rec. | |
19fa75a9 | 8414 | mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist) |
83fb1e36 A |
8415 | { |
8416 | CacheRecord *const newcr = &m->rec.r; | |
8417 | ResourceRecord *rr = &newcr->resrec; | |
8418 | const CacheRecord *cr; | |
8419 | ||
83fb1e36 A |
8420 | for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList) |
8421 | { | |
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. | |
8428 | ||
8429 | if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name)) | |
8430 | { | |
2682e09e | 8431 | LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr)); |
83fb1e36 A |
8432 | return (mDNStrue); |
8433 | } | |
8434 | } | |
83fb1e36 A |
8435 | return mDNSfalse; |
8436 | } | |
8437 | ||
19fa75a9 A |
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, | |
8442 | #endif | |
8443 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
8444 | denial_of_existence_records_t **denial_of_existence_records_ptr, | |
8445 | #endif | |
8446 | const uDNS_LLQType LLQType) | |
83fb1e36 A |
8447 | { |
8448 | int i; | |
8449 | const mDNSu8 *ptr = response->data; | |
51601d48 A |
8450 | CacheRecord *SOARecord = mDNSNULL; |
8451 | ||
83fb1e36 A |
8452 | for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++) |
8453 | { | |
8454 | DNSQuestion q; | |
83fb1e36 | 8455 | ptr = getQuestion(response, ptr, end, InterfaceID, &q); |
19fa75a9 | 8456 | if (ptr) |
83fb1e36 | 8457 | { |
19fa75a9 | 8458 | DNSQuestion *qptr; |
f0cc3e7b | 8459 | CacheRecord *cr, *neg = mDNSNULL; |
19fa75a9 A |
8460 | CacheGroup *cg; |
8461 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
8462 | if (querier) | |
8463 | { | |
8464 | qptr = Querier_GetDNSQuestion(querier); | |
8465 | } | |
8466 | else | |
8467 | #endif | |
8468 | { | |
8469 | qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr); | |
8470 | if (!qptr) | |
8471 | { | |
8472 | continue; | |
8473 | } | |
8474 | } | |
8475 | cg = CacheGroupForName(m, q.qnamehash, &q.qname); | |
f0cc3e7b A |
8476 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) |
8477 | { | |
19fa75a9 A |
8478 | mDNSBool isAnswer; |
8479 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
8480 | if (querier) | |
8481 | { | |
8482 | isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier); | |
8483 | } | |
8484 | else | |
8485 | #endif | |
8486 | { | |
8487 | isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr); | |
8488 | } | |
8489 | if (isAnswer) | |
83fb1e36 A |
8490 | { |
8491 | // 1. If we got a fresh answer to this query, then don't need to generate a negative entry | |
f0cc3e7b | 8492 | if (RRExpireTime(cr) - m->timenow > 0) break; |
83fb1e36 | 8493 | // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one |
f0cc3e7b | 8494 | if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = cr; |
19fa75a9 A |
8495 | else if (cr->resrec.mortality == Mortality_Ghost) |
8496 | { | |
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); | |
8502 | } | |
83fb1e36 | 8503 | } |
f0cc3e7b | 8504 | } |
83fb1e36 A |
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 :-) | |
8515 | // | |
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)) | |
8522 | { | |
f0cc3e7b | 8523 | if (!cr) |
83fb1e36 | 8524 | { |
19fa75a9 A |
8525 | if (qptr) |
8526 | { | |
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 | |
8534 | // the application | |
8535 | if (qptr->ProxyQuestion) | |
8536 | qptr->responseFlags = response->h.flags; | |
8537 | GenerateNegativeResponseEx(m, mDNSInterface_Any, QC_forceresponse, noData); | |
8538 | m->CurrentQuestion = mDNSNULL; | |
8539 | } | |
83fb1e36 | 8540 | } |
51601d48 A |
8541 | else |
8542 | { | |
f0cc3e7b | 8543 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, |
19fa75a9 A |
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)); | |
51601d48 | 8546 | } |
83fb1e36 A |
8547 | } |
8548 | else | |
8549 | { | |
f0cc3e7b | 8550 | if (!cr) |
83fb1e36 A |
8551 | { |
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; | |
8555 | int repeat = 0; | |
8556 | const domainname *name = &q.qname; | |
8557 | mDNSu32 hash = q.qnamehash; | |
8558 | ||
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; | |
8566 | ||
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) | |
8569 | { | |
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) | |
8572 | { | |
12c5fa7a | 8573 | CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec); |
83fb1e36 A |
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; | |
8582 | ||
51601d48 A |
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. | |
12c5fa7a | 8585 | SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL); |
51601d48 | 8586 | |
83fb1e36 A |
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 | |
51601d48 A |
8591 | // |
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. | |
19fa75a9 | 8594 | if ((!qptr || !qptr->ProxyQuestion) && (q.qtype == kDNSType_SOA)) |
83fb1e36 A |
8595 | { |
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; | |
8601 | } | |
8602 | } | |
8603 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it | |
8604 | } | |
8605 | ||
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. | |
8612 | if (neg) | |
8613 | { | |
8614 | if (negttl < neg->resrec.rroriginalttl * 2) | |
8615 | negttl = neg->resrec.rroriginalttl * 2; | |
8616 | if (negttl > 3600) | |
8617 | negttl = 3600; | |
8618 | } | |
8619 | ||
8620 | negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary | |
8621 | ||
8622 | // If we already had a negative cache entry just update it, else make one or more new negative cache entries. | |
8623 | if (neg) | |
8624 | { | |
f0cc3e7b | 8625 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, |
19fa75a9 A |
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)); | |
83fb1e36 | 8628 | RefreshCacheRecord(m, neg, negttl); |
19fa75a9 A |
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 | |
8632 | // for DNSSEC. | |
8633 | if ((qptr != mDNSNULL) && qptr->DNSSECStatus.enable_dnssec) | |
8634 | { | |
8635 | update_denial_records_in_cache_record(neg, denial_of_existence_records_ptr); | |
8636 | } | |
8637 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
83fb1e36 A |
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. | |
19fa75a9 | 8643 | if (qptr) |
83fb1e36 | 8644 | { |
19fa75a9 | 8645 | ResetQuestionState(m, qptr); |
83fb1e36 | 8646 | } |
51601d48 A |
8647 | if (SOARecord) |
8648 | { | |
8649 | if (neg->soa) | |
8650 | ReleaseCacheRecord(m, neg->soa); | |
8651 | neg->soa = SOARecord; | |
8652 | SOARecord = mDNSNULL; | |
8653 | } | |
83fb1e36 A |
8654 | } |
8655 | else while (1) | |
8656 | { | |
51601d48 | 8657 | CacheRecord *negcr; |
83fb1e36 | 8658 | debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype)); |
19fa75a9 A |
8659 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
8660 | MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, uDNSService); | |
8661 | #else | |
83fb1e36 | 8662 | MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer); |
19fa75a9 | 8663 | #endif |
51601d48 A |
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. | |
12c5fa7a | 8670 | cg = CacheGroupForName(m, hash, name); |
19fa75a9 A |
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); | |
8673 | ||
8674 | if (negcr) | |
83fb1e36 | 8675 | { |
19fa75a9 A |
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) | |
83fb1e36 | 8680 | { |
19fa75a9 | 8681 | update_denial_records_in_cache_record(negcr, denial_of_existence_records_ptr); |
83fb1e36 | 8682 | } |
19fa75a9 A |
8683 | #endif |
8684 | negcr->DelayDelivery = 0; | |
51601d48 | 8685 | |
19fa75a9 A |
8686 | if (SOARecord) |
8687 | { | |
8688 | if (negcr->soa) | |
8689 | ReleaseCacheRecord(m, negcr->soa); | |
8690 | negcr->soa = SOARecord; | |
8691 | SOARecord = mDNSNULL; | |
51601d48 | 8692 | } |
19fa75a9 | 8693 | CacheRecordDeferredAdd(m, negcr); |
83fb1e36 | 8694 | } |
51601d48 | 8695 | m->rec.r.responseFlags = zeroID; |
83fb1e36 A |
8696 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it |
8697 | if (!repeat) break; | |
8698 | repeat--; | |
8699 | name = (const domainname *)(name->c + 1 + name->c[0]); | |
8700 | hash = DomainNameHashValue(name); | |
83fb1e36 A |
8701 | } |
8702 | } | |
8703 | } | |
8704 | } | |
8705 | } | |
f0cc3e7b A |
8706 | if (SOARecord) |
8707 | { | |
8708 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); | |
8709 | ReleaseCacheRecord(m, SOARecord); | |
8710 | } | |
83fb1e36 A |
8711 | } |
8712 | ||
341ce4f4 A |
8713 | mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m) |
8714 | { | |
8715 | AuthRecord *rrPtr = mDNSNULL; | |
f0cc3e7b | 8716 | if (!m->SPSRRSet) return; |
341ce4f4 A |
8717 | LogSPS("Stored Proxy records :"); |
8718 | for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next) | |
8719 | { | |
8720 | LogSPS("%s", ARDisplayString(m, rrPtr)); | |
8721 | } | |
8722 | } | |
8723 | ||
83fb1e36 A |
8724 | mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr) |
8725 | { | |
341ce4f4 | 8726 | AuthRecord *rrPtr = mDNSNULL; |
83fb1e36 | 8727 | |
341ce4f4 | 8728 | for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next) |
83fb1e36 | 8729 | { |
341ce4f4 | 8730 | if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec)) |
83fb1e36 | 8731 | { |
341ce4f4 A |
8732 | LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr)); |
8733 | return mDNStrue; | |
83fb1e36 | 8734 | } |
83fb1e36 | 8735 | } |
341ce4f4 | 8736 | mDNSCorePrintStoredProxyRecords(m); |
83fb1e36 A |
8737 | return mDNSfalse; |
8738 | } | |
6528fe3e | 8739 | |
f0cc3e7b | 8740 | mDNSexport CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType, |
19fa75a9 | 8741 | const mDNSu32 slot, CacheGroup *cg, CacheRecord ***cfp, mDNSInterfaceID InterfaceID) |
83fb1e36 | 8742 | { |
f0cc3e7b | 8743 | CacheRecord *cr; |
51601d48 A |
8744 | CacheRecord **cflocal = *cfp; |
8745 | ||
f0cc3e7b | 8746 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) |
51601d48 A |
8747 | { |
8748 | mDNSBool match; | |
8749 | // Resource record received via unicast, the resGroupID should match ? | |
8750 | if (!InterfaceID) | |
8751 | { | |
19fa75a9 A |
8752 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
8753 | match = (cr->resrec.dnsservice == m->rec.r.resrec.dnsservice) ? mDNStrue : mDNSfalse; | |
8754 | #else | |
f0cc3e7b | 8755 | const mDNSu32 id1 = (cr->resrec.rDNSServer ? cr->resrec.rDNSServer->resGroupID : 0); |
672757b6 | 8756 | const mDNSu32 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0); |
51601d48 | 8757 | match = (id1 == id2); |
19fa75a9 | 8758 | #endif |
51601d48 A |
8759 | } |
8760 | else | |
f0cc3e7b | 8761 | match = (cr->resrec.InterfaceID == InterfaceID); |
51601d48 | 8762 | // If we found this exact resource record, refresh its TTL |
19fa75a9 | 8763 | if (match) |
51601d48 | 8764 | { |
19fa75a9 | 8765 | if (IdenticalSameNameRecord(&m->rec.r.resrec, &cr->resrec)) |
51601d48 | 8766 | { |
19fa75a9 A |
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)); | |
8770 | ||
8771 | if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) | |
51601d48 | 8772 | { |
19fa75a9 A |
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) | |
8775 | { | |
8776 | *cflocal = cr; | |
8777 | cflocal = &cr->NextInCFList; | |
8778 | *cflocal = (CacheRecord*)1; | |
8779 | *cfp = &cr->NextInCFList; | |
8780 | } | |
8781 | ||
8782 | // If this packet record is marked unique, and our previous cached copy was not, then fix it | |
8783 | if (!(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) | |
8784 | { | |
8785 | DNSQuestion *q; | |
8786 | for (q = m->Questions; q; q=q->next) | |
8787 | { | |
8788 | if (CacheRecordAnswersQuestion(cr, q)) | |
8789 | q->UniqueAnswers++; | |
8790 | } | |
8791 | cr->resrec.RecordType = m->rec.r.resrec.RecordType; | |
8792 | } | |
51601d48 A |
8793 | } |
8794 | ||
19fa75a9 A |
8795 | if (!SameRDataBody(&m->rec.r.resrec, &cr->resrec.rdata->u, SameDomainNameCS)) |
8796 | { | |
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 | |
8810 | } | |
8811 | else if (m->rec.r.resrec.rroriginalttl > 0) | |
51601d48 A |
8812 | { |
8813 | DNSQuestion *q; | |
19fa75a9 A |
8814 | |
8815 | m->mDNSStats.CacheRefreshed++; | |
8816 | ||
8817 | if ((cr->resrec.mortality == Mortality_Ghost) && !cr->DelayDelivery) | |
51601d48 | 8818 | { |
19fa75a9 A |
8819 | cr->DelayDelivery = NonZeroTime(m->timenow); |
8820 | debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(cr), CRDisplayString(m, cr)); | |
51601d48 | 8821 | } |
51601d48 | 8822 | |
19fa75a9 A |
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; | |
8829 | ||
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. | |
8837 | if (!InterfaceID) | |
8838 | { | |
8839 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S, CRDisplayString(m, cr)); | |
8840 | } | |
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) | |
51601d48 | 8850 | { |
19fa75a9 | 8851 | for (q = m->Questions; q; q=q->next) |
51601d48 | 8852 | { |
19fa75a9 A |
8853 | if (!q->DuplicateOf && !q->LongLived && |
8854 | ActiveQuestion(q) && CacheRecordAnswersQuestion(cr, q)) | |
8855 | { | |
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 | |
8859 | } | |
51601d48 A |
8860 | } |
8861 | } | |
19fa75a9 A |
8862 | break; // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above) |
8863 | } | |
8864 | else | |
8865 | { | |
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) | |
8876 | { | |
8877 | cr->resrec.rroriginalttl = 1; | |
8878 | cr->TimeRcvd = m->timenow; | |
8879 | cr->UnansweredQueries = MaxUnansweredQueries; | |
8880 | SetNextCacheCheckTimeForRecord(m, cr); | |
8881 | } | |
8882 | break; | |
51601d48 | 8883 | } |
51601d48 | 8884 | } |
19fa75a9 A |
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))) | |
51601d48 | 8889 | { |
19fa75a9 A |
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 | |
51601d48 A |
8895 | } |
8896 | } | |
8897 | } | |
f0cc3e7b | 8898 | return cr; |
51601d48 A |
8899 | } |
8900 | ||
19fa75a9 | 8901 | mDNSlocal void mDNSCoreResetRecord(mDNS *const m) |
51601d48 | 8902 | { |
19fa75a9 A |
8903 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it |
8904 | } | |
51601d48 | 8905 | |
51601d48 A |
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 | |
19fa75a9 A |
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, | |
8916 | #endif | |
8917 | const mDNSInterfaceID InterfaceID) | |
51601d48 A |
8918 | { |
8919 | int i; | |
19fa75a9 A |
8920 | const mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr); |
8921 | const mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr); | |
83fb1e36 | 8922 | DNSQuestion *llqMatch = mDNSNULL; |
83fb1e36 A |
8923 | uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch); |
8924 | ||
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; | |
51601d48 | 8930 | NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID); |
9f221bca | 8931 | mDNSBool recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question. |
83fb1e36 A |
8932 | |
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 | |
9f221bca | 8935 | // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record. |
83fb1e36 A |
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; | |
19fa75a9 | 8940 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 | 8941 | DNSServer *uDNSServer = mDNSNULL; |
19fa75a9 A |
8942 | #endif |
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; | |
8946 | #endif | |
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; | |
8954 | #else | |
8955 | const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id); | |
8956 | #endif | |
83fb1e36 A |
8957 | |
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); | |
8965 | ||
19fa75a9 | 8966 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
4f6e7a0c A |
8967 | if (mDNSSameIPPort(srcport, UnicastDNSPort)) |
8968 | { | |
8969 | MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response)); | |
8970 | } | |
8971 | #endif | |
8972 | ||
83fb1e36 A |
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. | |
564f2ae2 A |
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. | |
8989 | // | |
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. | |
19fa75a9 A |
8995 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
8996 | if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && !querier && | |
8997 | #else | |
564f2ae2 | 8998 | if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && |
19fa75a9 | 8999 | #endif |
564f2ae2 | 9000 | ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return; |
83fb1e36 A |
9001 | |
9002 | if (LLQType == uDNS_LLQ_Ignore) return; | |
9003 | ||
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 | |
83fb1e36 | 9006 | // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged |
564f2ae2 | 9007 | if (ResponseMCast || LLQType == uDNS_LLQ_Events) |
83fb1e36 A |
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. | |
9011 | else | |
9012 | { | |
9013 | mDNSBool failure, returnEarly; | |
19fa75a9 | 9014 | const int rcode = response->h.flags.b[1] & kDNSFlag1_RC_Mask; |
83fb1e36 A |
9015 | failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth); |
9016 | returnEarly = mDNSfalse; | |
19fa75a9 A |
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) | |
9026 | { | |
9027 | totalrecords = 0; | |
9028 | failure = mDNSfalse; | |
9029 | } | |
9030 | #endif | |
83fb1e36 A |
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++) | |
9038 | { | |
19fa75a9 A |
9039 | DNSQuestion q; |
9040 | DNSQuestion *qptr; | |
9041 | mDNSBool expectingResponse; | |
83fb1e36 | 9042 | ptr = getQuestion(response, ptr, end, InterfaceID, &q); |
19fa75a9 A |
9043 | if (!ptr) |
9044 | { | |
9045 | continue; | |
9046 | } | |
9047 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
9048 | if (querier) | |
9049 | { | |
9050 | expectingResponse = mDNStrue; | |
9051 | qptr = mDNSNULL; | |
9052 | } | |
9053 | else | |
9054 | #endif | |
9055 | { | |
9056 | qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr); | |
9057 | expectingResponse = qptr ? mDNStrue : mDNSfalse; | |
9058 | } | |
9059 | if (!expectingResponse) | |
83fb1e36 | 9060 | { |
19fa75a9 A |
9061 | continue; |
9062 | } | |
9063 | if (!failure) | |
9064 | { | |
9065 | CacheRecord *cr; | |
9066 | CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname); | |
9067 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) | |
83fb1e36 | 9068 | { |
19fa75a9 A |
9069 | mDNSBool isAnswer; |
9070 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
9071 | if (querier) | |
51601d48 | 9072 | { |
19fa75a9 | 9073 | isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier); |
51601d48 | 9074 | } |
19fa75a9 A |
9075 | else |
9076 | #endif | |
f0cc3e7b | 9077 | { |
19fa75a9 | 9078 | isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr); |
f0cc3e7b | 9079 | } |
19fa75a9 | 9080 | if (isAnswer) |
83fb1e36 | 9081 | { |
19fa75a9 A |
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; | |
83fb1e36 | 9087 | } |
83fb1e36 | 9088 | } |
fc8aa221 | 9089 | } |
19fa75a9 | 9090 | else |
fc8aa221 | 9091 | { |
19fa75a9 A |
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); | |
f0cc3e7b | 9098 | #endif |
19fa75a9 | 9099 | returnEarly = mDNStrue; |
83fb1e36 A |
9100 | } |
9101 | } | |
9102 | if (returnEarly) | |
9103 | { | |
f0cc3e7b A |
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"); | |
83fb1e36 A |
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) | |
9112 | return; | |
9113 | } | |
9114 | } | |
9115 | ||
9116 | for (i = 0; i < totalrecords && ptr && ptr < end; i++) | |
9117 | { | |
9118 | // All responses sent via LL multicast are acceptable for caching | |
9119 | // All responses received over our outbound TCP connections are acceptable for caching | |
9f221bca A |
9120 | // We accept all records in a unicast response to a multicast query once we find one that |
9121 | // answers an active question. | |
19fa75a9 A |
9122 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9123 | mDNSBool AcceptableResponse = ResponseMCast || (!querier && !dstaddr) || LLQType || recordAcceptedInResponse; | |
9124 | #else | |
9f221bca | 9125 | mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse; |
19fa75a9 | 9126 | #endif |
83fb1e36 A |
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.) | |
9129 | ||
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 | |
83fb1e36 | 9135 | |
51601d48 A |
9136 | if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) |
9137 | { | |
9138 | mDNSCoreResetRecord(m); | |
9139 | continue; | |
9140 | } | |
9141 | ||
83fb1e36 | 9142 | // Don't want to cache OPT or TSIG pseudo-RRs |
51601d48 A |
9143 | if (m->rec.r.resrec.rrtype == kDNSType_TSIG) |
9144 | { | |
9145 | mDNSCoreResetRecord(m); | |
9146 | continue; | |
9147 | } | |
83fb1e36 A |
9148 | if (m->rec.r.resrec.rrtype == kDNSType_OPT) |
9149 | { | |
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]) | |
9156 | { | |
9157 | ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords); | |
9158 | ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords); | |
9159 | } | |
51601d48 | 9160 | mDNSCoreResetRecord(m); |
83fb1e36 A |
9161 | continue; |
9162 | } | |
83fb1e36 A |
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)) | |
9165 | { | |
9166 | LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c); | |
51601d48 | 9167 | mDNSCoreResetRecord(m); |
83fb1e36 A |
9168 | continue; |
9169 | } | |
9170 | ||
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 | |
19fa75a9 A |
9174 | if (!ResponseIsMDNS) |
9175 | { | |
83fb1e36 | 9176 | m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl); |
19fa75a9 | 9177 | } |
83fb1e36 A |
9178 | |
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. | |
9181 | if (!ResponseMCast) | |
9182 | { | |
9183 | if (LLQType) | |
9184 | { | |
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. | |
9190 | ||
19fa75a9 A |
9191 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9192 | if (querier) | |
9193 | { | |
9194 | mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService); | |
9195 | } | |
9196 | #else | |
83fb1e36 | 9197 | if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer; |
19fa75a9 | 9198 | #endif |
83fb1e36 A |
9199 | } |
9200 | else if (!AcceptableResponse || !dstaddr) | |
9201 | { | |
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 | |
9205 | // we create. | |
19fa75a9 A |
9206 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9207 | if (querier) | |
9f221bca | 9208 | { |
19fa75a9 A |
9209 | ResourceRecord *const rr = &m->rec.r.resrec; |
9210 | if (Querier_ResourceRecordIsAnswer(rr, querier)) | |
83fb1e36 | 9211 | { |
19fa75a9 A |
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)) | |
9215 | { | |
9216 | rr->protocol = mdns_resolver_type_tcp; | |
9217 | } | |
9218 | else | |
9219 | { | |
9220 | rr->protocol = resolver_type; | |
9221 | } | |
9222 | mdns_replace(&rr->dnsservice, uDNSService); | |
9223 | AcceptableResponse = mDNStrue; | |
83fb1e36 A |
9224 | } |
9225 | } | |
9f221bca | 9226 | else |
19fa75a9 | 9227 | #endif |
51601d48 | 9228 | { |
19fa75a9 A |
9229 | const DNSQuestion *q; |
9230 | // Initialize the DNS server on the resource record which will now filter what questions we answer with | |
9231 | // this record. | |
9232 | // | |
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); | |
9239 | if (q != mDNSNULL) | |
9240 | { | |
9241 | AcceptableResponse = mDNStrue; | |
9242 | if (!InterfaceID) | |
9243 | { | |
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; | |
9247 | #endif | |
9248 | } | |
9249 | else | |
9250 | { | |
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)); | |
9256 | } | |
9257 | } | |
9258 | else | |
9f221bca | 9259 | { |
19fa75a9 A |
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 | |
9262 | if (!InterfaceID) | |
9263 | { | |
9264 | debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c); | |
9265 | AcceptableResponse = mDNSfalse; | |
9266 | } | |
9f221bca | 9267 | } |
51601d48 A |
9268 | } |
9269 | } | |
9270 | } | |
9271 | else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A) | |
9272 | { | |
9f221bca 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> | |
9279 | ||
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. | |
9286 | ||
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. | |
9292 | ||
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 | |
9297 | ||
9298 | const CacheRecord *const rr = &m->rec.r; | |
9299 | const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data; | |
51601d48 A |
9300 | if (mDNSv4AddressIsLinkLocal(&rdb->ipv4)) |
9301 | { | |
9302 | LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r)); | |
9303 | mDNSCoreResetRecord(m); | |
9304 | continue; | |
83fb1e36 A |
9305 | } |
9306 | } | |
9307 | ||
9308 | // 1. Check that this packet resource record does not conflict with any of ours | |
19fa75a9 | 9309 | if (ResponseIsMDNS && m->rec.r.resrec.rrtype != kDNSType_NSEC) |
83fb1e36 A |
9310 | { |
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) | |
9315 | { | |
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; | |
9322 | ||
9323 | if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match... | |
9324 | { | |
9325 | // ... check to see if type and rdata are identical | |
9326 | if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec)) | |
9327 | { | |
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) | |
9330 | { | |
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; } | |
9333 | } | |
9334 | else | |
9335 | { | |
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; } | |
9338 | } | |
9339 | } | |
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)) | |
9342 | { | |
f0cc3e7b A |
9343 | LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)", |
9344 | m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r), IIDPrintable(InterfaceID)); | |
83fb1e36 A |
9345 | LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr)); |
9346 | ||
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) | |
9350 | { | |
9351 | while (rr->DependentOn) rr = rr->DependentOn; | |
9352 | LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr)); | |
9353 | } | |
9354 | ||
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) | |
9f221bca | 9359 | LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr)); |
83fb1e36 A |
9360 | else |
9361 | { | |
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) | |
9365 | { | |
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 | |
9376 | } | |
9377 | // If we're probing for this record, we just failed | |
9378 | else if (rr->resrec.RecordType == kDNSRecordTypeUnique) | |
9379 | { | |
9f221bca A |
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). | |
83fb1e36 A |
9383 | // Before we call deregister, check if this is a packet we registered with the sleep proxy. |
9384 | if (!mDNSCoreRegisteredProxyRecord(m, rr)) | |
9385 | { | |
f0cc3e7b | 9386 | if ((rr->ProbingConflictCount == 0) || (m->MPktNum != rr->LastConflictPktNum)) |
9f221bca | 9387 | { |
f0cc3e7b A |
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)) | |
9393 | { | |
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); | |
9401 | } | |
9402 | else | |
9403 | { | |
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); | |
9f221bca | 9410 | #endif |
f0cc3e7b A |
9411 | mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict); |
9412 | } | |
9f221bca | 9413 | } |
83fb1e36 A |
9414 | } |
9415 | } | |
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) | |
9422 | { | |
9423 | LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr)); | |
51601d48 | 9424 | m->mDNSStats.KnownUniqueNameConflicts++; |
f0cc3e7b | 9425 | #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) |
9f221bca A |
9426 | D2D_stop_advertising_record(rr); |
9427 | #endif | |
83fb1e36 A |
9428 | mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict); |
9429 | } | |
9430 | else | |
9431 | LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr)); | |
9432 | } | |
9433 | } | |
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). | |
19fa75a9 A |
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)) | |
9442 | { | |
9443 | rr->ImmedAnswer = mDNSInterfaceMark; | |
9444 | m->NextScheduledResponse = m->timenow; | |
9445 | } | |
83fb1e36 A |
9446 | } |
9447 | } | |
9448 | } | |
9449 | ||
83fb1e36 A |
9450 | if (!AcceptableResponse) |
9451 | { | |
19fa75a9 A |
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); | |
9456 | #else | |
9457 | not_answer_but_required_for_dnssec = mDNSfalse; | |
9458 | #endif | |
9459 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
9460 | AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords); | |
9461 | ||
9462 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
9463 | if (AcceptableResponse) mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService); | |
9464 | #else | |
83fb1e36 | 9465 | if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer; |
19fa75a9 | 9466 | #endif |
83fb1e36 A |
9467 | } |
9468 | ||
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 | |
f0cc3e7b | 9472 | if (!AcceptableResponse) { |
19fa75a9 A |
9473 | const char* savedString = ""; |
9474 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
9475 | savedString = (not_answer_but_required_for_dnssec ? "Saved for DNSSEC" : ""); | |
9476 | #endif | |
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); | |
f0cc3e7b | 9479 | } |
19fa75a9 | 9480 | |
83fb1e36 A |
9481 | if (m->rrcache_size && AcceptableResponse) |
9482 | { | |
12c5fa7a A |
9483 | const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash); |
9484 | CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec); | |
51601d48 | 9485 | CacheRecord *rr = mDNSNULL; |
83fb1e36 | 9486 | |
51601d48 | 9487 | // 2a. Check if this packet resource record is already in our cache. |
19fa75a9 | 9488 | rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, &cfp, InterfaceID); |
51601d48 | 9489 | |
83fb1e36 A |
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) | |
9493 | { | |
9494 | const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events); | |
51601d48 A |
9495 | mDNSs32 delay; |
9496 | ||
9497 | if (AddToCFList) | |
9498 | delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond); | |
9499 | else | |
564f2ae2 | 9500 | delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash); |
51601d48 | 9501 | |
83fb1e36 A |
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. | |
19fa75a9 | 9506 | rr = CreateNewCacheEntry(m, slot, cg, delay, mDNStrue, srcaddr); |
83fb1e36 A |
9507 | if (rr) |
9508 | { | |
19fa75a9 A |
9509 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) |
9510 | set_denial_records_in_cache_record(rr, &denial_of_existence_records); | |
9511 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
9512 | ||
51601d48 | 9513 | rr->responseFlags = response->h.flags; |
19fa75a9 A |
9514 | |
9515 | if (AddToCFList) | |
51601d48 A |
9516 | { |
9517 | *cfp = rr; | |
9518 | cfp = &rr->NextInCFList; | |
9519 | *cfp = (CacheRecord*)1; | |
9520 | } | |
9521 | else if (rr->DelayDelivery) | |
9522 | { | |
9523 | ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery); | |
9524 | } | |
9525 | } | |
9526 | } | |
83fb1e36 | 9527 | } |
51601d48 | 9528 | mDNSCoreResetRecord(m); |
83fb1e36 | 9529 | } |
6528fe3e | 9530 | |
7f0064bd | 9531 | exit: |
51601d48 | 9532 | mDNSCoreResetRecord(m); |
83fb1e36 A |
9533 | |
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) | |
9537 | { | |
9538 | CacheRecord *r1 = CacheFlushRecords, *r2; | |
12c5fa7a A |
9539 | const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash); |
9540 | const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec); | |
564f2ae2 | 9541 | mDNSBool purgedRecords = mDNSfalse; |
83fb1e36 A |
9542 | CacheFlushRecords = CacheFlushRecords->NextInCFList; |
9543 | r1->NextInCFList = mDNSNULL; | |
9544 | ||
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) | |
9559 | { | |
19fa75a9 A |
9560 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9561 | mDNSBool match; | |
9562 | #else | |
9563 | mDNSu32 id1; | |
9564 | mDNSu32 id2; | |
9565 | #endif | |
83fb1e36 A |
9566 | if (!r1->resrec.InterfaceID) |
9567 | { | |
19fa75a9 A |
9568 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9569 | match = (r1->resrec.dnsservice == r2->resrec.dnsservice) ? mDNStrue : mDNSfalse; | |
9570 | #else | |
83fb1e36 A |
9571 | id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0); |
9572 | id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0); | |
19fa75a9 | 9573 | #endif |
83fb1e36 A |
9574 | } |
9575 | else | |
9576 | { | |
19fa75a9 A |
9577 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9578 | match = mDNStrue; | |
9579 | #else | |
83fb1e36 | 9580 | id1 = id2 = 0; |
19fa75a9 | 9581 | #endif |
83fb1e36 | 9582 | } |
83fb1e36 A |
9583 | // For Unicast (null InterfaceID) the resolver IDs should also match |
9584 | if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) && | |
19fa75a9 A |
9585 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
9586 | (r1->resrec.InterfaceID || match) && | |
9587 | #else | |
83fb1e36 | 9588 | (r1->resrec.InterfaceID || (id1 == id2)) && |
19fa75a9 | 9589 | #endif |
83fb1e36 | 9590 | r1->resrec.rrtype == r2->resrec.rrtype && |
19fa75a9 A |
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) | |
9595 | #endif | |
9596 | ) | |
83fb1e36 | 9597 | { |
19fa75a9 | 9598 | if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal) |
83fb1e36 | 9599 | { |
19fa75a9 A |
9600 | verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2); |
9601 | r1->resrec.mortality = Mortality_Immortal; // Immortalize the replacement record | |
83fb1e36 | 9602 | } |
19fa75a9 A |
9603 | |
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) | |
83fb1e36 | 9607 | { |
19fa75a9 A |
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). | |
9613 | ||
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 | |
9620 | ||
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 | |
9624 | // GM builds. | |
9625 | if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1) | |
9626 | { | |
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) && | |
9629 | ResponseIsMDNS) | |
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; | |
9633 | } | |
9634 | r2->TimeRcvd = m->timenow; | |
9635 | SetNextCacheCheckTimeForRecord(m, r2); | |
83fb1e36 | 9636 | } |
19fa75a9 | 9637 | else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed |
83fb1e36 | 9638 | { |
19fa75a9 A |
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. | |
9650 | ||
9651 | // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary | |
9652 | // final expiration queries for this record. | |
9653 | ||
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) | |
9661 | { | |
9662 | LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2)); | |
9663 | r2->resrec.rroriginalttl = 0; | |
9664 | } | |
9665 | else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond) | |
9666 | { | |
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 | |
9674 | } | |
9675 | SetNextCacheCheckTimeForRecord(m, r2); | |
83fb1e36 | 9676 | } |
19fa75a9 A |
9677 | else |
9678 | { | |
f0cc3e7b | 9679 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
2682e09e A |
9680 | if (r2->resrec.mortality == Mortality_Ghost) |
9681 | { | |
9682 | DNSQuestion * q; | |
9683 | for (q = m->Questions; q; q=q->next) | |
9684 | { | |
9685 | if (!q->LongLived && ActiveQuestion(q) && | |
f0cc3e7b | 9686 | CacheRecordAnswersQuestion(r2, q) && |
2682e09e A |
9687 | q->metrics.expiredAnswerState == ExpiredAnswer_AnsweredWithExpired) |
9688 | { | |
9689 | q->metrics.expiredAnswerState = ExpiredAnswer_ExpiredAnswerChanged; | |
9690 | } | |
9691 | } | |
9692 | } | |
9693 | #endif | |
564f2ae2 A |
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; | |
83fb1e36 | 9697 | } |
83fb1e36 | 9698 | } |
19fa75a9 | 9699 | } |
83fb1e36 A |
9700 | |
9701 | if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to | |
9702 | { | |
564f2ae2 A |
9703 | if (r1->resrec.InterfaceID) |
9704 | { | |
9705 | r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash); | |
9706 | } | |
9707 | else | |
9708 | { | |
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; | |
9712 | } | |
83fb1e36 A |
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); | |
9716 | } | |
9717 | } | |
9718 | ||
83fb1e36 | 9719 | // See if we need to generate negative cache entries for unanswered unicast questions |
19fa75a9 A |
9720 | mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, |
9721 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
9722 | querier, uDNSService, | |
9723 | #endif | |
9724 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
9725 | &denial_of_existence_records, | |
9726 | #endif | |
9727 | LLQType); | |
51601d48 | 9728 | |
19fa75a9 A |
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) | |
83fb1e36 | 9732 | } |
67c8f8a1 | 9733 | |
294beb6e A |
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) | |
9739 | ||
263eeeab | 9740 | mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist) |
83fb1e36 A |
9741 | { |
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. | |
9746 | if (!e->l[0]) | |
9747 | { | |
9748 | LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero"); | |
9749 | return; | |
9750 | } | |
9751 | m->CurrentRecord = thelist; | |
9752 | while (m->CurrentRecord) | |
9753 | { | |
9754 | AuthRecord *const rr = m->CurrentRecord; | |
9755 | if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e)) | |
9756 | { | |
9757 | LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr)); | |
9758 | mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); | |
9759 | } | |
9760 | if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now | |
9761 | m->CurrentRecord = rr->next; | |
9762 | } | |
9763 | } | |
263eeeab A |
9764 | |
9765 | mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e) | |
83fb1e36 A |
9766 | { |
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); | |
9770 | } | |
263eeeab | 9771 | |
32bb7e43 | 9772 | mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result) |
83fb1e36 A |
9773 | { |
9774 | if (result && result != mStatus_MemFree) | |
9775 | LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar)); | |
9776 | ||
9777 | if (result == mStatus_NameConflict) | |
9778 | { | |
9779 | mDNS_Lock(m); | |
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]) | |
9782 | { | |
9f221bca A |
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 | |
83fb1e36 A |
9785 | } |
9786 | mDNS_Unlock(m); | |
9787 | } | |
9788 | ||
9789 | if (result == mStatus_NameConflict || result == mStatus_MemFree) | |
9790 | { | |
9791 | m->ProxyRecords--; | |
9792 | mDNSPlatformMemFree(ar); | |
9793 | mDNS_UpdateAllowSleep(m); | |
9794 | } | |
9795 | } | |
9796 | ||
51601d48 A |
9797 | mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth) |
9798 | { | |
9799 | int i; | |
9800 | mDNSs8 hval = 0; | |
9801 | int colons = 0; | |
9802 | mDNSu8 val = 0; | |
9803 | ||
9804 | for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++) | |
9805 | { | |
9806 | hval = HexVal(*ptr); | |
9807 | if (hval != -1) | |
9808 | { | |
9809 | val <<= 4; | |
9810 | val |= hval; | |
9811 | } | |
9812 | else if (*ptr == ':') | |
9813 | { | |
9f221bca A |
9814 | if (colons >=5) |
9815 | { | |
9816 | LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val); | |
9817 | return mDNSNULL; | |
9818 | } | |
51601d48 A |
9819 | eth->b[colons] = val; |
9820 | colons++; | |
9821 | val = 0; | |
9822 | } | |
9823 | } | |
9824 | if (colons != 5) | |
9825 | { | |
9826 | LogMsg("GetValueForMACAddr: Address malformed colons %d", colons); | |
9827 | return mDNSNULL; | |
9828 | } | |
9829 | eth->b[colons] = val; | |
9830 | return ptr; | |
9831 | } | |
9832 | ||
83fb1e36 A |
9833 | mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6) |
9834 | { | |
9835 | int hval; | |
9836 | int value; | |
9837 | int numBytes; | |
9838 | int digitsProcessed; | |
9839 | int zeroFillStart; | |
9840 | int numColons; | |
9841 | mDNSu8 v6addr[16]; | |
9842 | ||
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. | |
9845 | // | |
9846 | // First forms a address in "v6addr", then expands to fill the zeroes in and returns | |
9847 | // the result in "v6" | |
9848 | ||
9849 | numColons = numBytes = value = digitsProcessed = zeroFillStart = 0; | |
9850 | while (ptr < limit && *ptr != ' ') | |
9851 | { | |
9852 | hval = HexVal(*ptr); | |
9853 | if (hval != -1) | |
9854 | { | |
9855 | value <<= 4; | |
9856 | value |= hval; | |
9857 | digitsProcessed = 1; | |
9858 | } | |
9859 | else if (*ptr == ':') | |
9860 | { | |
9861 | if (!digitsProcessed) | |
9862 | { | |
9863 | // If we have already seen a "::", we should not see one more. Handle the special | |
9864 | // case of "::" | |
9865 | if (numColons) | |
9866 | { | |
9867 | // if we never filled any bytes and the next character is space (we have reached the end) | |
9868 | // we are done | |
9869 | if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ') | |
9870 | { | |
9871 | mDNSPlatformMemZero(v6->b, 16); | |
9872 | return ptr + 1; | |
9873 | } | |
9874 | LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart); | |
9875 | return mDNSNULL; | |
9876 | } | |
9877 | ||
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; | |
9881 | numColons++; | |
9882 | } | |
9883 | else if ((ptr + 1) < limit && *(ptr + 1) == ' ') | |
9884 | { | |
9885 | // We have a trailing ":" i.e., no more characters after ":" | |
9886 | LogMsg("GetValueForIPv6Addr: Trailing colon"); | |
9887 | return mDNSNULL; | |
9888 | } | |
9889 | else | |
9890 | { | |
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; } | |
9895 | ||
9896 | v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF); | |
9897 | v6addr[numBytes++] = (mDNSu8) (value & 0xFF); | |
9898 | digitsProcessed = value = 0; | |
9899 | ||
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; } | |
9902 | } | |
9903 | } | |
9904 | ptr++; | |
9905 | } | |
9906 | ||
9907 | // We should be processing the last set of bytes following the last ":" here | |
9908 | if (!digitsProcessed) | |
9909 | { | |
9910 | LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes); | |
9911 | return mDNSNULL; | |
9912 | } | |
9913 | ||
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); | |
9917 | ||
9918 | if (zeroFillStart) | |
9919 | { | |
9920 | int i, j, n; | |
9921 | for (i = 0; i < zeroFillStart; i++) | |
9922 | v6->b[i] = v6addr[i]; | |
9923 | for (j = i, n = 0; n < 16 - numBytes; j++, n++) | |
9924 | v6->b[j] = 0; | |
9925 | for (; j < 16; i++, j++) | |
9926 | v6->b[j] = v6addr[i]; | |
9927 | } | |
9928 | else if (numBytes == 16) | |
9929 | mDNSPlatformMemCopy(v6->b, v6addr, 16); | |
9930 | else | |
9931 | { | |
9932 | LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes); | |
9933 | return mDNSNULL; | |
9934 | } | |
9935 | return ptr; | |
9936 | } | |
9937 | ||
9938 | mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4) | |
9939 | { | |
83fb1e36 A |
9940 | mDNSu32 val; |
9941 | int dots = 0; | |
83fb1e36 | 9942 | val = 0; |
51601d48 A |
9943 | |
9944 | for ( ; ptr < limit && *ptr != ' '; ptr++) | |
83fb1e36 A |
9945 | { |
9946 | if (*ptr >= '0' && *ptr <= '9') | |
9947 | val = val * 10 + *ptr - '0'; | |
9948 | else if (*ptr == '.') | |
9949 | { | |
9f221bca A |
9950 | if (val > 255 || dots >= 3) |
9951 | { | |
9952 | LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); | |
9953 | return mDNSNULL; | |
9954 | } | |
83fb1e36 A |
9955 | v4->b[dots++] = val; |
9956 | val = 0; | |
9957 | } | |
9958 | else | |
9959 | { | |
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) | |
9962 | { | |
9963 | v4->b[dots] = val; | |
9964 | return ptr + 1; | |
9965 | } | |
9966 | else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; } | |
9967 | } | |
9968 | } | |
9969 | if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; } | |
9970 | v4->b[dots] = val; | |
9971 | return ptr; | |
9972 | } | |
9973 | ||
9974 | mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value) | |
9975 | { | |
83fb1e36 A |
9976 | mDNSu32 val; |
9977 | ||
9978 | val = 0; | |
51601d48 | 9979 | for ( ; ptr < limit && *ptr != ' '; ptr++) |
83fb1e36 A |
9980 | { |
9981 | if (*ptr < '0' || *ptr > '9') | |
9982 | { | |
9983 | // We have a zero at the end and if we reached that, then we are done. | |
9984 | if (*ptr == 0 && ptr == limit - 1) | |
9985 | { | |
9986 | *value = val; | |
9987 | return ptr + 1; | |
9988 | } | |
9989 | else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; } | |
9990 | } | |
9991 | val = val * 10 + *ptr - '0'; | |
9992 | } | |
9993 | *value = val; | |
9994 | return ptr; | |
9995 | } | |
9996 | ||
9f221bca A |
9997 | mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr) |
9998 | { | |
9999 | mDNSAddr laddr, raddr; | |
10000 | mDNSEthAddr eth; | |
10001 | mDNSIPPort lport, rport; | |
10002 | mDNSu32 timeout, seq, ack; | |
10003 | mDNSu16 win; | |
10004 | ||
10005 | if (!mDNS_KeepaliveRecord(&rr->resrec)) | |
10006 | { | |
10007 | return mDNSfalse; | |
10008 | } | |
10009 | ||
10010 | timeout = seq = ack = 0; | |
10011 | win = 0; | |
10012 | laddr = raddr = zeroAddr; | |
10013 | lport = rport = zeroIPPort; | |
10014 | eth = zeroEthAddr; | |
10015 | ||
10016 | mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); | |
10017 | ||
10018 | if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) || | |
10019 | mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) || | |
10020 | mDNSEthAddressIsZero(eth)) | |
10021 | { | |
10022 | return mDNSfalse; | |
10023 | } | |
10024 | ||
10025 | return mDNStrue; | |
10026 | } | |
10027 | ||
10028 | ||
51601d48 | 10029 | mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq, |
83fb1e36 A |
10030 | mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win) |
10031 | { | |
10032 | if (ar->resrec.rrtype != kDNSType_NULL) | |
10033 | return; | |
10034 | ||
10035 | if (mDNS_KeepaliveRecord(&ar->resrec)) | |
10036 | { | |
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 | |
51601d48 | 10040 | mDNSu32 value = 0; |
83fb1e36 A |
10041 | |
10042 | while (ptr < limit) | |
10043 | { | |
10044 | mDNSu8 param = *ptr; | |
83fb1e36 A |
10045 | ptr += 2; // Skip the letter and the "=" |
10046 | if (param == 'h') | |
10047 | { | |
10048 | laddr->type = mDNSAddrType_IPv4; | |
10049 | ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4); | |
10050 | } | |
10051 | else if (param == 'd') | |
10052 | { | |
10053 | raddr->type = mDNSAddrType_IPv4; | |
10054 | ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4); | |
10055 | } | |
9f221bca | 10056 | else if (param == 'H') |
83fb1e36 A |
10057 | { |
10058 | laddr->type = mDNSAddrType_IPv6; | |
10059 | ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6); | |
10060 | } | |
10061 | else if (param == 'D') | |
10062 | { | |
10063 | raddr->type = mDNSAddrType_IPv6; | |
10064 | ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6); | |
10065 | } | |
51601d48 A |
10066 | else if (param == 'm') |
10067 | { | |
10068 | ptr = GetValueForMACAddr(ptr, limit, eth); | |
10069 | } | |
83fb1e36 A |
10070 | else |
10071 | { | |
10072 | ptr = GetValueForKeepalive(ptr, limit, &value); | |
10073 | } | |
10074 | if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; } | |
10075 | ||
83fb1e36 A |
10076 | // Extract everything in network order so that it is easy for sending a keepalive and also |
10077 | // for matching incoming TCP packets | |
10078 | switch (param) | |
10079 | { | |
10080 | case 't': | |
10081 | *timeout = value; | |
10082 | //if (*timeout < 120) *timeout = 120; | |
10083 | break; | |
10084 | case 'h': | |
10085 | case 'H': | |
10086 | case 'd': | |
10087 | case 'D': | |
51601d48 A |
10088 | case 'm': |
10089 | case 'i': | |
10090 | case 'c': | |
83fb1e36 A |
10091 | break; |
10092 | case 'l': | |
51601d48 | 10093 | lport->NotAnInteger = swap16((mDNSu16)value); |
83fb1e36 A |
10094 | break; |
10095 | case 'r': | |
51601d48 | 10096 | rport->NotAnInteger = swap16((mDNSu16)value); |
83fb1e36 A |
10097 | break; |
10098 | case 's': | |
51601d48 | 10099 | *seq = swap32(value); |
83fb1e36 A |
10100 | break; |
10101 | case 'a': | |
51601d48 | 10102 | *ack = swap32(value); |
83fb1e36 A |
10103 | break; |
10104 | case 'w': | |
51601d48 | 10105 | *win = swap16((mDNSu16)value); |
83fb1e36 A |
10106 | break; |
10107 | default: | |
51601d48 | 10108 | LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param); |
83fb1e36 A |
10109 | ptr = limit; |
10110 | break; | |
10111 | } | |
10112 | ptr++; // skip the space | |
10113 | } | |
10114 | } | |
10115 | } | |
10116 | ||
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. | |
51601d48 | 10119 | mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport, |
83fb1e36 A |
10120 | const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack) |
10121 | { | |
10122 | AuthRecord *ar; | |
10123 | mDNSAddr laddr, raddr; | |
51601d48 | 10124 | mDNSEthAddr eth; |
83fb1e36 A |
10125 | mDNSIPPort lport, rport; |
10126 | mDNSu32 timeout, seq, ack; | |
10127 | mDNSu16 win; | |
10128 | ||
10129 | for (ar = m->ResourceRecords; ar; ar=ar->next) | |
10130 | { | |
10131 | timeout = seq = ack = 0; | |
10132 | win = 0; | |
10133 | laddr = raddr = zeroAddr; | |
10134 | lport = rport = zeroIPPort; | |
10135 | ||
10136 | if (!ar->WakeUp.HMAC.l[0]) continue; | |
10137 | ||
51601d48 | 10138 | mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); |
83fb1e36 A |
10139 | |
10140 | // Did we parse correctly ? | |
10141 | if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win) | |
10142 | { | |
10143 | debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar)); | |
10144 | continue; | |
10145 | } | |
10146 | ||
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)); | |
10149 | ||
10150 | // Does it match the incoming TCP packet ? | |
10151 | if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport)) | |
10152 | { | |
10153 | // returning in network order | |
10154 | *rseq = seq; | |
10155 | *rack = ack; | |
10156 | return ar; | |
10157 | } | |
10158 | } | |
10159 | return mDNSNULL; | |
10160 | } | |
10161 | ||
10162 | mDNSlocal void mDNS_SendKeepalives(mDNS *const m) | |
10163 | { | |
10164 | AuthRecord *ar; | |
10165 | ||
10166 | for (ar = m->ResourceRecords; ar; ar=ar->next) | |
10167 | { | |
10168 | mDNSu32 timeout, seq, ack; | |
10169 | mDNSu16 win; | |
10170 | mDNSAddr laddr, raddr; | |
51601d48 | 10171 | mDNSEthAddr eth; |
83fb1e36 A |
10172 | mDNSIPPort lport, rport; |
10173 | ||
10174 | timeout = seq = ack = 0; | |
10175 | win = 0; | |
10176 | ||
10177 | laddr = raddr = zeroAddr; | |
10178 | lport = rport = zeroIPPort; | |
10179 | ||
10180 | if (!ar->WakeUp.HMAC.l[0]) continue; | |
10181 | ||
51601d48 | 10182 | mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); |
83fb1e36 A |
10183 | |
10184 | if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win) | |
10185 | { | |
10186 | debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar)); | |
10187 | continue; | |
10188 | } | |
10189 | LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport)); | |
10190 | ||
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)) | |
10194 | { | |
10195 | mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win); | |
10196 | ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond); | |
10197 | } | |
10198 | if (m->NextScheduledKA - ar->KATimeExpire > 0) | |
10199 | m->NextScheduledKA = ar->KATimeExpire; | |
10200 | } | |
10201 | } | |
67c8f8a1 | 10202 | |
51601d48 A |
10203 | mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar) |
10204 | { | |
9f221bca | 10205 | mDNSu32 timeout, seq, ack, seqInc; |
51601d48 A |
10206 | mDNSu16 win; |
10207 | mDNSAddr laddr, raddr; | |
10208 | mDNSEthAddr eth; | |
10209 | mDNSIPPort lport, rport; | |
9f221bca A |
10210 | mDNSu8 *ptr; |
10211 | ||
10212 | if (ar == mDNSNULL) | |
10213 | { | |
10214 | LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL"); | |
10215 | return; | |
10216 | } | |
51601d48 A |
10217 | |
10218 | timeout = seq = ack = 0; | |
10219 | win = 0; | |
10220 | ||
10221 | laddr = raddr = zeroAddr; | |
10222 | lport = rport = zeroIPPort; | |
10223 | ||
10224 | mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); | |
10225 | ||
10226 | if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win) | |
10227 | { | |
10228 | LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar)); | |
10229 | return; | |
10230 | } | |
9f221bca A |
10231 | |
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); | |
51601d48 A |
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); | |
10244 | } | |
10245 | ||
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, | |
83fb1e36 A |
10249 | const mDNSInterfaceID InterfaceID) |
10250 | { | |
10251 | int i; | |
10252 | AuthRecord opt; | |
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; | |
10256 | const mDNSu8 *ptr; | |
10257 | ||
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); | |
10265 | ||
10266 | if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return; | |
10267 | ||
10268 | if (mDNS_PacketLoggingEnabled) | |
f0cc3e7b | 10269 | DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID); |
83fb1e36 A |
10270 | |
10271 | ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space); | |
10272 | if (ptr) | |
10273 | { | |
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) | |
10276 | { | |
10277 | const rdataOPT *o; | |
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++) | |
10280 | { | |
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; | |
10283 | } | |
10284 | } | |
10285 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it | |
10286 | } | |
10287 | ||
10288 | InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags); | |
10289 | ||
10290 | if (!updatelease || !owner.HMAC.l[0]) | |
10291 | { | |
10292 | static int msgs = 0; | |
10293 | if (msgs < 100) | |
10294 | { | |
10295 | msgs++; | |
10296 | LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport), | |
10297 | !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : ""); | |
10298 | } | |
10299 | m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr; | |
10300 | } | |
10301 | else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS) | |
10302 | { | |
10303 | static int msgs = 0; | |
10304 | if (msgs < 100) | |
10305 | { | |
10306 | msgs++; | |
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); | |
10309 | } | |
10310 | m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; | |
10311 | } | |
10312 | else | |
10313 | { | |
10314 | LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq); | |
10315 | ||
10316 | if (updatelease > 24 * 60 * 60) | |
10317 | updatelease = 24 * 60 * 60; | |
10318 | ||
10319 | if (updatelease > 0x40000000UL / mDNSPlatformOneSecond) | |
10320 | updatelease = 0x40000000UL / mDNSPlatformOneSecond; | |
10321 | ||
10322 | ptr = LocateAuthorities(msg, end); | |
51601d48 A |
10323 | |
10324 | // Clear any stale TCP keepalive records that may exist | |
10325 | ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID); | |
10326 | ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID); | |
10327 | ||
83fb1e36 A |
10328 | for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++) |
10329 | { | |
10330 | ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec); | |
10331 | if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative) | |
10332 | { | |
10333 | mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec); | |
f0cc3e7b | 10334 | AuthRecord *ar = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem); |
51601d48 A |
10335 | if (!ar) |
10336 | { | |
10337 | m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; | |
10338 | break; | |
10339 | } | |
83fb1e36 A |
10340 | else |
10341 | { | |
10342 | mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared; | |
10343 | m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet; | |
51601d48 A |
10344 | // All stale keepalive records have been flushed prior to this loop. |
10345 | if (!mDNS_KeepaliveRecord(&m->rec.r.resrec)) | |
10346 | { | |
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); | |
10349 | } | |
83fb1e36 A |
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) | |
10358 | { | |
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); | |
10364 | } | |
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); | |
51601d48 | 10371 | |
83fb1e36 A |
10372 | m->ProxyRecords++; |
10373 | mDNS_UpdateAllowSleep(m); | |
10374 | LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar)); | |
10375 | } | |
10376 | } | |
10377 | m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it | |
10378 | } | |
10379 | ||
10380 | if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask) | |
10381 | { | |
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); | |
10385 | } | |
10386 | else | |
10387 | { | |
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); | |
10395 | } | |
10396 | } | |
10397 | ||
f0cc3e7b | 10398 | if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, mDNSNULL, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSfalse); |
83fb1e36 A |
10399 | mDNS_SendKeepalives(m); |
10400 | } | |
32bb7e43 | 10401 | |
9f221bca A |
10402 | mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg) |
10403 | { | |
10404 | mDNSu8 *ptr = msg->data; | |
10405 | mDNSu8 *end = mDNSNULL; | |
10406 | mDNSu32 length = 0; | |
10407 | AuthRecord opt; | |
12c5fa7a | 10408 | NetworkInterfaceInfo *intf; |
9f221bca A |
10409 | |
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); | |
10414 | ||
12c5fa7a | 10415 | intf = FirstInterfaceForID(m, InterfaceID); |
9f221bca A |
10416 | SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]); |
10417 | ||
10418 | LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt)); | |
10419 | end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec); | |
10420 | if (end != mDNSNULL) | |
10421 | { | |
10422 | // Put all the integer values in IETF byte-order (MSB first, LSB second) | |
10423 | SwapDNSHeaderBytes(msg); | |
19fa75a9 | 10424 | length = (mDNSu32)(end - msg->data); |
9f221bca A |
10425 | } |
10426 | else | |
10427 | LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record"); | |
10428 | ||
10429 | return length; | |
10430 | } | |
10431 | ||
12c5fa7a A |
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. | |
51601d48 | 10436 | mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID) |
83fb1e36 A |
10437 | { |
10438 | if (InterfaceID) | |
10439 | { | |
12c5fa7a A |
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); | |
83fb1e36 A |
10444 | |
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) | |
10449 | { | |
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)) | |
10453 | { | |
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); | |
12c5fa7a A |
10462 | spsupdates++; |
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)); | |
83fb1e36 A |
10464 | if (rr->WakeUp.HMAC.l[0]) |
10465 | { | |
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); | |
10469 | } | |
10470 | } | |
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; | |
10475 | } | |
12c5fa7a | 10476 | if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response |
9f221bca | 10477 | { |
12c5fa7a A |
10478 | char *ifname; |
10479 | mDNSAddr spsaddr; | |
10480 | DNSMessage optMsg; | |
10481 | int length; | |
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); | |
10486 | ||
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); | |
10491 | if (length != 0) | |
10492 | { | |
10493 | length += sizeof(DNSMessageHeader); | |
10494 | mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length); | |
10495 | } | |
9f221bca | 10496 | } |
83fb1e36 A |
10497 | } |
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; | |
10501 | } | |
32bb7e43 | 10502 | |
19fa75a9 A |
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) | |
10507 | #else | |
10508 | DNSServer *dnsserver) | |
10509 | #endif | |
83fb1e36 A |
10510 | { |
10511 | if (cr == &m->rec.r && m->rec.r.resrec.RecordType) | |
9f221bca | 10512 | LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r)); |
83fb1e36 A |
10513 | |
10514 | // Create empty resource record | |
10515 | cr->resrec.RecordType = kDNSRecordTypePacketNegative; | |
10516 | cr->resrec.InterfaceID = InterfaceID; | |
19fa75a9 A |
10517 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
10518 | mdns_replace(&cr->resrec.dnsservice, service); | |
10519 | #else | |
83fb1e36 | 10520 | cr->resrec.rDNSServer = dnsserver; |
19fa75a9 | 10521 | #endif |
83fb1e36 A |
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; | |
10532 | ||
10533 | cr->NextInKAList = mDNSNULL; | |
10534 | cr->TimeRcvd = m->timenow; | |
10535 | cr->DelayDelivery = 0; | |
10536 | cr->NextRequiredQuery = m->timenow; | |
19fa75a9 A |
10537 | #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) |
10538 | cr->LastCachedAnswerTime= 0; | |
10539 | #endif | |
83fb1e36 A |
10540 | cr->CRActiveQuestion = mDNSNULL; |
10541 | cr->UnansweredQueries = 0; | |
10542 | cr->LastUnansweredTime = 0; | |
83fb1e36 | 10543 | cr->NextInCFList = mDNSNULL; |
51601d48 | 10544 | cr->soa = mDNSNULL; |
51601d48 A |
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; | |
83fb1e36 | 10548 | } |
6528fe3e | 10549 | |
19fa75a9 A |
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) | |
10553 | { | |
10554 | SwapDNSHeaderBytes(msg); | |
10555 | mDNS_Lock(m); | |
10556 | mDNSCoreReceiveResponse(m, msg, end, mDNSNULL, zeroIPPort, mDNSNULL, zeroIPPort, querier, dnsservice, mDNSNULL); | |
10557 | mDNS_Unlock(m); | |
10558 | } | |
10559 | #endif | |
10560 | ||
5a93c909 | 10561 | mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, |
83fb1e36 A |
10562 | const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport, |
10563 | const mDNSInterfaceID InterfaceID) | |
10564 | { | |
10565 | mDNSInterfaceID ifid = InterfaceID; | |
5a93c909 | 10566 | const mDNSu8 *const pkt = (mDNSu8 *)msg; |
83fb1e36 A |
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; | |
10571 | mDNSu8 QR_OP; | |
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; | |
7f0064bd | 10575 | |
67c8f8a1 | 10576 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
10577 | if (mDNSSameAddress(srcaddr, &m->Router)) |
10578 | { | |
030b743d | 10579 | #ifdef _LEGACY_NAT_TRAVERSAL_ |
83fb1e36 A |
10580 | if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port))) |
10581 | { | |
10582 | mDNS_Lock(m); | |
5a93c909 | 10583 | LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt)); |
83fb1e36 A |
10584 | mDNS_Unlock(m); |
10585 | return; | |
10586 | } | |
030b743d | 10587 | #endif |
83fb1e36 A |
10588 | if (mDNSSameIPPort(srcport, NATPMPPort)) |
10589 | { | |
10590 | mDNS_Lock(m); | |
5a93c909 | 10591 | uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt)); |
83fb1e36 A |
10592 | mDNS_Unlock(m); |
10593 | return; | |
10594 | } | |
10595 | } | |
32bb7e43 | 10596 | #ifdef _LEGACY_NAT_TRAVERSAL_ |
83fb1e36 | 10597 | else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; } |
32bb7e43 A |
10598 | #endif |
10599 | ||
67c8f8a1 | 10600 | #endif |
5a93c909 | 10601 | if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader)) |
83fb1e36 | 10602 | { |
5a93c909 | 10603 | LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt)); |
83fb1e36 A |
10604 | return; |
10605 | } | |
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]); | |
10613 | ||
10614 | if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; } | |
10615 | ||
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 | |
f0cc3e7b | 10618 | if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; } |
83fb1e36 A |
10619 | |
10620 | mDNS_Lock(m); | |
10621 | m->PktNum++; | |
51601d48 A |
10622 | if (mDNSOpaque16IsZero(msg->h.id)) |
10623 | { | |
10624 | m->MPktNum++; | |
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. | |
12c5fa7a | 10629 | if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr && |
51601d48 A |
10630 | mDNSAddressIsAllDNSLinkGroup(dstaddr)) |
10631 | { | |
10632 | m->RemoteSubnet++; | |
10633 | } | |
10634 | #endif // #if APPLE_OSX_mDNSResponder | |
10635 | } | |
10636 | ||
7f0064bd | 10637 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
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 | |
10640 | { | |
10641 | ifid = mDNSInterface_Any; | |
10642 | if (mDNS_PacketLoggingEnabled) | |
f0cc3e7b | 10643 | DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID); |
83fb1e36 A |
10644 | uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport); |
10645 | // Note: mDNSCore also needs to get access to received unicast responses | |
10646 | } | |
67c8f8a1 | 10647 | #endif |
83fb1e36 | 10648 | if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid); |
19fa75a9 A |
10649 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
10650 | else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, mDNSNULL, mDNSNULL, ifid); | |
10651 | #else | |
83fb1e36 | 10652 | else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid); |
19fa75a9 | 10653 | #endif |
83fb1e36 | 10654 | else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID); |
51601d48 | 10655 | else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID); |
83fb1e36 A |
10656 | else |
10657 | { | |
83fb1e36 A |
10658 | if (mDNS_LoggingEnabled) |
10659 | { | |
9f221bca A |
10660 | static int msgCount = 0; |
10661 | if (msgCount < 1000) { | |
9f221bca | 10662 | int i = 0; |
12c5fa7a | 10663 | msgCount++; |
9f221bca | 10664 | LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)", |
5a93c909 A |
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)) | |
9f221bca A |
10667 | { |
10668 | char buffer[128]; | |
10669 | char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i); | |
5a93c909 | 10670 | do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15); |
9f221bca A |
10671 | LogInfo("%s", buffer); |
10672 | } | |
83fb1e36 A |
10673 | } |
10674 | } | |
10675 | } | |
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 | |
10681 | mDNS_Unlock(m); | |
10682 | } | |
6528fe3e A |
10683 | |
10684 | // *************************************************************************** | |
c9b9ae52 | 10685 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e | 10686 | #pragma mark - |
6528fe3e A |
10687 | #pragma mark - Searcher Functions |
10688 | #endif | |
10689 | ||
96f69b28 A |
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. | |
263eeeab A |
10695 | // |
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. | |
51601d48 | 10703 | // |
96f69b28 | 10704 | |
32bb7e43 A |
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 | |
f0cc3e7b A |
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)) | |
32bb7e43 | 10712 | |
6528fe3e | 10713 | mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question) |
83fb1e36 A |
10714 | { |
10715 | DNSQuestion *q; | |
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. | |
f0cc3e7b A |
10720 | for (q = m->Questions; q && (q != question); q = q->next) |
10721 | { | |
19fa75a9 A |
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; | |
10734 | #endif | |
10735 | if (!SameDomainName(&q->qname, &question->qname)) continue; | |
f0cc3e7b A |
10736 | return(q); |
10737 | } | |
83fb1e36 A |
10738 | return(mDNSNULL); |
10739 | } | |
6528fe3e | 10740 | |
030b743d | 10741 | // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates |
67c8f8a1 | 10742 | mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question) |
83fb1e36 A |
10743 | { |
10744 | DNSQuestion *q; | |
10745 | DNSQuestion *first = mDNSNULL; | |
10746 | ||
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) | |
10750 | { | |
19fa75a9 | 10751 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, |
f0cc3e7b | 10752 | "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME " (" PUB_S ") duplicate of %p " PRI_DM_NAME " (" PUB_S ")", |
19fa75a9 A |
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)); | |
83fb1e36 A |
10756 | return; |
10757 | } | |
10758 | ||
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 | |
10761 | { | |
10762 | q->DuplicateOf = first; | |
10763 | if (!first) | |
10764 | { | |
10765 | first = q; | |
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; | |
19fa75a9 A |
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); | |
10785 | #else | |
83fb1e36 A |
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; | |
19fa75a9 | 10791 | #endif |
83fb1e36 A |
10792 | |
10793 | q->TargetQID = question->TargetQID; | |
19fa75a9 | 10794 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 | 10795 | q->LocalSocket = question->LocalSocket; |
9f221bca | 10796 | // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets |
19fa75a9 | 10797 | #endif |
83fb1e36 A |
10798 | |
10799 | q->state = question->state; | |
9f221bca | 10800 | // q->tcp = question->tcp; |
83fb1e36 A |
10801 | q->ReqLease = question->ReqLease; |
10802 | q->expire = question->expire; | |
10803 | q->ntries = question->ntries; | |
10804 | q->id = question->id; | |
83fb1e36 | 10805 | |
19fa75a9 | 10806 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 | 10807 | question->LocalSocket = mDNSNULL; |
19fa75a9 | 10808 | #endif |
83fb1e36 | 10809 | question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question |
9f221bca | 10810 | // question->tcp = mDNSNULL; |
83fb1e36 | 10811 | |
19fa75a9 | 10812 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 A |
10813 | if (q->LocalSocket) |
10814 | debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
19fa75a9 | 10815 | #endif |
83fb1e36 A |
10816 | if (q->nta) |
10817 | { | |
10818 | LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
10819 | q->nta->ZoneDataContext = q; | |
10820 | } | |
10821 | ||
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"); | |
10824 | ||
10825 | if (question->state == LLQ_Established) | |
10826 | { | |
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 | |
10829 | } | |
10830 | ||
10831 | SetNextQueryTime(m,q); | |
10832 | } | |
10833 | } | |
10834 | } | |
294beb6e A |
10835 | |
10836 | mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout) | |
83fb1e36 A |
10837 | { |
10838 | McastResolver **p = &m->McastResolvers; | |
10839 | McastResolver *tmp = mDNSNULL; | |
10840 | ||
10841 | if (!d) d = (const domainname *)""; | |
10842 | ||
f0cc3e7b A |
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); | |
83fb1e36 | 10845 | |
51601d48 | 10846 | mDNS_CheckLock(m); |
83fb1e36 A |
10847 | |
10848 | while (*p) // Check if we already have this {interface, domain} tuple registered | |
10849 | { | |
10850 | if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d)) | |
10851 | { | |
9f221bca A |
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; | |
83fb1e36 A |
10854 | tmp = *p; |
10855 | *p = tmp->next; | |
10856 | tmp->next = mDNSNULL; | |
10857 | } | |
10858 | else | |
10859 | p=&(*p)->next; | |
10860 | } | |
10861 | ||
10862 | if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer | |
10863 | else | |
10864 | { | |
10865 | // allocate, add to list | |
f0cc3e7b | 10866 | *p = (McastResolver *) mDNSPlatformMemAllocateClear(sizeof(**p)); |
83fb1e36 A |
10867 | if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc"); |
10868 | else | |
10869 | { | |
10870 | (*p)->interface = interface; | |
9f221bca | 10871 | (*p)->flags = McastResolver_FlagNew; |
83fb1e36 A |
10872 | (*p)->timeout = timeout; |
10873 | AssignDomainName(&(*p)->domain, d); | |
10874 | (*p)->next = mDNSNULL; | |
10875 | } | |
10876 | } | |
10877 | return(*p); | |
10878 | } | |
67c8f8a1 | 10879 | |
19fa75a9 | 10880 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
ca3eca6b | 10881 | mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server) |
83fb1e36 A |
10882 | { |
10883 | mDNSs32 ptime = 0; | |
10884 | if (server->penaltyTime != 0) | |
10885 | { | |
10886 | ptime = server->penaltyTime - m->timenow; | |
10887 | if (ptime < 0) | |
10888 | { | |
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 | |
10891 | // here | |
10892 | LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty", | |
10893 | ptime, server->penaltyTime, m->timenow); | |
10894 | server->penaltyTime = 0; | |
10895 | ptime = 0; | |
10896 | } | |
10897 | } | |
10898 | return ptime; | |
10899 | } | |
19fa75a9 | 10900 | #endif |
ca3eca6b | 10901 | |
ca3eca6b A |
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, | |
83fb1e36 A |
10908 | int bestcount) |
10909 | { | |
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; | |
10913 | ||
10914 | // If there is no match, return -1 and the caller will skip this newname for | |
10915 | // selection | |
10916 | // | |
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 | |
10920 | // | |
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. | |
10923 | // | |
10924 | // Note: newcount can either be equal or greater than bestcount beause of the | |
10925 | // check above. | |
10926 | ||
10927 | if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname)) | |
10928 | return bestcount == newcount ? 0 : 1; | |
10929 | else | |
10930 | return -1; | |
10931 | } | |
ca3eca6b | 10932 | |
294beb6e A |
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 | |
83fb1e36 | 10936 | #define DEFAULT_MCAST_TIMEOUT 5 |
294beb6e | 10937 | mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question) |
83fb1e36 A |
10938 | { |
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) | |
10944 | { | |
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) | |
10950 | { | |
10951 | curmatch = curr; | |
10952 | bestmatchlen = currcount; | |
10953 | } | |
10954 | } | |
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); | |
10958 | } | |
294beb6e | 10959 | |
4a95efb2 A |
10960 | // Returns true if it is a Domain Enumeration Query |
10961 | mDNSexport mDNSBool DomainEnumQuery(const domainname *qname) | |
83fb1e36 A |
10962 | { |
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; | |
10967 | int i = 0; | |
10968 | ||
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; } | |
10971 | ||
10972 | label = (const mDNSu8 *)d; | |
10973 | while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL) | |
10974 | { | |
10975 | if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;} | |
10976 | i++; | |
10977 | } | |
10978 | if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL) | |
10979 | { | |
10980 | debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c); | |
10981 | return mDNSfalse; | |
10982 | } | |
10983 | debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); | |
10984 | ||
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")) | |
10989 | { | |
10990 | debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c); | |
10991 | return(mDNSfalse); | |
10992 | } | |
10993 | debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c); | |
10994 | ||
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")) | |
10998 | { | |
10999 | debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c); | |
11000 | return(mDNSfalse); | |
11001 | } | |
11002 | debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c); | |
11003 | ||
11004 | debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c); | |
11005 | ||
11006 | return mDNStrue; | |
11007 | } | |
4a95efb2 | 11008 | |
19fa75a9 | 11009 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
51601d48 A |
11010 | // Note: InterfaceID is the InterfaceID of the question |
11011 | mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID) | |
11012 | { | |
672757b6 A |
11013 | // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer |
11014 | // with scopeType set to kScopeNone) | |
51601d48 A |
11015 | // |
11016 | // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer | |
672757b6 | 11017 | // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match. |
51601d48 A |
11018 | // |
11019 | // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer | |
672757b6 | 11020 | // with scopeType set to kScopeServiceID) and their ServiceIDs should match. |
9f221bca | 11021 | // |
51601d48 A |
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. | |
11024 | // | |
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): | |
11027 | // | |
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). | |
11030 | // | |
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. | |
11034 | // | |
11035 | // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer | |
11036 | // should match (Refer to (2) above). | |
51601d48 | 11037 | |
f0cc3e7b | 11038 | if (((d->scopeType == kScopeNone) && (!InterfaceID && ServiceID == -1)) || |
672757b6 A |
11039 | ((d->scopeType == kScopeInterfaceID) && d->interface == InterfaceID) || |
11040 | ((d->scopeType == kScopeServiceID) && d->serviceID == ServiceID)) | |
51601d48 A |
11041 | { |
11042 | return mDNStrue; | |
11043 | } | |
11044 | return mDNSfalse; | |
11045 | } | |
11046 | ||
263eeeab | 11047 | // Sets all the Valid DNS servers for a question |
294beb6e | 11048 | mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question) |
83fb1e36 | 11049 | { |
83fb1e36 A |
11050 | int bestmatchlen = -1, namecount = CountLabels(&question->qname); |
11051 | DNSServer *curr; | |
11052 | int bettermatch, currcount; | |
11053 | int index = 0; | |
11054 | mDNSu32 timeout = 0; | |
11055 | mDNSBool DEQuery; | |
11056 | ||
12c5fa7a | 11057 | question->validDNSServers = zeroOpaque128; |
83fb1e36 A |
11058 | DEQuery = DomainEnumQuery(&question->qname); |
11059 | for (curr = m->DNSServers; curr; curr = curr->next) | |
11060 | { | |
f0cc3e7b | 11061 | debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scopeType); |
83fb1e36 | 11062 | // skip servers that will soon be deleted |
f0cc3e7b | 11063 | if (curr->flags & DNSServerFlag_Delete) |
51601d48 | 11064 | { |
f0cc3e7b | 11065 | debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType); |
51601d48 A |
11066 | continue; |
11067 | } | |
83fb1e36 A |
11068 | |
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. | |
11074 | // | |
11075 | // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout | |
11076 | ||
9f221bca | 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 |
672757b6 A |
11078 | if (((curr->scopeType == kScopeInterfaceID) && (curr->interface == mDNSInterface_Any)) || |
11079 | ((curr->scopeType == kScopeServiceID) && (curr->serviceID <= 0))) | |
51601d48 | 11080 | { |
672757b6 A |
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); | |
51601d48 A |
11083 | continue; |
11084 | } | |
83fb1e36 A |
11085 | |
11086 | currcount = CountLabels(&curr->domain); | |
f0cc3e7b | 11087 | if ((!DEQuery || !curr->isCell) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID)) |
83fb1e36 A |
11088 | { |
11089 | bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen); | |
11090 | ||
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 | |
11094 | // bit | |
11095 | if ((bettermatch == 1) || (bettermatch == 0)) | |
11096 | { | |
83fb1e36 | 11097 | bestmatchlen = currcount; |
51601d48 A |
11098 | if (bettermatch) |
11099 | { | |
11100 | debugf("SetValidDNSServers: Resetting all the bits"); | |
12c5fa7a | 11101 | question->validDNSServers = zeroOpaque128; |
51601d48 A |
11102 | timeout = 0; |
11103 | } | |
83fb1e36 | 11104 | debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d," |
f0cc3e7b | 11105 | " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scopeType, index, curr->timeout, |
83fb1e36 A |
11106 | curr->interface); |
11107 | timeout += curr->timeout; | |
51601d48 | 11108 | if (DEQuery) |
672757b6 | 11109 | debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->isCell); |
12c5fa7a | 11110 | bit_set_opaque128(question->validDNSServers, index); |
83fb1e36 A |
11111 | } |
11112 | } | |
11113 | index++; | |
11114 | } | |
11115 | question->noServerResponse = 0; | |
11116 | ||
f0cc3e7b | 11117 | debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)", |
12c5fa7a | 11118 | question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype)); |
51601d48 | 11119 | // If there are no matching resolvers, then use the default timeout value. |
19fa75a9 | 11120 | return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT); |
83fb1e36 | 11121 | } |
263eeeab | 11122 | |
ca3eca6b A |
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 | |
12c5fa7a | 11125 | mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits, |
51601d48 | 11126 | int *selected, mDNSBool nameMatch) |
83fb1e36 A |
11127 | { |
11128 | DNSServer *curmatch = mDNSNULL; | |
11129 | int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0; | |
11130 | DNSServer *curr; | |
11131 | mDNSs32 bestPenaltyTime, currPenaltyTime; | |
11132 | int bettermatch, currcount; | |
11133 | int index = 0; | |
11134 | int currindex = -1; | |
11135 | ||
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) | |
11139 | { | |
11140 | // skip servers that will soon be deleted | |
f0cc3e7b | 11141 | if (curr->flags & DNSServerFlag_Delete) |
51601d48 | 11142 | { |
f0cc3e7b | 11143 | debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType); |
51601d48 A |
11144 | continue; |
11145 | } | |
83fb1e36 A |
11146 | |
11147 | // Check if this is a valid DNSServer | |
51601d48 A |
11148 | if (!bit_get_opaque64(validBits, index)) |
11149 | { | |
11150 | debugf("GetBestServer: continuing for index %d", index); | |
11151 | index++; | |
11152 | continue; | |
11153 | } | |
83fb1e36 A |
11154 | |
11155 | currcount = CountLabels(&curr->domain); | |
11156 | currPenaltyTime = PenaltyTimeForServer(m, curr); | |
11157 | ||
11158 | debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d", | |
11159 | &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime); | |
11160 | ||
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 | |
51601d48 | 11166 | // when there are some penalized servers. |
83fb1e36 | 11167 | |
51601d48 | 11168 | if (DNSServerMatch(curr, InterfaceID, ServiceID)) |
83fb1e36 A |
11169 | { |
11170 | ||
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 | |
11175 | ||
51601d48 A |
11176 | if (nameMatch) |
11177 | bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen); | |
11178 | else | |
11179 | bettermatch = 0; | |
83fb1e36 A |
11180 | |
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 | |
11184 | ||
11185 | if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime)) | |
51601d48 A |
11186 | { |
11187 | currindex = index; | |
11188 | curmatch = curr; | |
11189 | bestmatchlen = currcount; | |
11190 | bestPenaltyTime = currPenaltyTime; | |
11191 | } | |
83fb1e36 A |
11192 | } |
11193 | index++; | |
11194 | } | |
11195 | if (selected) *selected = currindex; | |
11196 | return curmatch; | |
11197 | } | |
ca3eca6b | 11198 | |
263eeeab | 11199 | // Look up a DNS Server, matching by name and InterfaceID |
51601d48 | 11200 | mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID) |
83fb1e36 A |
11201 | { |
11202 | DNSServer *curmatch = mDNSNULL; | |
11203 | char *ifname = mDNSNULL; // for logging purposes only | |
12c5fa7a | 11204 | mDNSOpaque128 allValid; |
263eeeab | 11205 | |
f0cc3e7b | 11206 | if (InterfaceID == mDNSInterface_LocalOnly) |
83fb1e36 | 11207 | InterfaceID = mDNSNULL; |
263eeeab | 11208 | |
83fb1e36 | 11209 | if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID); |
263eeeab | 11210 | |
83fb1e36 | 11211 | // By passing in all ones, we make sure that every DNS server is considered |
12c5fa7a | 11212 | allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF; |
263eeeab | 11213 | |
51601d48 | 11214 | curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue); |
263eeeab | 11215 | |
83fb1e36 | 11216 | if (curmatch != mDNSNULL) |
2682e09e | 11217 | LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr, |
83fb1e36 A |
11218 | mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None", |
11219 | InterfaceID, name); | |
11220 | else | |
2682e09e | 11221 | LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name); |
263eeeab | 11222 | |
83fb1e36 A |
11223 | return(curmatch); |
11224 | } | |
263eeeab A |
11225 | |
11226 | // Look up a DNS Server for a question within its valid DNSServer bits | |
11227 | mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question) | |
83fb1e36 A |
11228 | { |
11229 | DNSServer *curmatch = mDNSNULL; | |
11230 | char *ifname = mDNSNULL; // for logging purposes only | |
11231 | mDNSInterfaceID InterfaceID = question->InterfaceID; | |
11232 | const domainname *name = &question->qname; | |
11233 | int currindex; | |
67c8f8a1 | 11234 | |
f0cc3e7b | 11235 | if (InterfaceID == mDNSInterface_LocalOnly) |
83fb1e36 | 11236 | InterfaceID = mDNSNULL; |
263eeeab | 11237 | |
51601d48 A |
11238 | if (InterfaceID) |
11239 | ifname = InterfaceNameForID(m, InterfaceID); | |
263eeeab | 11240 | |
12c5fa7a | 11241 | if (!mDNSOpaque128IsZero(&question->validDNSServers)) |
83fb1e36 | 11242 | { |
51601d48 A |
11243 | curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse); |
11244 | if (currindex != -1) | |
12c5fa7a | 11245 | bit_clr_opaque128(question->validDNSServers, currindex); |
83fb1e36 | 11246 | } |
ca3eca6b | 11247 | |
83fb1e36 | 11248 | if (curmatch != mDNSNULL) |
51601d48 | 11249 | { |
f0cc3e7b A |
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)); | |
51601d48 | 11255 | } |
83fb1e36 | 11256 | else |
51601d48 | 11257 | { |
f0cc3e7b A |
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)); | |
51601d48 | 11262 | } |
ca3eca6b | 11263 | |
83fb1e36 A |
11264 | return(curmatch); |
11265 | } | |
19fa75a9 | 11266 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
67c8f8a1 | 11267 | |
96f69b28 A |
11268 | // Called in normal client context (lock not held) |
11269 | mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n) | |
83fb1e36 A |
11270 | { |
11271 | DNSQuestion *q; | |
83fb1e36 A |
11272 | mDNS_Lock(m); |
11273 | LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result); | |
51601d48 | 11274 | n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T |
83fb1e36 A |
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 | |
83fb1e36 A |
11278 | mDNS_Unlock(m); |
11279 | } | |
11280 | ||
51601d48 | 11281 | // This function takes the DNSServer as a separate argument because sometimes the |
f0cc3e7b | 11282 | // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed |
51601d48 | 11283 | // status before switching to it. |
19fa75a9 A |
11284 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11285 | mDNSexport mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const mdns_dns_service_t dnsservice) | |
11286 | #else | |
f0cc3e7b | 11287 | mDNSlocal mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const DNSServer *const server) |
19fa75a9 | 11288 | #endif |
83fb1e36 | 11289 | { |
f0cc3e7b | 11290 | mDNSBool suppress = mDNSfalse; |
19fa75a9 | 11291 | const char *reason = mDNSNULL; |
83fb1e36 | 11292 | |
f0cc3e7b | 11293 | if (q->BlockedByPolicy) |
51601d48 | 11294 | { |
f0cc3e7b A |
11295 | suppress = mDNStrue; |
11296 | reason = " (blocked by policy)"; | |
51601d48 | 11297 | } |
19fa75a9 A |
11298 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11299 | else if (!dnsservice) | |
11300 | { | |
11301 | if (!q->IsUnicastDotLocal) | |
11302 | { | |
11303 | suppress = mDNStrue; | |
11304 | reason = " (no DNS service)"; | |
11305 | } | |
11306 | } | |
11307 | #else | |
f0cc3e7b | 11308 | else if (!server) |
51601d48 | 11309 | { |
f0cc3e7b | 11310 | if (!q->IsUnicastDotLocal) |
0b74dd16 | 11311 | { |
f0cc3e7b A |
11312 | suppress = mDNStrue; |
11313 | reason = " (no DNS server)"; | |
0b74dd16 | 11314 | } |
51601d48 | 11315 | } |
19fa75a9 A |
11316 | #endif |
11317 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
11318 | else if ((q->flags & kDNSServiceFlagsDenyCellular) && mdns_dns_service_interface_is_cellular(dnsservice)) | |
11319 | #else | |
11320 | else if ((q->flags & kDNSServiceFlagsDenyCellular) && server->isCell) | |
11321 | #endif | |
51601d48 | 11322 | { |
f0cc3e7b A |
11323 | suppress = mDNStrue; |
11324 | reason = " (interface is cellular)"; | |
51601d48 | 11325 | } |
19fa75a9 A |
11326 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11327 | else if ((q->flags & kDNSServiceFlagsDenyExpensive) && mdns_dns_service_interface_is_expensive(dnsservice)) | |
11328 | #else | |
11329 | else if ((q->flags & kDNSServiceFlagsDenyExpensive) && server->isExpensive) | |
11330 | #endif | |
12c5fa7a | 11331 | { |
f0cc3e7b A |
11332 | suppress = mDNStrue; |
11333 | reason = " (interface is expensive)"; | |
12c5fa7a | 11334 | } |
19fa75a9 A |
11335 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11336 | else if ((q->flags & kDNSServiceFlagsDenyConstrained) && mdns_dns_service_interface_is_constrained(dnsservice)) | |
11337 | #else | |
11338 | else if ((q->flags & kDNSServiceFlagsDenyConstrained) && server->isConstrained) | |
11339 | #endif | |
f0cc3e7b A |
11340 | { |
11341 | suppress = mDNStrue; | |
11342 | reason = " (interface is constrained)"; | |
11343 | } | |
11344 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) | |
11345 | else if (q->SuppressUnusable && !DNS64IsQueryingARecord(q->dns64.state)) | |
11346 | #else | |
11347 | else if (q->SuppressUnusable) | |
12c5fa7a | 11348 | #endif |
83fb1e36 | 11349 | { |
f0cc3e7b | 11350 | if (q->qtype == kDNSType_A) |
51601d48 | 11351 | { |
19fa75a9 A |
11352 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11353 | if (!mdns_dns_service_a_queries_advised(dnsservice)) | |
11354 | #else | |
f0cc3e7b | 11355 | if (!server->usableA) |
19fa75a9 | 11356 | #endif |
f0cc3e7b A |
11357 | { |
11358 | suppress = mDNStrue; | |
11359 | reason = " (A records are unusable)"; | |
11360 | } | |
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. | |
19fa75a9 A |
11365 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11366 | else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && mdns_dns_service_interface_is_clat46(dnsservice)) | |
11367 | #else | |
11368 | else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && server->isCLAT46) | |
11369 | #endif | |
f0cc3e7b A |
11370 | { |
11371 | suppress = mDNStrue; | |
11372 | reason = " (CLAT46 A records are unusable)"; | |
11373 | } | |
51601d48 | 11374 | } |
f0cc3e7b | 11375 | else if (q->qtype == kDNSType_AAAA) |
83fb1e36 | 11376 | { |
19fa75a9 A |
11377 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11378 | if (!mdns_dns_service_aaaa_queries_advised(dnsservice)) | |
11379 | #else | |
f0cc3e7b | 11380 | if (!server->usableAAAA) |
19fa75a9 | 11381 | #endif |
f0cc3e7b A |
11382 | { |
11383 | suppress = mDNStrue; | |
11384 | reason = " (AAAA records are unusable)"; | |
11385 | } | |
83fb1e36 A |
11386 | } |
11387 | } | |
f0cc3e7b A |
11388 | if (suppress) |
11389 | { | |
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 : ""); | |
11393 | } | |
11394 | return suppress; | |
83fb1e36 | 11395 | } |
263eeeab | 11396 | |
f0cc3e7b | 11397 | mDNSlocal mDNSBool ShouldSuppressQuery(DNSQuestion *q) |
51601d48 | 11398 | { |
19fa75a9 A |
11399 | // Multicast queries are never suppressed. |
11400 | if (mDNSOpaque16IsZero(q->TargetQID)) | |
51601d48 | 11401 | { |
51601d48 A |
11402 | return mDNSfalse; |
11403 | } | |
19fa75a9 A |
11404 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11405 | return (ShouldSuppressUnicastQuery(q, q->dnsservice)); | |
11406 | #else | |
f0cc3e7b | 11407 | return (ShouldSuppressUnicastQuery(q, q->qDNSServer)); |
19fa75a9 | 11408 | #endif |
51601d48 A |
11409 | } |
11410 | ||
294beb6e | 11411 | mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q) |
83fb1e36 | 11412 | { |
f0cc3e7b | 11413 | CacheRecord *cr; |
83fb1e36 A |
11414 | CacheGroup *cg; |
11415 | ||
12c5fa7a | 11416 | cg = CacheGroupForName(m, q->qnamehash, &q->qname); |
f0cc3e7b | 11417 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) |
83fb1e36 A |
11418 | { |
11419 | // Don't deliver RMV events for negative records | |
f0cc3e7b | 11420 | if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) |
83fb1e36 | 11421 | { |
f0cc3e7b A |
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", | |
19fa75a9 | 11424 | q->request_id, mDNSVal16(q->TargetQID), CRDisplayString(m, cr), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), cr->CRActiveQuestion, q->CurrentAnswers); |
83fb1e36 A |
11425 | continue; |
11426 | } | |
11427 | ||
f0cc3e7b | 11428 | if (SameNameCacheRecordAnswersQuestion(cr, q)) |
83fb1e36 A |
11429 | { |
11430 | LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d", | |
f0cc3e7b | 11431 | q->qname.c, CRDisplayString(m, cr), q->LOAddressAnswers); |
83fb1e36 A |
11432 | |
11433 | q->CurrentAnswers--; | |
f0cc3e7b A |
11434 | if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--; |
11435 | if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--; | |
11436 | AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv); | |
83fb1e36 A |
11437 | if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here |
11438 | } | |
11439 | } | |
11440 | } | |
263eeeab A |
11441 | |
11442 | mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question) | |
83fb1e36 A |
11443 | { |
11444 | DNSQuestion *q; | |
11445 | for (q = m->NewQuestions; q; q = q->next) | |
11446 | if (q == question) return mDNStrue; | |
11447 | return mDNSfalse; | |
11448 | } | |
263eeeab | 11449 | |
19fa75a9 A |
11450 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11451 | mDNSexport mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q) | |
11452 | #else | |
294beb6e | 11453 | mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q) |
19fa75a9 | 11454 | #endif |
83fb1e36 A |
11455 | { |
11456 | AuthRecord *rr; | |
83fb1e36 A |
11457 | AuthGroup *ag; |
11458 | ||
11459 | if (m->CurrentQuestion) | |
11460 | LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)", | |
11461 | m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); | |
11462 | ||
11463 | if (IsQuestionNew(m, q)) | |
11464 | { | |
11465 | LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
11466 | return mDNStrue; | |
11467 | } | |
11468 | m->CurrentQuestion = q; | |
12c5fa7a | 11469 | ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); |
83fb1e36 A |
11470 | if (ag) |
11471 | { | |
11472 | for (rr = ag->members; rr; rr=rr->next) | |
11473 | // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME | |
51601d48 | 11474 | if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q)) |
83fb1e36 A |
11475 | { |
11476 | LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s", | |
11477 | ARDisplayString(m, rr)); | |
11478 | if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0) | |
11479 | { | |
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); | |
11483 | continue; | |
11484 | } | |
11485 | AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again | |
11486 | if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; } | |
11487 | } | |
11488 | } | |
11489 | m->CurrentQuestion = mDNSNULL; | |
11490 | return mDNStrue; | |
11491 | } | |
294beb6e A |
11492 | |
11493 | // Returns false if the question got deleted while delivering the RMV events | |
83fb1e36 | 11494 | // The caller should handle the case |
12c5fa7a | 11495 | mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q) |
83fb1e36 A |
11496 | { |
11497 | if (m->CurrentQuestion) | |
11498 | LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)", | |
11499 | m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); | |
11500 | ||
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) | |
11504 | { | |
11505 | m->CurrentQuestion = q; | |
11506 | CacheRecordRmvEventsForCurrentQuestion(m, q); | |
11507 | if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; } | |
11508 | m->CurrentQuestion = mDNSNULL; | |
11509 | } | |
11510 | else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); } | |
11511 | return mDNStrue; | |
11512 | } | |
294beb6e | 11513 | |
51601d48 A |
11514 | mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart) |
11515 | { | |
11516 | // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero | |
95d7a4a3 | 11517 | // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before |
51601d48 | 11518 | // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers) |
f0cc3e7b | 11519 | if (q->Suppressed) |
51601d48 | 11520 | { |
f0cc3e7b | 11521 | q->Suppressed = mDNSfalse; |
51601d48 A |
11522 | if (!CacheRecordRmvEventsForQuestion(m, q)) |
11523 | { | |
f0cc3e7b A |
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)); | |
51601d48 A |
11527 | return; |
11528 | } | |
f0cc3e7b | 11529 | q->Suppressed = mDNStrue; |
51601d48 A |
11530 | } |
11531 | ||
11532 | // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts) | |
f0cc3e7b | 11533 | // and Suppressed status does not mean anything for these questions. As we are going to stop the |
51601d48 A |
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)) | |
11537 | { | |
f0cc3e7b A |
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)); | |
51601d48 A |
11541 | return; |
11542 | } | |
11543 | ||
11544 | // There are two cases here. | |
11545 | // | |
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. | |
11551 | // | |
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 | |
f0cc3e7b | 11554 | // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false). |
51601d48 | 11555 | // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed |
f0cc3e7b | 11556 | // (Suppressed is true). The reason for this is that when a question is suppressed, we want an |
51601d48 A |
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. | |
11561 | // | |
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. | |
11568 | // | |
11569 | // It is much cleaner and less error prone to build a list of questions and restart at the end. | |
11570 | ||
f0cc3e7b A |
11571 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, |
11572 | "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME " (" PUB_S ")", | |
19fa75a9 | 11573 | q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); |
51601d48 A |
11574 | mDNS_StopQuery_internal(m, q); |
11575 | q->next = *restart; | |
11576 | *restart = q; | |
11577 | } | |
11578 | ||
263eeeab A |
11579 | // The caller should hold the lock |
11580 | mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m) | |
83fb1e36 A |
11581 | { |
11582 | DNSQuestion *q; | |
11583 | DNSQuestion *restart = mDNSNULL; | |
11584 | ||
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 | |
f0cc3e7b | 11589 | // new questions, we would never change its Suppressed status. |
83fb1e36 A |
11590 | // |
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) | |
11601 | { | |
11602 | q = m->RestartQuestion; | |
11603 | m->RestartQuestion = q->next; | |
51601d48 | 11604 | if (q->SuppressUnusable) |
83fb1e36 | 11605 | { |
f0cc3e7b A |
11606 | const mDNSBool old = q->Suppressed; |
11607 | q->Suppressed = ShouldSuppressQuery(q); | |
11608 | if (q->Suppressed != old) | |
83fb1e36 | 11609 | { |
51601d48 A |
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); | |
11614 | } | |
11615 | } | |
11616 | } | |
11617 | while (restart) | |
11618 | { | |
11619 | 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); | |
11624 | } | |
11625 | } | |
83fb1e36 | 11626 | |
19fa75a9 | 11627 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
51601d48 A |
11628 | mDNSlocal void RestartUnicastQuestions(mDNS *const m) |
11629 | { | |
11630 | DNSQuestion *q; | |
f0cc3e7b | 11631 | DNSQuestion *restartList = mDNSNULL; |
51601d48 A |
11632 | |
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) | |
11638 | { | |
11639 | q = m->RestartQuestion; | |
11640 | m->RestartQuestion = q->next; | |
11641 | if (q->Restart) | |
11642 | { | |
11643 | if (mDNSOpaque16IsZero(q->TargetQID)) | |
11644 | LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); | |
9f221bca | 11645 | |
f0cc3e7b A |
11646 | q->Restart = mDNSfalse; |
11647 | SuppressStatusChanged(m, q, &restartList); | |
51601d48 A |
11648 | } |
11649 | } | |
f0cc3e7b | 11650 | while ((q = restartList) != mDNSNULL) |
51601d48 | 11651 | { |
f0cc3e7b | 11652 | restartList = q->next; |
51601d48 | 11653 | q->next = mDNSNULL; |
f0cc3e7b A |
11654 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, |
11655 | "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME " (" PUB_S ")", | |
19fa75a9 | 11656 | q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); |
51601d48 A |
11657 | mDNS_StartQuery_internal(m, q); |
11658 | } | |
11659 | } | |
19fa75a9 | 11660 | #endif |
83fb1e36 | 11661 | |
51601d48 A |
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) | |
11665 | { | |
51601d48 A |
11666 | if (!ValidateDomainName(&question->qname)) |
11667 | { | |
11668 | LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); | |
11669 | return(mStatus_Invalid); | |
11670 | } | |
11671 | ||
11672 | // If this question is referencing a specific interface, verify it exists | |
f0cc3e7b | 11673 | if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID)) |
51601d48 A |
11674 | { |
11675 | NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID); | |
11676 | if (!intf) | |
b8d5688b | 11677 | LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list", |
f0cc3e7b | 11678 | IIDPrintable(question->InterfaceID), question->qname.c, DNSTypeName(question->qtype)); |
51601d48 | 11679 | } |
9f221bca | 11680 | |
51601d48 A |
11681 | return(mStatus_NoError); |
11682 | } | |
11683 | ||
11684 | // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question. | |
564f2ae2 | 11685 | // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve() |
51601d48 A |
11686 | mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question) |
11687 | { | |
11688 | // First reset all DNS Configuration | |
19fa75a9 A |
11689 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11690 | mdns_forget(&question->dnsservice); | |
11691 | #else | |
51601d48 | 11692 | question->qDNSServer = mDNSNULL; |
12c5fa7a | 11693 | question->validDNSServers = zeroOpaque128; |
f0cc3e7b A |
11694 | question->triedAllServersOnce = mDNSfalse; |
11695 | question->noServerResponse = mDNSfalse; | |
19fa75a9 | 11696 | #endif |
12c5fa7a | 11697 | question->StopTime = (question->TimeoutQuestion) ? question->StopTime : 0; |
f0cc3e7b | 11698 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
9f221bca | 11699 | mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics)); |
2682e09e | 11700 | question->metrics.expiredAnswerState = (question->allowExpired != AllowExpired_None) ? ExpiredAnswer_Allowed : ExpiredAnswer_None; |
9f221bca | 11701 | #endif |
51601d48 | 11702 | |
12c5fa7a A |
11703 | // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified |
11704 | if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion) | |
51601d48 A |
11705 | return; |
11706 | // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers()) | |
11707 | if (!mDNSOpaque16IsZero(question->TargetQID)) | |
9f221bca | 11708 | { |
19fa75a9 A |
11709 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11710 | mDNSu32 timeout = 30; | |
11711 | #else | |
51601d48 | 11712 | mDNSu32 timeout = SetValidDNSServers(m, question); |
19fa75a9 | 11713 | #endif |
12c5fa7a A |
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, | |
51601d48 | 11717 | // it gets a full timeout value even if the original question times out earlier. |
12c5fa7a | 11718 | if (question->TimeoutQuestion && !question->StopTime) |
51601d48 A |
11719 | { |
11720 | question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond); | |
f0cc3e7b A |
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 ")", | |
19fa75a9 | 11723 | mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); |
83fb1e36 | 11724 | } |
51601d48 | 11725 | |
19fa75a9 A |
11726 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11727 | Querier_SetDNSServiceForQuestion(question); | |
11728 | #else | |
51601d48 | 11729 | question->qDNSServer = GetServerForQuestion(m, question); |
f0cc3e7b A |
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", | |
19fa75a9 | 11732 | question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), |
f0cc3e7b A |
11733 | DNSTypeName(question->qtype), timeout, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL, |
11734 | mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort)); | |
19fa75a9 | 11735 | #endif |
51601d48 | 11736 | } |
12c5fa7a | 11737 | else if (question->TimeoutQuestion && !question->StopTime) |
9f221bca | 11738 | { |
12c5fa7a A |
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); | |
f0cc3e7b A |
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 ")", | |
19fa75a9 | 11746 | question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); |
51601d48 A |
11747 | } |
11748 | // Set StopTime here since it is a part of DNS Configuration | |
11749 | if (question->StopTime) | |
11750 | SetNextQueryStopTime(m, question); | |
12c5fa7a A |
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); | |
51601d48 A |
11755 | } |
11756 | ||
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. | |
564f2ae2 | 11759 | mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question) |
51601d48 | 11760 | { |
51601d48 A |
11761 | int i; |
11762 | ||
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 | |
19fa75a9 | 11775 | // turned ON which can allocate memory e.g., base64 encoding. |
51601d48 A |
11776 | question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question |
11777 | question->qnamehash = DomainNameHashValue(&question->qname); | |
564f2ae2 | 11778 | question->DelayAnswering = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0; |
51601d48 A |
11779 | question->LastQTime = m->timenow; |
11780 | question->ExpectUnicastResp = 0; | |
11781 | question->LastAnswerPktNum = m->PktNum; | |
11782 | question->RecentAnswerPkts = 0; | |
11783 | question->CurrentAnswers = 0; | |
11784 | ||
11785 | #if APPLE_OSX_mDNSResponder | |
11786 | ||
11787 | // Initial browse threshold used by Finder. | |
11788 | #define mDNSFinderBrowseThreshold 20 | |
11789 | ||
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; | |
11796 | else | |
11797 | question->BrowseThreshold = 0; | |
11798 | ||
11799 | #else // APPLE_OSX_mDNSResponder | |
11800 | question->BrowseThreshold = 0; | |
11801 | #endif // APPLE_OSX_mDNSResponder | |
11802 | question->CachedAnswerNeedsUpdate = mDNSfalse; | |
11803 | ||
11804 | question->LargeAnswers = 0; | |
11805 | question->UniqueAnswers = 0; | |
11806 | question->LOAddressAnswers = 0; | |
11807 | question->FlappingInterface1 = mDNSNULL; | |
11808 | question->FlappingInterface2 = mDNSNULL; | |
9f221bca | 11809 | |
19fa75a9 A |
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; | |
11813 | ||
9f221bca A |
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)) | |
11817 | { | |
9f221bca | 11818 | question->ServiceID = -1; |
19fa75a9 A |
11819 | #if APPLE_OSX_mDNSResponder |
11820 | if (!(question->flags & kDNSServiceFlagsPathEvaluationDone) || question->ForcePathEval) | |
11821 | { | |
11822 | if (question->flags & kDNSServiceFlagsPathEvaluationDone) | |
11823 | { | |
11824 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, | |
11825 | "[R%u->Q%u] Forcing another path evaluation", question->request_id, mDNSVal16(question->TargetQID)); | |
11826 | } | |
11827 | question->ForcePathEval = mDNSfalse; | |
11828 | mDNSPlatformGetDNSRoutePolicy(question); | |
11829 | } | |
9f221bca A |
11830 | #endif |
11831 | } | |
11832 | else | |
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); | |
11835 | ||
51601d48 | 11836 | InitDNSConfig(m, question); |
51601d48 | 11837 | question->AuthInfo = GetAuthInfoForQuestion(m, question); |
f0cc3e7b | 11838 | question->Suppressed = ShouldSuppressQuery(question); |
51601d48 A |
11839 | question->NextInDQList = mDNSNULL; |
11840 | question->SendQNow = mDNSNULL; | |
11841 | question->SendOnAll = mDNSfalse; | |
9f221bca | 11842 | question->RequestUnicast = kDefaultRequestUnicastCount; |
51601d48 A |
11843 | |
11844 | #if APPLE_OSX_mDNSResponder | |
9f221bca A |
11845 | // Set the QU bit in the first query for the following options. |
11846 | if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder)) | |
51601d48 | 11847 | { |
9f221bca | 11848 | question->RequestUnicast = SET_QU_IN_FIRST_QUERY; |
51601d48 A |
11849 | LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c, |
11850 | DNSTypeName(question->qtype)); | |
51601d48 A |
11851 | } |
11852 | #endif // APPLE_OSX_mDNSResponder | |
11853 | ||
11854 | question->LastQTxTime = m->timenow; | |
9f221bca | 11855 | question->CNAMEReferrals = 0; |
51601d48 A |
11856 | |
11857 | question->WakeOnResolveCount = 0; | |
11858 | if (question->WakeOnResolve) | |
9f221bca | 11859 | { |
51601d48 | 11860 | question->WakeOnResolveCount = InitialWakeOnResolveCount; |
9f221bca | 11861 | } |
51601d48 A |
11862 | |
11863 | for (i=0; i<DupSuppressInfoSize; i++) | |
11864 | question->DupSuppress[i].InterfaceID = mDNSNULL; | |
11865 | ||
19fa75a9 | 11866 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
f0cc3e7b | 11867 | question->Restart = mDNSfalse; |
19fa75a9 | 11868 | #endif |
51601d48 A |
11869 | |
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); | |
11875 | ||
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)); | |
51601d48 A |
11879 | } |
11880 | ||
11881 | // Excludes the DNS Config fields which are already handled by InitDNSConfig() | |
11882 | mDNSlocal void InitWABState(DNSQuestion *const question) | |
11883 | { | |
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. | |
9f221bca | 11888 | question->LocalSocket = mDNSNULL; |
19fa75a9 A |
11889 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
11890 | mdns_querier_forget(&question->querier); | |
11891 | #else | |
51601d48 | 11892 | question->unansweredQueries = 0; |
19fa75a9 | 11893 | #endif |
51601d48 A |
11894 | question->nta = mDNSNULL; |
11895 | question->servAddr = zeroAddr; | |
11896 | question->servPort = zeroIPPort; | |
11897 | question->tcp = mDNSNULL; | |
11898 | question->NoAnswer = NoAnswer_Normal; | |
11899 | } | |
11900 | ||
11901 | mDNSlocal void InitLLQNATState(mDNS *const m) | |
11902 | { | |
11903 | // If we don't have our NAT mapping active, start it now | |
11904 | if (!m->LLQNAT.clientCallback) | |
11905 | { | |
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); | |
11912 | } | |
11913 | } | |
11914 | ||
11915 | mDNSlocal void InitLLQState(DNSQuestion *const question) | |
11916 | { | |
f0cc3e7b | 11917 | question->state = LLQ_Init; |
51601d48 A |
11918 | question->ReqLease = 0; |
11919 | question->expire = 0; | |
11920 | question->ntries = 0; | |
11921 | question->id = zeroOpaque64; | |
11922 | } | |
11923 | ||
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) | |
11927 | { | |
11928 | (void) m; | |
19fa75a9 | 11929 | question->responseFlags = zeroID; |
51601d48 A |
11930 | } |
11931 | ||
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. | |
564f2ae2 | 11935 | mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question) |
51601d48 A |
11936 | { |
11937 | // Ensure DNS related info of duplicate question is same as the orig question | |
11938 | if (question->DuplicateOf) | |
11939 | { | |
19fa75a9 A |
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)); | |
11947 | #else | |
51601d48 | 11948 | question->validDNSServers = question->DuplicateOf->validDNSServers; |
12c5fa7a A |
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) | |
11952 | { | |
19fa75a9 A |
11953 | if (question->qDNSServer) |
11954 | { | |
f0cc3e7b A |
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, | |
19fa75a9 | 11960 | DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); |
f0cc3e7b | 11961 | } |
12c5fa7a | 11962 | } |
51601d48 | 11963 | question->qDNSServer = question->DuplicateOf->qDNSServer; |
f0cc3e7b A |
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", | |
19fa75a9 A |
11966 | question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID), |
11967 | question, question->DuplicateOf, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), | |
f0cc3e7b A |
11968 | question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL, |
11969 | mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort)); | |
19fa75a9 | 11970 | #endif |
51601d48 A |
11971 | } |
11972 | ||
11973 | ActivateUnicastQuery(m, question, mDNSfalse); | |
11974 | ||
51601d48 A |
11975 | if (question->LongLived) |
11976 | { | |
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); | |
83fb1e36 A |
11983 | } |
11984 | } | |
263eeeab | 11985 | |
67c8f8a1 | 11986 | mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question) |
83fb1e36 | 11987 | { |
51601d48 A |
11988 | DNSQuestion **q; |
11989 | mStatus vStatus; | |
8e92c31c | 11990 | |
51601d48 A |
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); | |
7f0064bd | 11994 | |
51601d48 A |
11995 | vStatus = ValidateParameters(m, question); |
11996 | if (vStatus) | |
11997 | return(vStatus); | |
9f221bca A |
11998 | |
11999 | #ifdef USE_LIBIDN | |
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.) | |
f0cc3e7b A |
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. | |
9f221bca A |
12004 | if (IsHighASCIILabel(LastLabel(&question->qname))) |
12005 | { | |
12006 | domainname newname; | |
12007 | if (PerformNextPunycodeConversion(question, &newname)) | |
12008 | AssignDomainName(&question->qname, &newname); | |
12009 | } | |
12010 | #endif // USE_LIBIDN | |
12011 | ||
67c8f8a1 | 12012 | #ifndef UNICAST_DISABLED |
f0cc3e7b A |
12013 | question->TargetQID = Question_uDNS(question) ? mDNS_NewMessageID(m) : zeroID; |
12014 | #else | |
12015 | question->TargetQID = zeroID; | |
12016 | #endif | |
9f221bca A |
12017 | debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); |
12018 | ||
51601d48 A |
12019 | // Note: It important that new questions are appended at the *end* of the list, not prepended at the start |
12020 | q = &m->Questions; | |
9f221bca | 12021 | if (LocalOnlyOrP2PInterface(question->InterfaceID)) |
51601d48 | 12022 | q = &m->LocalOnlyQuestions; |
9f221bca | 12023 | while (*q && *q != question) |
51601d48 | 12024 | q=&(*q)->next; |
83fb1e36 | 12025 | |
51601d48 | 12026 | if (*q) |
83fb1e36 | 12027 | { |
51601d48 A |
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); | |
12031 | } | |
12032 | *q = question; | |
83fb1e36 | 12033 | |
51601d48 A |
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 | |
12037 | // validation. | |
83fb1e36 | 12038 | |
564f2ae2 | 12039 | InitCommonState(m, question); |
51601d48 A |
12040 | InitWABState(question); |
12041 | InitLLQState(question); | |
12042 | InitDNSSECProxyState(m, question); | |
83fb1e36 | 12043 | |
51601d48 A |
12044 | // FindDuplicateQuestion should be called last after all the intialization |
12045 | // as the duplicate logic could be potentially based on any field in the | |
12046 | // question. | |
12047 | question->DuplicateOf = FindDuplicateQuestion(m, question); | |
9f221bca A |
12048 | if (question->DuplicateOf) |
12049 | question->AuthInfo = question->DuplicateOf->AuthInfo; | |
83fb1e36 | 12050 | |
9f221bca | 12051 | if (LocalOnlyOrP2PInterface(question->InterfaceID)) |
51601d48 | 12052 | { |
9f221bca | 12053 | if (!m->NewLocalOnlyQuestions) |
51601d48 A |
12054 | m->NewLocalOnlyQuestions = question; |
12055 | } | |
12056 | else | |
12057 | { | |
9f221bca | 12058 | if (!m->NewQuestions) |
51601d48 | 12059 | m->NewQuestions = question; |
83fb1e36 | 12060 | |
51601d48 A |
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)) | |
83fb1e36 | 12068 | { |
564f2ae2 | 12069 | FinalizeUnicastQuestion(m, question); |
83fb1e36 A |
12070 | } |
12071 | else | |
12072 | { | |
f0cc3e7b | 12073 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca | 12074 | m->NumAllInterfaceQuestions++; |
f0cc3e7b A |
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)); | |
9f221bca A |
12078 | if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) |
12079 | { | |
12080 | m->NextBonjourDisableTime = 0; | |
12081 | if (m->BonjourEnabled == 0) | |
12082 | { | |
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; | |
12087 | } | |
12088 | } | |
f0cc3e7b | 12089 | #endif |
564f2ae2 | 12090 | if (question->WakeOnResolve) |
83fb1e36 | 12091 | { |
51601d48 | 12092 | LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c); |
564f2ae2 | 12093 | mDNS_PurgeBeforeResolve(m, question); |
83fb1e36 | 12094 | } |
83fb1e36 | 12095 | } |
83fb1e36 | 12096 | } |
51601d48 A |
12097 | |
12098 | return(mStatus_NoError); | |
83fb1e36 | 12099 | } |
6528fe3e | 12100 | |
67c8f8a1 A |
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) | |
83fb1e36 A |
12103 | { |
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 | |
12107 | // call it again | |
12108 | if (nta->question.ThisQInterval != -1) | |
12109 | { | |
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); | |
12113 | } | |
12114 | mDNSPlatformMemFree(nta); | |
12115 | } | |
67c8f8a1 A |
12116 | |
12117 | mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question) | |
83fb1e36 | 12118 | { |
12c5fa7a | 12119 | CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname); |
f0cc3e7b | 12120 | CacheRecord *cr; |
83fb1e36 A |
12121 | DNSQuestion **qp = &m->Questions; |
12122 | ||
12123 | //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); | |
12124 | ||
9f221bca A |
12125 | if (LocalOnlyOrP2PInterface(question->InterfaceID)) |
12126 | qp = &m->LocalOnlyQuestions; | |
83fb1e36 A |
12127 | while (*qp && *qp != question) qp=&(*qp)->next; |
12128 | if (*qp) *qp = (*qp)->next; | |
12129 | else | |
12130 | { | |
96f69b28 | 12131 | #if !ForceAlerts |
83fb1e36 | 12132 | if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active |
96f69b28 | 12133 | #endif |
9f221bca | 12134 | LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype)); |
83fb1e36 A |
12135 | return(mStatus_BadReferenceErr); |
12136 | } | |
12137 | ||
f0cc3e7b | 12138 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca A |
12139 | if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID)) |
12140 | { | |
12141 | if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) | |
12142 | m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond)); | |
12143 | m->NumAllInterfaceQuestions--; | |
f0cc3e7b A |
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)); | |
9f221bca | 12147 | } |
f0cc3e7b | 12148 | #endif |
9f221bca | 12149 | |
f0cc3e7b | 12150 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
19fa75a9 | 12151 | if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.firstQueryTime != 0)) |
9f221bca | 12152 | { |
19fa75a9 A |
12153 | mDNSu32 querySendCount = question->metrics.querySendCount; |
12154 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
12155 | if (question->querier) | |
12156 | { | |
12157 | querySendCount += mdns_querier_get_send_count(question->querier); | |
12158 | } | |
12159 | #endif | |
12160 | if (querySendCount > 0) | |
12161 | { | |
12162 | const domainname * queryName; | |
12163 | mDNSBool isForCell; | |
12164 | mDNSu32 durationMs; | |
9f221bca | 12165 | |
19fa75a9 A |
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)); | |
12169 | #else | |
12170 | isForCell = (question->qDNSServer && question->qDNSServer->isCell); | |
12171 | #endif | |
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); | |
12175 | } | |
9f221bca A |
12176 | } |
12177 | #endif | |
83fb1e36 A |
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; | |
12182 | ||
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. | |
f0cc3e7b | 12185 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) |
83fb1e36 | 12186 | { |
f0cc3e7b | 12187 | if (cr->CRActiveQuestion == question) |
83fb1e36 A |
12188 | { |
12189 | DNSQuestion *q; | |
9f221bca A |
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) | |
12196 | { | |
f0cc3e7b | 12197 | if (!q->DuplicateOf && !q->Suppressed && CacheRecordAnswersQuestion(cr, q)) |
9f221bca A |
12198 | { |
12199 | if (q->ThisQInterval > 0) | |
12200 | { | |
12201 | replacement = q; | |
12202 | break; | |
12203 | } | |
12204 | else if (!replacement) | |
12205 | { | |
12206 | replacement = q; | |
12207 | } | |
12208 | } | |
12209 | } | |
12210 | if (replacement) | |
83fb1e36 | 12211 | debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question " |
f0cc3e7b A |
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 | |
9f221bca | 12214 | if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count |
83fb1e36 A |
12215 | } |
12216 | } | |
12217 | ||
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) | |
12221 | { | |
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; | |
12225 | } | |
12226 | ||
12227 | if (m->NewQuestions == question) | |
12228 | { | |
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; | |
12232 | } | |
12233 | ||
12234 | if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next; | |
12235 | ||
12236 | if (m->RestartQuestion == question) | |
12237 | { | |
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; | |
12241 | } | |
12242 | ||
83fb1e36 A |
12243 | // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions |
12244 | question->next = mDNSNULL; | |
12245 | ||
12246 | // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype)); | |
12247 | ||
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; } | |
19fa75a9 A |
12255 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
12256 | Querier_HandleStoppedDNSQuestion(question); | |
12257 | #endif | |
83fb1e36 A |
12258 | if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived) |
12259 | { | |
12260 | // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal. | |
12261 | DNSQuestion *q; | |
12262 | for (q = m->Questions; q; q=q->next) | |
12263 | if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break; | |
12264 | if (!q) | |
12265 | { | |
51601d48 A |
12266 | if (!m->LLQNAT.clientCallback) // Should never happen, but just in case... |
12267 | { | |
12268 | LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL"); | |
12269 | } | |
83fb1e36 A |
12270 | else |
12271 | { | |
12272 | LogInfo("Stopping LLQNAT"); | |
12273 | mDNS_StopNATOperation_internal(m, &m->LLQNAT); | |
51601d48 | 12274 | m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running |
83fb1e36 A |
12275 | } |
12276 | } | |
12277 | ||
12278 | // If necessary, tell server it can delete this LLQ state | |
12279 | if (question->state == LLQ_Established) | |
12280 | { | |
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. | |
12287 | if (question->tcp) | |
12288 | { | |
12289 | question->tcp->question = mDNSNULL; | |
12290 | question->tcp = mDNSNULL; | |
12291 | } | |
12292 | } | |
f0cc3e7b A |
12293 | #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) |
12294 | else if (question->dnsPushServer != mDNSNULL) | |
9f221bca | 12295 | { |
f0cc3e7b | 12296 | UnSubscribeToDNSPushNotificationServer(m, question); |
9f221bca | 12297 | } |
5e65c77f | 12298 | #endif |
83fb1e36 A |
12299 | } |
12300 | // wait until we send the refresh above which needs the nta | |
12301 | if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; } | |
67c8f8a1 | 12302 | |
f0cc3e7b | 12303 | #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) |
19fa75a9 | 12304 | uDNSMetricsClear(&question->metrics); |
9f221bca | 12305 | #endif |
51601d48 | 12306 | |
f0cc3e7b | 12307 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) |
12c5fa7a A |
12308 | DNS64ResetState(question); |
12309 | #endif | |
12310 | ||
83fb1e36 A |
12311 | return(mStatus_NoError); |
12312 | } | |
6528fe3e A |
12313 | |
12314 | mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question) | |
83fb1e36 A |
12315 | { |
12316 | mStatus status; | |
12317 | mDNS_Lock(m); | |
12318 | status = mDNS_StartQuery_internal(m, question); | |
12319 | mDNS_Unlock(m); | |
12320 | return(status); | |
12321 | } | |
c9b9ae52 A |
12322 | |
12323 | mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question) | |
83fb1e36 A |
12324 | { |
12325 | mStatus status; | |
12326 | mDNS_Lock(m); | |
12327 | status = mDNS_StopQuery_internal(m, question); | |
12328 | mDNS_Unlock(m); | |
12329 | return(status); | |
12330 | } | |
c9b9ae52 | 12331 | |
67c8f8a1 A |
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) | |
83fb1e36 A |
12337 | { |
12338 | mStatus status; | |
12339 | DNSQuestion *qq; | |
12340 | mDNS_Lock(m); | |
12341 | ||
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; | |
12344 | ||
12345 | status = mDNS_StopQuery_internal(m, question); | |
12346 | if (status == mStatus_NoError && !qq) | |
12347 | { | |
f0cc3e7b | 12348 | const CacheRecord *cr; |
12c5fa7a | 12349 | CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname); |
83fb1e36 | 12350 | LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); |
f0cc3e7b A |
12351 | for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) |
12352 | { | |
12353 | if (cr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameCacheRecordAnswersQuestion(cr, question)) | |
83fb1e36 A |
12354 | { |
12355 | // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls | |
12356 | if (question->QuestionCallback) | |
f0cc3e7b | 12357 | question->QuestionCallback(m, question, &cr->resrec, mDNSfalse); |
83fb1e36 | 12358 | } |
f0cc3e7b | 12359 | } |
83fb1e36 A |
12360 | } |
12361 | mDNS_Unlock(m); | |
12362 | return(status); | |
12363 | } | |
67c8f8a1 A |
12364 | |
12365 | mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr) | |
83fb1e36 A |
12366 | { |
12367 | mStatus status; | |
12368 | mDNS_Lock(m); | |
12369 | status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); | |
2682e09e | 12370 | if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0); |
83fb1e36 A |
12371 | mDNS_Unlock(m); |
12372 | return(status); | |
12373 | } | |
6528fe3e | 12374 | |
c9b9ae52 | 12375 | mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr) |
83fb1e36 A |
12376 | { |
12377 | mStatus status = mStatus_BadReferenceErr; | |
12378 | CacheRecord *cr; | |
12379 | mDNS_Lock(m); | |
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); | |
2682e09e | 12383 | if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0); |
83fb1e36 A |
12384 | mDNS_Unlock(m); |
12385 | return(status); | |
12386 | } | |
6528fe3e | 12387 | |
32bb7e43 | 12388 | mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question, |
83fb1e36 | 12389 | const domainname *const srv, const domainname *const domain, |
f0cc3e7b | 12390 | const mDNSInterfaceID InterfaceID, mDNSu32 flags, |
83fb1e36 A |
12391 | mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass, |
12392 | mDNSQuestionCallback *Callback, void *Context) | |
12393 | { | |
12394 | question->InterfaceID = InterfaceID; | |
12395 | question->flags = flags; | |
83fb1e36 A |
12396 | question->qtype = kDNSType_PTR; |
12397 | question->qclass = kDNSClass_IN; | |
12398 | question->LongLived = mDNStrue; | |
12399 | question->ExpectUnique = mDNSfalse; | |
12400 | question->ForceMCast = ForceMCast; | |
9f221bca | 12401 | question->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; |
83fb1e36 | 12402 | question->SuppressUnusable = mDNSfalse; |
f0cc3e7b | 12403 | question->AppendSearchDomains = mDNSfalse; |
83fb1e36 A |
12404 | question->TimeoutQuestion = 0; |
12405 | question->WakeOnResolve = 0; | |
f0cc3e7b | 12406 | question->UseBackgroundTraffic = useBackgroundTrafficClass; |
51601d48 | 12407 | question->ProxyQuestion = 0; |
83fb1e36 A |
12408 | question->QuestionCallback = Callback; |
12409 | question->QuestionContext = Context; | |
51601d48 A |
12410 | |
12411 | if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) | |
12412 | return(mStatus_BadParamErr); | |
12413 | ||
83fb1e36 A |
12414 | return(mDNS_StartQuery_internal(m, question)); |
12415 | } | |
32bb7e43 A |
12416 | |
12417 | mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question, | |
83fb1e36 | 12418 | const domainname *const srv, const domainname *const domain, |
f0cc3e7b | 12419 | const mDNSInterfaceID InterfaceID, mDNSu32 flags, |
83fb1e36 A |
12420 | mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass, |
12421 | mDNSQuestionCallback *Callback, void *Context) | |
12422 | { | |
12423 | mStatus status; | |
12424 | mDNS_Lock(m); | |
f0cc3e7b | 12425 | status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context); |
83fb1e36 A |
12426 | mDNS_Unlock(m); |
12427 | return(status); | |
12428 | } | |
7f0064bd | 12429 | |
6528fe3e | 12430 | |
8e92c31c | 12431 | mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom, |
83fb1e36 A |
12432 | const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context) |
12433 | { | |
12434 | question->InterfaceID = InterfaceID; | |
12435 | question->flags = 0; | |
83fb1e36 A |
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; | |
f0cc3e7b | 12443 | question->AppendSearchDomains = mDNSfalse; |
83fb1e36 A |
12444 | question->TimeoutQuestion = 0; |
12445 | question->WakeOnResolve = 0; | |
f0cc3e7b | 12446 | question->UseBackgroundTraffic = mDNSfalse; |
51601d48 | 12447 | question->ProxyQuestion = 0; |
51601d48 | 12448 | question->pid = mDNSPlatformGetPID(); |
9f221bca | 12449 | question->euid = 0; |
83fb1e36 A |
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)); | |
12457 | } | |
6528fe3e A |
12458 | |
12459 | // *************************************************************************** | |
c9b9ae52 | 12460 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e A |
12461 | #pragma mark - |
12462 | #pragma mark - Responder Functions | |
12463 | #endif | |
12464 | ||
c9b9ae52 | 12465 | mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr) |
83fb1e36 A |
12466 | { |
12467 | mStatus status; | |
12468 | mDNS_Lock(m); | |
12469 | status = mDNS_Register_internal(m, rr); | |
12470 | mDNS_Unlock(m); | |
12471 | return(status); | |
12472 | } | |
6528fe3e | 12473 | |
c9b9ae52 | 12474 | mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl, |
83fb1e36 A |
12475 | const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback) |
12476 | { | |
12477 | if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata)) | |
12478 | { | |
12479 | LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer)); | |
12480 | return(mStatus_Invalid); | |
12481 | } | |
12482 | ||
12483 | mDNS_Lock(m); | |
12484 | ||
12485 | // If TTL is unspecified, leave TTL unchanged | |
12486 | if (newttl == 0) newttl = rr->resrec.rroriginalttl; | |
12487 | ||
12488 | // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory | |
12489 | if (rr->NewRData) | |
12490 | { | |
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 | |
12495 | } | |
12496 | ||
12497 | rr->NewRData = newrdata; | |
12498 | rr->newrdlength = newrdlength; | |
12499 | rr->UpdateCallback = Callback; | |
7f0064bd | 12500 | |
263eeeab | 12501 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
12502 | if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name)) |
12503 | { | |
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; } | |
12507 | mDNS_Unlock(m); | |
12508 | return(status); | |
12509 | } | |
263eeeab | 12510 | #endif |
7f0064bd | 12511 | |
83fb1e36 A |
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); | |
12515 | else | |
12516 | { | |
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) | |
12524 | { | |
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" : ""); | |
12531 | } | |
12532 | rr->resrec.rroriginalttl = newttl; | |
12533 | } | |
12534 | ||
12535 | mDNS_Unlock(m); | |
12536 | return(mStatus_NoError); | |
12537 | } | |
6528fe3e | 12538 | |
32bb7e43 | 12539 | // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change |
6528fe3e A |
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. | |
c9b9ae52 | 12542 | mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr) |
83fb1e36 A |
12543 | { |
12544 | mStatus status; | |
12545 | mDNS_Lock(m); | |
12546 | status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); | |
12547 | mDNS_Unlock(m); | |
12548 | return(status); | |
12549 | } | |
c9b9ae52 | 12550 | |
67c8f8a1 A |
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); | |
f0cc3e7b A |
12553 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12554 | mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *m, AuthRecord *rr, mStatus result); | |
12555 | #endif | |
c9b9ae52 | 12556 | |
e9410223 A |
12557 | mDNSlocal AuthRecord *GetInterfaceAddressRecord(NetworkInterfaceInfo *intf, mDNSBool forRandHostname) |
12558 | { | |
12559 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
12560 | return(forRandHostname ? &intf->RR_AddrRand : &intf->RR_A); | |
12561 | #else | |
12562 | (void)forRandHostname; // Unused. | |
12563 | return(&intf->RR_A); | |
12564 | #endif | |
12565 | } | |
12566 | ||
12567 | mDNSlocal AuthRecord *GetFirstAddressRecordEx(const mDNS *const m, const mDNSBool forRandHostname) | |
83fb1e36 A |
12568 | { |
12569 | NetworkInterfaceInfo *intf; | |
12570 | for (intf = m->HostInterfaces; intf; intf = intf->next) | |
e9410223 A |
12571 | { |
12572 | if (!intf->Advertise) continue; | |
12573 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
12574 | if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue; | |
12575 | #endif | |
12576 | return(GetInterfaceAddressRecord(intf, forRandHostname)); | |
12577 | } | |
12578 | return(mDNSNULL); | |
83fb1e36 | 12579 | } |
e9410223 | 12580 | #define GetFirstAddressRecord(M) GetFirstAddressRecordEx(M, mDNSfalse) |
c9b9ae52 | 12581 | |
12c5fa7a A |
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.) | |
f0cc3e7b A |
12584 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12585 | mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool useRandomizedHostname) | |
12586 | #else | |
8e92c31c | 12587 | mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set) |
f0cc3e7b | 12588 | #endif |
83fb1e36 | 12589 | { |
f0cc3e7b A |
12590 | const domainname *hostname; |
12591 | mDNSRecordCallback *hostnameCallback; | |
12592 | AuthRecord *addrAR; | |
12593 | AuthRecord *ptrAR; | |
12594 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
12595 | const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID); | |
12596 | #endif | |
12597 | mDNSu8 addrRecordType; | |
12598 | char buffer[MAX_REVERSE_MAPPING_NAME]; | |
51601d48 | 12599 | |
f0cc3e7b A |
12600 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12601 | if (interfaceIsAWDL || useRandomizedHostname) | |
51601d48 | 12602 | { |
f0cc3e7b A |
12603 | hostname = &m->RandomizedHostname; |
12604 | hostnameCallback = mDNS_RandomizedHostNameCallback; | |
12605 | } | |
12606 | else | |
12607 | #endif | |
12608 | { | |
12609 | hostname = &m->MulticastHostname; | |
12610 | hostnameCallback = mDNS_HostNameCallback; | |
51601d48 | 12611 | } |
51601d48 | 12612 | |
f0cc3e7b A |
12613 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12614 | if (!interfaceIsAWDL && useRandomizedHostname) | |
12615 | { | |
12616 | addrAR = &set->RR_AddrRand; | |
12617 | ptrAR = mDNSNULL; | |
12618 | } | |
12619 | else | |
12620 | #endif | |
12621 | { | |
12622 | addrAR = &set->RR_A; | |
12623 | ptrAR = &set->RR_PTR; | |
12624 | } | |
12625 | if (addrAR->resrec.RecordType != kDNSRecordTypeUnregistered) return; | |
f9f18293 | 12626 | |
f0cc3e7b A |
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); | |
12633 | #else | |
12634 | LogInfo("AdvertiseInterface: Advertising for ifname %s", set->ifname); | |
12635 | #endif | |
f9f18293 | 12636 | |
83fb1e36 | 12637 | // Send dynamic update for non-linklocal IPv4 Addresses |
f0cc3e7b A |
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); | |
7f0064bd A |
12640 | |
12641 | #if ANSWER_REMOTE_HOSTNAME_QUERIES | |
f0cc3e7b A |
12642 | addrAR->AllowRemoteQuery = mDNStrue; |
12643 | if (ptrAR) ptrAR->AllowRemoteQuery = mDNStrue; | |
7f0064bd | 12644 | #endif |
83fb1e36 A |
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 | |
f0cc3e7b | 12647 | AssignDomainName(&addrAR->namestorage, hostname); |
83fb1e36 A |
12648 | if (set->ip.type == mDNSAddrType_IPv4) |
12649 | { | |
f0cc3e7b A |
12650 | addrAR->resrec.rrtype = kDNSType_A; |
12651 | addrAR->resrec.rdata->u.ipv4 = set->ip.ip.v4; | |
83fb1e36 A |
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]); | |
12655 | } | |
12656 | else if (set->ip.type == mDNSAddrType_IPv6) | |
12657 | { | |
12658 | int i; | |
f0cc3e7b A |
12659 | addrAR->resrec.rrtype = kDNSType_AAAA; |
12660 | addrAR->resrec.rdata->u.ipv6 = set->ip.ip.v6; | |
83fb1e36 A |
12661 | for (i = 0; i < 16; i++) |
12662 | { | |
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] = '.'; | |
12668 | } | |
12669 | mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa."); | |
12670 | } | |
12671 | ||
f0cc3e7b A |
12672 | if (ptrAR) |
12673 | { | |
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 | |
12677 | } | |
83fb1e36 | 12678 | |
f0cc3e7b | 12679 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
e9410223 A |
12680 | addrAR->RRSet = interfaceIsAWDL ? addrAR : GetFirstAddressRecordEx(m, useRandomizedHostname); |
12681 | #else | |
12682 | addrAR->RRSet = GetFirstAddressRecord(m); | |
f0cc3e7b | 12683 | #endif |
e9410223 | 12684 | if (!addrAR->RRSet) addrAR->RRSet = addrAR; |
f0cc3e7b | 12685 | mDNS_Register_internal(m, addrAR); |
e9410223 A |
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)); | |
f0cc3e7b | 12688 | if (ptrAR) mDNS_Register_internal(m, ptrAR); |
f9f18293 | 12689 | |
f0cc3e7b | 12690 | #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) |
f9f18293 | 12691 | // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc |
51601d48 | 12692 | D2D_start_advertising_interface(set); |
f0cc3e7b A |
12693 | #endif |
12694 | } | |
51601d48 | 12695 | |
f0cc3e7b A |
12696 | mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set) |
12697 | { | |
12698 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
12699 | if (mDNSPlatformInterfaceIsAWDL(set->InterfaceID)) | |
83fb1e36 | 12700 | { |
f0cc3e7b A |
12701 | if ((m->AutoTargetAWDLIncludedCount > 0) || (m->AutoTargetAWDLOnlyCount > 0)) |
12702 | { | |
12703 | AdvertiseInterface(m, set, mDNSfalse); | |
12704 | } | |
83fb1e36 A |
12705 | } |
12706 | else | |
12707 | { | |
f0cc3e7b A |
12708 | if (m->AutoTargetServices > 0) AdvertiseInterface(m, set, mDNSfalse); |
12709 | if (m->AutoTargetAWDLIncludedCount > 0) AdvertiseInterface(m, set, mDNStrue); | |
83fb1e36 | 12710 | } |
f0cc3e7b A |
12711 | #else |
12712 | if (m->AutoTargetServices > 0) AdvertiseInterface(m, set); | |
12713 | #endif | |
83fb1e36 | 12714 | } |
c9b9ae52 | 12715 | |
f0cc3e7b | 12716 | mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags) |
83fb1e36 | 12717 | { |
f0cc3e7b A |
12718 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12719 | const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID); | |
12720 | #endif | |
83fb1e36 A |
12721 | |
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(). | |
f0cc3e7b A |
12727 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12728 | if ((!interfaceIsAWDL && (flags & kDeadvertiseFlag_NormalHostname)) || | |
12729 | ( interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname))) | |
12730 | #else | |
12731 | if (flags & kDeadvertiseFlag_NormalHostname) | |
12732 | #endif | |
51601d48 | 12733 | { |
f0cc3e7b A |
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); | |
12739 | #endif | |
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); | |
51601d48 | 12742 | } |
f0cc3e7b A |
12743 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12744 | if (!interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname)) | |
51601d48 | 12745 | { |
f0cc3e7b A |
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); | |
51601d48 | 12750 | } |
f0cc3e7b | 12751 | #endif |
9f221bca A |
12752 | } |
12753 | ||
12754 | // Change target host name for record. | |
12755 | mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr) | |
12756 | { | |
f0cc3e7b A |
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); | |
9f221bca A |
12761 | #endif |
12762 | ||
12763 | SetTargetToHostName(m, rr); | |
12764 | ||
f0cc3e7b A |
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); | |
51601d48 | 12768 | #endif |
83fb1e36 | 12769 | } |
6528fe3e | 12770 | |
f0cc3e7b A |
12771 | mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m, DeadvertiseFlags flags) |
12772 | { | |
12773 | NetworkInterfaceInfo *intf; | |
12774 | for (intf = m->HostInterfaces; intf; intf = intf->next) | |
12775 | { | |
12776 | if (intf->Advertise) DeadvertiseInterface(m, intf, flags); | |
12777 | } | |
12778 | } | |
12779 | ||
7f0064bd | 12780 | mDNSexport void mDNS_SetFQDN(mDNS *const m) |
83fb1e36 A |
12781 | { |
12782 | domainname newmname; | |
83fb1e36 A |
12783 | AuthRecord *rr; |
12784 | newmname.c[0] = 0; | |
12785 | ||
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; } | |
12788 | ||
12789 | mDNS_Lock(m); | |
12790 | ||
12791 | if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged"); | |
12792 | else | |
12793 | { | |
12794 | AssignDomainName(&m->MulticastHostname, &newmname); | |
f0cc3e7b A |
12795 | DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_NormalHostname); |
12796 | AdvertiseNecessaryInterfaceRecords(m); | |
83fb1e36 A |
12797 | } |
12798 | ||
12799 | // 3. Make sure that any AutoTarget SRV records (and the like) get updated | |
9f221bca A |
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); | |
83fb1e36 A |
12802 | |
12803 | mDNS_Unlock(m); | |
12804 | } | |
c9b9ae52 | 12805 | |
67c8f8a1 | 12806 | mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result) |
83fb1e36 A |
12807 | { |
12808 | (void)rr; // Unused parameter | |
12809 | ||
12810 | #if MDNS_DEBUGMSGS | |
12811 | { | |
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); | |
12816 | } | |
12817 | #endif | |
12818 | ||
12819 | if (result == mStatus_NoError) | |
12820 | { | |
12821 | // Notify the client that the host name is successfully registered | |
12822 | if (m->MainCallback) | |
12823 | m->MainCallback(m, mStatus_NoError); | |
12824 | } | |
12825 | else if (result == mStatus_NameConflict) | |
12826 | { | |
12827 | domainlabel oldlabel = m->hostlabel; | |
12828 | ||
12829 | // 1. First give the client callback a chance to pick a new name | |
12830 | if (m->MainCallback) | |
12831 | m->MainCallback(m, mStatus_NameConflict); | |
12832 | ||
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); | |
12838 | ||
12839 | // 3. Generate the FQDNs from the hostlabel, | |
12840 | // and make sure all SRV records, etc., are updated to reference our new hostname | |
12841 | mDNS_SetFQDN(m); | |
12842 | LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c); | |
12843 | } | |
12844 | else if (result == mStatus_MemFree) | |
12845 | { | |
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)"); | |
12849 | } | |
12850 | else | |
12851 | LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c); | |
12852 | } | |
6528fe3e | 12853 | |
f0cc3e7b A |
12854 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
12855 | mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *const m, AuthRecord *const addrRecord, const mStatus result) | |
12856 | { | |
12857 | (void)addrRecord; // Unused parameter | |
12858 | ||
12859 | if (result == mStatus_NameConflict) | |
12860 | { | |
12861 | AuthRecord *rr; | |
12862 | domainlabel newUUIDLabel; | |
12863 | ||
12864 | GetRandomUUIDLabel(&newUUIDLabel); | |
12865 | if (SameDomainLabel(newUUIDLabel.c, m->RandomizedHostname.c)) | |
12866 | { | |
12867 | IncrementLabelSuffix(&newUUIDLabel, mDNSfalse); | |
12868 | } | |
12869 | ||
12870 | mDNS_Lock(m); | |
12871 | ||
12872 | m->RandomizedHostname.c[0] = 0; | |
12873 | AppendDomainLabel(&m->RandomizedHostname, &newUUIDLabel); | |
12874 | AppendLiteralLabelString(&m->RandomizedHostname, "local"); | |
12875 | ||
12876 | DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_RandHostname); | |
12877 | AdvertiseNecessaryInterfaceRecords(m); | |
12878 | for (rr = m->ResourceRecords; rr; rr = rr->next) | |
12879 | { | |
12880 | if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr); | |
12881 | } | |
12882 | for (rr = m->DuplicateRecords; rr; rr = rr->next) | |
12883 | { | |
12884 | if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr); | |
12885 | } | |
12886 | ||
12887 | mDNS_Unlock(m); | |
12888 | } | |
12889 | } | |
12890 | #endif | |
12891 | ||
c9b9ae52 | 12892 | mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active) |
83fb1e36 A |
12893 | { |
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) | |
12899 | { | |
12900 | if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue; | |
12901 | if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue; | |
12902 | } | |
12903 | } | |
6528fe3e | 12904 | |
32bb7e43 | 12905 | mDNSlocal void RestartRecordGetZoneData(mDNS * const m) |
83fb1e36 A |
12906 | { |
12907 | AuthRecord *rr; | |
12908 | LogInfo("RestartRecordGetZoneData: ResourceRecords"); | |
12909 | for (rr = m->ResourceRecords; rr; rr=rr->next) | |
12910 | if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget) | |
12911 | { | |
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); | |
12917 | } | |
12918 | } | |
32bb7e43 A |
12919 | |
12920 | mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set) | |
83fb1e36 A |
12921 | { |
12922 | int i; | |
51601d48 A |
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. | |
9f221bca | 12928 | |
83fb1e36 A |
12929 | set->NetWakeBrowse.ThisQInterval = -1; |
12930 | for (i=0; i<3; i++) | |
12931 | { | |
12932 | set->NetWakeResolve[i].ThisQInterval = -1; | |
12933 | set->SPSAddr[i].type = mDNSAddrType_None; | |
12934 | } | |
12935 | set->NextSPSAttempt = -1; | |
12936 | set->NextSPSAttemptTime = m->timenow; | |
12937 | } | |
32bb7e43 A |
12938 | |
12939 | mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set) | |
83fb1e36 A |
12940 | { |
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; } | |
12944 | ||
12945 | if (set->InterfaceActive) | |
12946 | { | |
12947 | LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip); | |
f0cc3e7b | 12948 | mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set); |
83fb1e36 A |
12949 | } |
12950 | } | |
32bb7e43 A |
12951 | |
12952 | mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set) | |
83fb1e36 A |
12953 | { |
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; } | |
12957 | ||
51601d48 A |
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. | |
83fb1e36 A |
12962 | if (set->NetWakeBrowse.ThisQInterval >= 0) |
12963 | { | |
12964 | int i; | |
12965 | LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip); | |
12966 | ||
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]); | |
12970 | ||
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) | |
12973 | { | |
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 | |
12977 | } | |
12978 | ||
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); | |
12982 | } | |
12983 | } | |
32bb7e43 | 12984 | |
12c5fa7a | 12985 | mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed) |
83fb1e36 A |
12986 | { |
12987 | AuthRecord *rr; | |
12988 | mDNSBool FirstOfType = mDNStrue; | |
12989 | NetworkInterfaceInfo **p = &m->HostInterfaces; | |
12990 | ||
12991 | if (!set->InterfaceID) | |
19fa75a9 A |
12992 | { |
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); | |
12996 | } | |
83fb1e36 A |
12997 | |
12998 | if (!mDNSAddressIsValidNonZero(&set->mask)) | |
19fa75a9 A |
12999 | { |
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); | |
13004 | } | |
83fb1e36 A |
13005 | |
13006 | mDNS_Lock(m); | |
13007 | ||
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); | |
13012 | ||
13013 | InitializeNetWakeState(m, set); | |
13014 | ||
13015 | // Scan list to see if this InterfaceID is already represented | |
13016 | while (*p) | |
13017 | { | |
13018 | if (*p == set) | |
13019 | { | |
19fa75a9 A |
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); | |
83fb1e36 A |
13023 | mDNS_Unlock(m); |
13024 | return(mStatus_AlreadyRegistered); | |
13025 | } | |
13026 | ||
13027 | if ((*p)->InterfaceID == set->InterfaceID) | |
13028 | { | |
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; | |
13034 | } | |
13035 | ||
13036 | p=&(*p)->next; | |
13037 | } | |
13038 | ||
13039 | set->next = mDNSNULL; | |
13040 | *p = set; | |
13041 | ||
f0cc3e7b | 13042 | if (set->Advertise) AdvertiseInterfaceIfNeeded(m, set); |
83fb1e36 | 13043 | |
19fa75a9 A |
13044 | if (set->InterfaceActive) |
13045 | { | |
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); | |
13049 | } | |
13050 | else | |
13051 | { | |
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); | |
13055 | } | |
83fb1e36 A |
13056 | |
13057 | if (set->NetWake) mDNS_ActivateNetWake_internal(m, set); | |
13058 | ||
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)) | |
13064 | { | |
13065 | DNSQuestion *q; | |
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. | |
12c5fa7a A |
13073 | mDNSs32 probedelay; |
13074 | mDNSu8 numannounce; | |
13075 | switch (activationSpeed) | |
13076 | { | |
13077 | case FastActivation: | |
13078 | probedelay = (mDNSs32)0; | |
13079 | numannounce = InitialAnnounceCount; | |
19fa75a9 A |
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); | |
12c5fa7a | 13083 | break; |
83fb1e36 | 13084 | |
f0cc3e7b | 13085 | #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) |
12c5fa7a A |
13086 | case SlowActivation: |
13087 | probedelay = mDNSPlatformOneSecond * 5; | |
13088 | numannounce = (mDNSu8)1; | |
19fa75a9 A |
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); | |
12c5fa7a A |
13092 | m->mDNSStats.InterfaceUpFlap++; |
13093 | break; | |
f0cc3e7b | 13094 | #endif |
83fb1e36 | 13095 | |
12c5fa7a A |
13096 | case NormalActivation: |
13097 | default: | |
13098 | probedelay = mDNSPlatformOneSecond / 2; | |
13099 | numannounce = InitialAnnounceCount; | |
13100 | break; | |
51601d48 | 13101 | } |
83fb1e36 | 13102 | |
19fa75a9 A |
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); | |
9f221bca | 13106 | |
12c5fa7a A |
13107 | // No probe or sending suppression on DirectLink type interfaces. |
13108 | if (activationSpeed == FastActivation) | |
13109 | { | |
13110 | m->SuppressSending = 0; | |
13111 | m->SuppressProbes = 0; | |
13112 | } | |
13113 | else | |
13114 | { | |
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); | |
13126 | ||
13127 | if (m->SuppressProbes == 0 || | |
13128 | m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0) | |
13129 | m->SuppressProbes = NonZeroTime(m->timenow + probedelay); | |
13130 | } | |
83fb1e36 A |
13131 | |
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); | |
19fa75a9 | 13137 | LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Setting AnnounceOwner"); |
83fb1e36 | 13138 | |
51601d48 | 13139 | m->mDNSStats.InterfaceUp++; |
83fb1e36 | 13140 | for (q = m->Questions; q; q=q->next) // Scan our list of questions |
51601d48 | 13141 | { |
83fb1e36 | 13142 | if (mDNSOpaque16IsZero(q->TargetQID)) |
51601d48 | 13143 | { |
83fb1e36 A |
13144 | if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface, |
13145 | { // then reactivate this question | |
f0cc3e7b | 13146 | #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) |
83fb1e36 | 13147 | // If flapping, delay between first and second queries is nine seconds instead of one second |
12c5fa7a | 13148 | mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID); |
83fb1e36 | 13149 | mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval; |
12c5fa7a | 13150 | mDNSs32 qdelay = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0; |
19fa75a9 A |
13151 | if (dodelay) |
13152 | { | |
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); | |
13156 | } | |
f0cc3e7b A |
13157 | #else |
13158 | mDNSs32 initial = InitialQuestionInterval; | |
13159 | mDNSs32 qdelay = 0; | |
13160 | #endif | |
83fb1e36 A |
13161 | |
13162 | if (!q->ThisQInterval || q->ThisQInterval > initial) | |
13163 | { | |
9f221bca A |
13164 | q->ThisQInterval = initial; |
13165 | q->RequestUnicast = kDefaultRequestUnicastCount; | |
83fb1e36 A |
13166 | } |
13167 | q->LastQTime = m->timenow - q->ThisQInterval + qdelay; | |
13168 | q->RecentAnswerPkts = 0; | |
13169 | SetNextQueryTime(m,q); | |
13170 | } | |
51601d48 A |
13171 | } |
13172 | } | |
83fb1e36 A |
13173 | |
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) | |
51601d48 | 13177 | { |
83fb1e36 | 13178 | if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID) |
51601d48 | 13179 | { |
51601d48 A |
13180 | mDNSCoreRestartRegistration(m, rr, numannounce); |
13181 | } | |
13182 | } | |
83fb1e36 A |
13183 | } |
13184 | ||
13185 | RestartRecordGetZoneData(m); | |
13186 | ||
83fb1e36 A |
13187 | mDNS_UpdateAllowSleep(m); |
13188 | ||
13189 | mDNS_Unlock(m); | |
13190 | return(mStatus_NoError); | |
13191 | } | |
6528fe3e | 13192 | |
e9410223 A |
13193 | mDNSlocal void AdjustAddressRecordSetsEx(mDNS *const m, NetworkInterfaceInfo *removedIntf, mDNSBool forRandHostname) |
13194 | { | |
13195 | NetworkInterfaceInfo *intf; | |
13196 | const AuthRecord *oldAR; | |
13197 | AuthRecord *newAR; | |
13198 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
13199 | if (mDNSPlatformInterfaceIsAWDL(removedIntf->InterfaceID)) return; | |
13200 | #endif | |
13201 | oldAR = GetInterfaceAddressRecord(removedIntf, forRandHostname); | |
13202 | newAR = GetFirstAddressRecordEx(m, forRandHostname); | |
13203 | for (intf = m->HostInterfaces; intf; intf = intf->next) | |
13204 | { | |
13205 | AuthRecord *ar; | |
13206 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
13207 | if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue; | |
13208 | #endif | |
13209 | ar = GetInterfaceAddressRecord(intf, forRandHostname); | |
13210 | if (ar->RRSet == oldAR) | |
13211 | { | |
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)); | |
13215 | } | |
13216 | } | |
13217 | } | |
13218 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) | |
13219 | #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue) | |
13220 | #endif | |
13221 | #define AdjustAddressRecordSets(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse) | |
13222 | ||
32bb7e43 | 13223 | // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change |
6528fe3e A |
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. | |
12c5fa7a | 13226 | mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed) |
83fb1e36 | 13227 | { |
f0cc3e7b A |
13228 | #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) |
13229 | (void)activationSpeed; // Unused parameter | |
13230 | #endif | |
83fb1e36 A |
13231 | NetworkInterfaceInfo **p = &m->HostInterfaces; |
13232 | mDNSBool revalidate = mDNSfalse; | |
9f221bca | 13233 | NetworkInterfaceInfo *intf; |
83fb1e36 A |
13234 | |
13235 | mDNS_Lock(m); | |
13236 | ||
13237 | // Find this record in our list | |
13238 | while (*p && *p != set) p=&(*p)->next; | |
19fa75a9 A |
13239 | if (!*p) |
13240 | { | |
13241 | LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "NetworkInterfaceInfo not found in list"); | |
13242 | mDNS_Unlock(m); | |
13243 | return; | |
13244 | } | |
83fb1e36 A |
13245 | |
13246 | mDNS_DeactivateNetWake_internal(m, set); | |
13247 | ||
13248 | // Unlink this record from our list | |
13249 | *p = (*p)->next; | |
13250 | set->next = mDNSNULL; | |
13251 | ||
13252 | if (!set->InterfaceActive) | |
13253 | { | |
13254 | // If this interface not the active member of its set, update the v4/v6Available flags for the active member | |
83fb1e36 A |
13255 | for (intf = m->HostInterfaces; intf; intf = intf->next) |
13256 | if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID) | |
13257 | UpdateInterfaceProtocols(m, intf); | |
13258 | } | |
13259 | else | |
13260 | { | |
9f221bca | 13261 | intf = FirstInterfaceForID(m, set->InterfaceID); |
83fb1e36 A |
13262 | if (intf) |
13263 | { | |
19fa75a9 A |
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); | |
83fb1e36 | 13267 | if (intf->InterfaceActive) |
19fa75a9 A |
13268 | { |
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); | |
13272 | } | |
83fb1e36 A |
13273 | intf->InterfaceActive = mDNStrue; |
13274 | UpdateInterfaceProtocols(m, intf); | |
13275 | ||
13276 | if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf); | |
13277 | ||
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) | |
13282 | break; | |
13283 | if (!intf) revalidate = mDNStrue; | |
13284 | } | |
13285 | else | |
13286 | { | |
13287 | mDNSu32 slot; | |
13288 | CacheGroup *cg; | |
13289 | CacheRecord *rr; | |
13290 | DNSQuestion *q; | |
19fa75a9 A |
13291 | #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) |
13292 | mDNSu32 cacheHitMulticastCount = 0; | |
13293 | mDNSu32 cacheMissMulticastCount = 0; | |
13294 | mDNSu32 cacheHitUnicastCount = 0; | |
13295 | mDNSu32 cacheMissUnicastCount = 0; | |
13296 | #endif | |
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); | |
83fb1e36 | 13301 | |
51601d48 | 13302 | m->mDNSStats.InterfaceDown++; |
f0cc3e7b A |
13303 | |
13304 | #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) | |
12c5fa7a | 13305 | if (set->McastTxRx && (activationSpeed == SlowActivation)) |
51601d48 | 13306 | { |
19fa75a9 A |
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); | |
51601d48 A |
13310 | m->mDNSStats.InterfaceDownFlap++; |
13311 | } | |
f0cc3e7b | 13312 | #endif |
83fb1e36 A |
13313 | |
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) | |
13317 | { | |
672757b6 | 13318 | if (mDNSOpaque16IsZero(q->TargetQID)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.) |
83fb1e36 | 13319 | { |
672757b6 A |
13320 | if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0; |
13321 | if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) | |
13322 | { | |
13323 | q->FlappingInterface2 = q->FlappingInterface1; | |
13324 | q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away | |
13325 | } | |
83fb1e36 A |
13326 | } |
13327 | } | |
13328 | ||
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) | |
13332 | { | |
13333 | if (rr->resrec.InterfaceID == set->InterfaceID) | |
13334 | { | |
f0cc3e7b | 13335 | #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) |
83fb1e36 A |
13336 | // If this interface is deemed flapping, |
13337 | // postpone deleting the cache records in case the interface comes back again | |
12c5fa7a | 13338 | if (set->McastTxRx && (activationSpeed == SlowActivation)) |
83fb1e36 | 13339 | { |
12c5fa7a A |
13340 | // For a flapping interface we want these records to go away after |
13341 | // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed. | |
83fb1e36 A |
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; | |
13346 | } | |
13347 | else | |
f0cc3e7b | 13348 | #endif |
83fb1e36 | 13349 | { |
19fa75a9 A |
13350 | #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) |
13351 | if (rr->LastCachedAnswerTime) | |
13352 | { | |
13353 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
13354 | if (rr->resrec.dnsservice) cacheHitUnicastCount++; | |
13355 | #else | |
13356 | if (rr->resrec.rDNSServer) cacheHitUnicastCount++; | |
13357 | #endif | |
13358 | else cacheHitMulticastCount++; | |
13359 | } | |
13360 | else | |
13361 | { | |
13362 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) | |
13363 | if (rr->resrec.dnsservice) cacheMissUnicastCount++; | |
13364 | #else | |
13365 | if (rr->resrec.rDNSServer) cacheMissUnicastCount++; | |
13366 | #endif | |
13367 | else cacheMissMulticastCount++; | |
13368 | } | |
13369 | #endif | |
83fb1e36 A |
13370 | mDNS_PurgeCacheResourceRecord(m, rr); |
13371 | } | |
13372 | } | |
13373 | } | |
19fa75a9 A |
13374 | #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) |
13375 | dnssd_analytics_update_cache_usage_counts(cacheHitMulticastCount, cacheMissMulticastCount, cacheHitUnicastCount, cacheMissUnicastCount); | |
13376 | #endif | |
83fb1e36 A |
13377 | } |
13378 | } | |
13379 | ||
9f221bca A |
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, | |
e9410223 A |
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); | |
13386 | #endif | |
9f221bca | 13387 | |
83fb1e36 | 13388 | // If we were advertising on this interface, deregister those address and reverse-lookup records now |
f0cc3e7b | 13389 | if (set->Advertise) DeadvertiseInterface(m, set, kDeadvertiseFlag_All); |
83fb1e36 A |
13390 | |
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) | |
13396 | { | |
13397 | mDNSu32 slot; | |
13398 | CacheGroup *cg; | |
13399 | CacheRecord *rr; | |
13400 | FORALL_CACHERECORDS(slot, cg, rr) | |
13401 | if (rr->resrec.InterfaceID == set->InterfaceID) | |
13402 | mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface); | |
13403 | } | |
13404 | ||
83fb1e36 A |
13405 | mDNS_UpdateAllowSleep(m); |
13406 | ||
13407 | mDNS_Unlock(m); | |
13408 | } | |
6528fe3e | 13409 | |
c9b9ae52 | 13410 | mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result) |
83fb1e36 A |
13411 | { |
13412 | ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext; | |
13413 | (void)m; // Unused parameter | |
13414 | ||
13415 | #if MDNS_DEBUGMSGS | |
13416 | { | |
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); | |
13422 | } | |
13423 | #endif | |
13424 | ||
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; | |
13427 | ||
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) | |
13430 | { | |
13431 | sr->Conflict = mDNStrue; // Record that this service set had a conflict | |
13432 | mDNS_DeregisterService(m, sr); // Unlink the records from our list | |
13433 | return; | |
13434 | } | |
13435 | ||
13436 | if (result == mStatus_MemFree) | |
13437 | { | |
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. | |
13441 | mDNSu32 i; | |
13442 | ExtraResourceRecord *e = sr->Extras; | |
13443 | ||
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; | |
13449 | ||
13450 | while (e) | |
13451 | { | |
13452 | if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return; | |
13453 | e = e->next; | |
13454 | } | |
13455 | ||
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; | |
13459 | ||
13460 | } | |
13461 | ||
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); | |
13467 | } | |
6528fe3e | 13468 | |
7f0064bd | 13469 | mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result) |
83fb1e36 A |
13470 | { |
13471 | ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext; | |
13472 | if (sr->ServiceCallback) | |
13473 | sr->ServiceCallback(m, sr, result); | |
13474 | } | |
13475 | ||
13476 | ||
12c5fa7a | 13477 | // Derive AuthRecType from the kDNSServiceFlags* values. |
83fb1e36 A |
13478 | mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags) |
13479 | { | |
13480 | AuthRecType artype; | |
13481 | ||
13482 | if (InterfaceID == mDNSInterface_LocalOnly) | |
13483 | artype = AuthRecordLocalOnly; | |
9f221bca | 13484 | else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE) |
83fb1e36 | 13485 | artype = AuthRecordP2P; |
12c5fa7a A |
13486 | else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P) |
13487 | && (flags & kDNSServiceFlagsIncludeAWDL)) | |
51601d48 | 13488 | artype = AuthRecordAnyIncludeAWDLandP2P; |
12c5fa7a | 13489 | else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)) |
83fb1e36 | 13490 | artype = AuthRecordAnyIncludeP2P; |
12c5fa7a | 13491 | else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL)) |
83fb1e36 A |
13492 | artype = AuthRecordAnyIncludeAWDL; |
13493 | else | |
13494 | artype = AuthRecordAny; | |
13495 | ||
13496 | return artype; | |
13497 | } | |
7f0064bd | 13498 | |
6528fe3e A |
13499 | // Note: |
13500 | // Name is first label of domain name (any dots in the name are actual dots, not label separators) | |
8e92c31c | 13501 | // Type is service type (e.g. "_ipp._tcp.") |
6528fe3e A |
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.) | |
c9b9ae52 | 13505 | // If the host parameter is mDNSNULL or the root domain (ASCII NUL), |
7f0064bd | 13506 | // then the default host name (m->MulticastHostname) is automatically used |
67c8f8a1 | 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 |
6528fe3e | 13508 | mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr, |
83fb1e36 | 13509 | const domainlabel *const name, const domainname *const type, const domainname *const domain, |
2682e09e | 13510 | const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen, |
83fb1e36 A |
13511 | AuthRecord *SubTypes, mDNSu32 NumSubTypes, |
13512 | mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags) | |
13513 | { | |
13514 | mStatus err; | |
13515 | mDNSu32 i; | |
83fb1e36 | 13516 | AuthRecType artype; |
12c5fa7a | 13517 | mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique; |
83fb1e36 A |
13518 | |
13519 | sr->ServiceCallback = Callback; | |
13520 | sr->ServiceContext = Context; | |
13521 | sr->Conflict = mDNSfalse; | |
13522 | ||
13523 | sr->Extras = mDNSNULL; | |
13524 | sr->NumSubTypes = NumSubTypes; | |
13525 | sr->SubTypes = SubTypes; | |
51601d48 | 13526 | sr->flags = flags; |
83fb1e36 A |
13527 | |
13528 | artype = setAuthRecType(InterfaceID, flags); | |
13529 | ||
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); | |
13534 | ||
12c5fa7a | 13535 | if (flags & kDNSServiceFlagsWakeOnlyService) |
51601d48 A |
13536 | { |
13537 | sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly; | |
13538 | } | |
13539 | ||
f0cc3e7b | 13540 | mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, recordType, artype, ServiceCallback, sr); |
2682e09e | 13541 | mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr); |
83fb1e36 A |
13542 | |
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)); | |
13546 | ||
9f221bca A |
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 | |
83fb1e36 A |
13549 | if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen) |
13550 | sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen; | |
13551 | ||
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); | |
13560 | ||
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); | |
13563 | ||
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; | |
13570 | ||
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++) | |
13575 | { | |
13576 | domainname st; | |
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; | |
13585 | } | |
9f221bca | 13586 | |
83fb1e36 A |
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; | |
13591 | ||
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'; } | |
13595 | ||
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) | |
13601 | { | |
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); | |
13605 | } | |
13606 | sr->RR_TXT.DependentOn = &sr->RR_SRV; | |
13607 | ||
13608 | mDNS_Lock(m); | |
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 | |
13616 | if (err) | |
13617 | { | |
13618 | mDNS_Unlock(m); | |
13619 | return err; | |
13620 | } | |
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); | |
13630 | ||
13631 | mDNS_Unlock(m); | |
13632 | ||
13633 | if (err) mDNS_DeregisterService(m, sr); | |
13634 | return(err); | |
13635 | } | |
6528fe3e | 13636 | |
c9b9ae52 | 13637 | mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, |
83fb1e36 A |
13638 | ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags) |
13639 | { | |
13640 | ExtraResourceRecord **e; | |
13641 | mStatus status; | |
13642 | AuthRecType artype; | |
13643 | mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID; | |
9f221bca | 13644 | ResourceRecord *rr; |
83fb1e36 A |
13645 | |
13646 | artype = setAuthRecType(InterfaceID, flags); | |
13647 | ||
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); | |
13652 | ||
13653 | mDNS_Lock(m); | |
9f221bca A |
13654 | rr = mDNSNULL; |
13655 | if (extra->r.resrec.rrtype == kDNSType_TXT) | |
13656 | { | |
13657 | if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec; | |
13658 | } | |
13659 | else if (extra->r.resrec.rrtype == kDNSType_SRV) | |
13660 | { | |
13661 | if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec; | |
13662 | } | |
13663 | ||
13664 | if (!rr) | |
13665 | { | |
13666 | ExtraResourceRecord *srExtra; | |
13667 | ||
13668 | for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next) | |
13669 | { | |
13670 | if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask)) | |
13671 | { | |
13672 | rr = &srExtra->r.resrec; | |
13673 | break; | |
13674 | } | |
13675 | } | |
13676 | } | |
13677 | ||
13678 | if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl)) | |
13679 | { | |
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; | |
13683 | } | |
13684 | ||
83fb1e36 A |
13685 | e = &sr->Extras; |
13686 | while (*e) e = &(*e)->next; | |
13687 | ||
83fb1e36 A |
13688 | extra->r.DependentOn = &sr->RR_SRV; |
13689 | ||
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); | |
13692 | ||
13693 | status = mDNS_Register_internal(m, &extra->r); | |
13694 | if (status == mStatus_NoError) *e = extra; | |
13695 | ||
13696 | mDNS_Unlock(m); | |
13697 | return(status); | |
13698 | } | |
6528fe3e | 13699 | |
67c8f8a1 | 13700 | mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, |
83fb1e36 A |
13701 | mDNSRecordCallback MemFreeCallback, void *Context) |
13702 | { | |
13703 | ExtraResourceRecord **e; | |
13704 | mStatus status; | |
13705 | ||
13706 | mDNS_Lock(m); | |
13707 | e = &sr->Extras; | |
13708 | while (*e && *e != extra) e = &(*e)->next; | |
13709 | if (!*e) | |
13710 | { | |
13711 | debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c); | |
13712 | status = mStatus_BadReferenceErr; | |
13713 | } | |
13714 | else | |
13715 | { | |
13716 | debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c); | |
13717 | extra->r.RecordCallback = MemFreeCallback; | |
13718 | extra->r.RecordContext = Context; | |
13719 | *e = (*e)->next; | |
13720 | status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal); | |
13721 | } | |
13722 | mDNS_Unlock(m); | |
13723 | return(status); | |
13724 | } | |
6528fe3e | 13725 | |
377735b0 | 13726 | mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname) |
83fb1e36 A |
13727 | { |
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; | |
13734 | mStatus err; | |
13735 | ||
13736 | DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain); | |
13737 | if (!newname) | |
13738 | { | |
13739 | name2 = name1; | |
13740 | IncrementLabelSuffix(&name2, mDNStrue); | |
13741 | newname = &name2; | |
13742 | } | |
13743 | ||
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); | |
13747 | ||
f0cc3e7b A |
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); | |
83fb1e36 | 13751 | err = mDNS_RegisterService(m, sr, newname, &type, &domain, |
2682e09e A |
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, | |
83fb1e36 | 13755 | sr->SubTypes, sr->NumSubTypes, |
51601d48 | 13756 | sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags); |
83fb1e36 A |
13757 | |
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) | |
13762 | { | |
13763 | ExtraResourceRecord *e = extras; | |
13764 | extras = extras->next; | |
13765 | err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0); | |
13766 | } | |
13767 | ||
13768 | return(err); | |
13769 | } | |
6528fe3e | 13770 | |
32bb7e43 | 13771 | // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback, |
6528fe3e | 13772 | // which may change the record list and/or question list. |
263eeeab A |
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) | |
83fb1e36 A |
13775 | { |
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)); | |
13778 | ||
13779 | if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered) | |
13780 | { | |
13781 | debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c); | |
13782 | return(mStatus_BadReferenceErr); | |
13783 | } | |
13784 | else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering) | |
13785 | { | |
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); | |
13800 | } | |
13801 | else | |
13802 | { | |
13803 | mDNSu32 i; | |
13804 | mStatus status; | |
13805 | ExtraResourceRecord *e; | |
13806 | mDNS_Lock(m); | |
13807 | e = sr->Extras; | |
13808 | ||
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); | |
83fb1e36 A |
13813 | mDNS_Deregister_internal(m, &sr->RR_ADV, drt); |
13814 | ||
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 | |
13817 | while (e) | |
13818 | { | |
13819 | mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat); | |
13820 | e = e->next; | |
13821 | } | |
13822 | ||
13823 | for (i=0; i<sr->NumSubTypes; i++) | |
13824 | mDNS_Deregister_internal(m, &sr->SubTypes[i], drt); | |
13825 | ||
13826 | status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt); | |
13827 | mDNS_Unlock(m); | |
13828 | return(status); | |
13829 | } | |
13830 | } | |
c9b9ae52 A |
13831 | |
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, | |
83fb1e36 A |
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) | |
13842 | { | |
13843 | AuthRecType artype; | |
13844 | ||
13845 | artype = setAuthRecType(InterfaceID, flags); | |
13846 | ||
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)); | |
13855 | } | |
6528fe3e | 13856 | |
c9b9ae52 | 13857 | mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr, |
83fb1e36 A |
13858 | mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname) |
13859 | { | |
13860 | AuthRecType artype; | |
13861 | ||
13862 | if (InterfaceID == mDNSInterface_LocalOnly) | |
13863 | artype = AuthRecordLocalOnly; | |
9f221bca | 13864 | else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE) |
83fb1e36 A |
13865 | artype = AuthRecordP2P; |
13866 | else | |
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)); | |
13872 | } | |
13873 | ||
263eeeab | 13874 | mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id) |
83fb1e36 A |
13875 | { |
13876 | AuthRecord *r; | |
13877 | for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue; | |
13878 | return mDNSfalse; | |
13879 | } | |
13880 | ||
263eeeab | 13881 | mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id) |
83fb1e36 A |
13882 | { |
13883 | DNSQuestion *q; | |
13884 | for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue; | |
13885 | return mDNSfalse; | |
13886 | } | |
13887 | ||
9f29194f | 13888 | mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m) |
83fb1e36 A |
13889 | { |
13890 | mDNSOpaque16 id; | |
13891 | int i; | |
263eeeab | 13892 | |
83fb1e36 A |
13893 | for (i=0; i<10; i++) |
13894 | { | |
13895 | id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE)); | |
13896 | if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break; | |
13897 | } | |
13898 | ||
13899 | debugf("mDNS_NewMessageID: %5d", mDNSVal16(id)); | |
263eeeab | 13900 | |
83fb1e36 A |
13901 | return id; |
13902 | } | |
6528fe3e | 13903 | |
32bb7e43 A |
13904 | // *************************************************************************** |
13905 | #if COMPILER_LIKES_PRAGMA_MARK | |
13906 | #pragma mark - | |
13907 | #pragma mark - Sleep Proxy Server | |
13908 | #endif | |
13909 | ||
ca3eca6b | 13910 | mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr) |
83fb1e36 A |
13911 | { |
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. | |
13921 | ||
13922 | rr->resrec.RecordType = kDNSRecordTypeUnique; | |
13923 | rr->ProbeCount = DefaultProbeCountForTypeUnique; | |
51601d48 | 13924 | rr->ProbeRestartCount++; |
83fb1e36 A |
13925 | |
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); | |
13934 | else | |
13935 | { | |
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); | |
13940 | } | |
13941 | } | |
32bb7e43 | 13942 | |
263eeeab | 13943 | mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID) |
83fb1e36 A |
13944 | { |
13945 | static const mDNSOpaque16 ARP_op_request = { { 0, 1 } }; | |
13946 | AuthRecord *rr; | |
13947 | NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); | |
13948 | if (!intf) return; | |
13949 | ||
13950 | mDNS_Lock(m); | |
13951 | ||
13952 | // Pass 1: | |
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)) | |
13961 | { | |
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)) | |
13965 | { | |
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; | |
5a93c909 A |
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)); | |
51601d48 A |
13976 | if (msg == msg1) |
13977 | { | |
13978 | if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS) | |
13979 | RestartARPProbing(m, rr); | |
13980 | else | |
13981 | LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr)); | |
13982 | } | |
13983 | else if (msg == msg3) | |
13984 | { | |
12c5fa7a | 13985 | mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID); |
51601d48 A |
13986 | } |
13987 | else if (msg == msg4) | |
13988 | { | |
5a93c909 | 13989 | SendARP(m, 2, rr, (mDNSv4Addr *)arp->tpa.b, &arp->sha, (mDNSv4Addr *)arp->spa.b, &arp->sha); |
51601d48 | 13990 | } |
83fb1e36 A |
13991 | } |
13992 | } | |
13993 | ||
13994 | // Pass 2: | |
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)) | |
5a93c909 | 14003 | debugf("ARP from self for %.4a", arp->tpa.b); |
83fb1e36 A |
14004 | else |
14005 | { | |
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 && | |
51601d48 | 14009 | rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)) |
83fb1e36 | 14010 | { |
51601d48 A |
14011 | if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC)) |
14012 | { | |
5a93c909 A |
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)); | |
51601d48 | 14015 | } |
83fb1e36 A |
14016 | else |
14017 | { | |
51601d48 A |
14018 | RestartARPProbing(m, rr); |
14019 | if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC)) | |
14020 | { | |
5a93c909 | 14021 | LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname, |
51601d48 | 14022 | mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ", |
5a93c909 | 14023 | arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr)); |
51601d48 A |
14024 | } |
14025 | else | |
14026 | { | |
14027 | LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname, | |
5a93c909 | 14028 | arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); |
51601d48 A |
14029 | ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC); |
14030 | } | |
83fb1e36 A |
14031 | } |
14032 | } | |
14033 | } | |
14034 | ||
14035 | mDNS_Unlock(m); | |
14036 | } | |
263eeeab A |
14037 | |
14038 | /* | |
83fb1e36 A |
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) | |
14042 | { | |
14043 | const mDNSu8 *options = (mDNSu8 *)(ndp+1); | |
14044 | while (options < end) | |
14045 | { | |
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; | |
14049 | } | |
14050 | return mDNSNULL; | |
14051 | } | |
14052 | */ | |
263eeeab A |
14053 | |
14054 | mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa, | |
83fb1e36 A |
14055 | const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID) |
14056 | { | |
14057 | AuthRecord *rr; | |
14058 | NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); | |
14059 | if (!intf) return; | |
14060 | ||
14061 | mDNS_Lock(m); | |
14062 | ||
14063 | // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary. | |
14064 | if (ndp->type == NDP_Sol) | |
14065 | { | |
14066 | //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL); | |
14067 | (void)end; | |
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)) | |
14071 | { | |
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 "; | |
f0cc3e7b A |
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; | |
83fb1e36 A |
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)); | |
51601d48 | 14083 | if (msg == msg1) |
83fb1e36 | 14084 | { |
51601d48 A |
14085 | if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS) |
14086 | RestartARPProbing(m, rr); | |
14087 | else | |
14088 | LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr)); | |
83fb1e36 | 14089 | } |
51601d48 | 14090 | else if (msg == msg3) |
12c5fa7a | 14091 | mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID); |
9f221bca | 14092 | else if (msg == msg4) |
51601d48 | 14093 | SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha); |
9f221bca | 14094 | else if (msg == msg5) |
51601d48 | 14095 | SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth); |
83fb1e36 A |
14096 | } |
14097 | } | |
14098 | ||
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); | |
14102 | else | |
14103 | { | |
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 && | |
51601d48 | 14112 | rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)) |
83fb1e36 | 14113 | { |
51601d48 A |
14114 | if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC)) |
14115 | { | |
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)); | |
14118 | } | |
83fb1e36 A |
14119 | else |
14120 | { | |
51601d48 A |
14121 | RestartARPProbing(m, rr); |
14122 | if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC)) | |
14123 | { | |
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)); | |
14126 | } | |
14127 | else | |
14128 | { | |
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); | |
14132 | } | |
83fb1e36 A |
14133 | } |
14134 | } | |
14135 | } | |
14136 | ||
14137 | mDNS_Unlock(m); | |
14138 | } | |
263eeeab A |
14139 | |
14140 | mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol, | |
83fb1e36 A |
14141 | const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len) |
14142 | { | |
14143 | const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort; | |
14144 | mDNSBool wake = mDNSfalse; | |
14145 | mDNSBool kaWake = mDNSfalse; | |
14146 | ||
14147 | switch (protocol) | |
14148 | { | |
14149 | #define XX wake ? "Received" : "Ignoring", end-p | |
14150 | case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst); | |
14151 | break; | |
14152 | ||
14153 | case 0x06: { | |
14154 | AuthRecord *kr; | |
14155 | mDNSu32 seq, ack; | |
14156 | #define TH_FIN 0x01 | |
14157 | #define TH_SYN 0x02 | |
14158 | #define TH_RST 0x04 | |
51601d48 | 14159 | #define TH_ACK 0x10 |
83fb1e36 A |
14160 | |
14161 | kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack); | |
14162 | if (kr) | |
14163 | { | |
14164 | LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port)); | |
14165 | // Plan to wake if | |
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 | |
14169 | ||
14170 | wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ; | |
14171 | if (!wake) | |
14172 | { | |
14173 | mDNSu8 *ptr; | |
14174 | mDNSu32 pseq, pack; | |
14175 | mDNSBool data = mDNSfalse; | |
14176 | mDNSu8 tcphlen; | |
14177 | ||
14178 | // Convert to host order | |
14179 | ptr = (mDNSu8 *)&seq; | |
14180 | seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; | |
14181 | ||
14182 | ptr = (mDNSu8 *)&ack; | |
14183 | ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; | |
14184 | ||
14185 | pseq = t->tcp.seq; | |
14186 | ptr = (mDNSu8 *)&pseq; | |
14187 | pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; | |
14188 | ||
14189 | pack = t->tcp.ack; | |
14190 | ptr = (mDNSu8 *)&pack; | |
14191 | pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; | |
14192 | ||
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 | |
14195 | // acked before | |
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; | |
51601d48 A |
14200 | |
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)) | |
14204 | { | |
14205 | // Send an ACK; | |
14206 | mDNS_SendKeepaliveACK(m, kr); | |
14207 | } | |
83fb1e36 A |
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); | |
14210 | } | |
14211 | else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); } | |
14212 | kaWake = wake; | |
14213 | } | |
14214 | else | |
14215 | { | |
83fb1e36 A |
14216 | // Plan to wake if |
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); | |
14220 | ||
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; | |
14224 | ||
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" : ""); | |
14230 | } | |
14231 | break; | |
14232 | } | |
14233 | ||
14234 | case 0x11: { | |
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)) | |
14239 | { | |
14240 | const mDNSu16 datalen = udplen - sizeof(UDPHeader); | |
14241 | wake = mDNStrue; | |
14242 | ||
14243 | // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling | |
14244 | if (mDNSSameIPPort(port, IPSECPort)) | |
14245 | { | |
14246 | // Specifically ignore NAT keepalive packets | |
14247 | if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse; | |
14248 | else | |
14249 | { | |
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) | |
14256 | { | |
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); | |
14261 | } | |
14262 | } | |
14263 | } | |
14264 | ||
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); | |
14271 | ||
14272 | LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port)); | |
14273 | } | |
14274 | } | |
14275 | break; | |
14276 | ||
14277 | case 0x3A: if (&t->bytes[len] <= end) | |
14278 | { | |
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); | |
14282 | } | |
14283 | break; | |
14284 | ||
14285 | default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst); | |
14286 | break; | |
14287 | } | |
14288 | ||
14289 | if (wake) | |
14290 | { | |
14291 | AuthRecord *rr, *r2; | |
14292 | ||
14293 | mDNS_Lock(m); | |
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)) | |
14298 | { | |
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)) | |
14305 | break; | |
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 | |
14308 | if (r2) | |
14309 | { | |
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); | |
14313 | } | |
14314 | else | |
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)); | |
14317 | } | |
14318 | mDNS_Unlock(m); | |
14319 | } | |
14320 | } | |
263eeeab A |
14321 | |
14322 | mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID) | |
83fb1e36 A |
14323 | { |
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) | |
14329 | ||
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); | |
14336 | mDNSAddr src, dst; | |
14337 | #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0) | |
14338 | ||
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) | |
14344 | { | |
14345 | const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4; | |
9f221bca A |
14346 | const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen); |
14347 | if (transEnd > end) transEnd = end; | |
f0cc3e7b | 14348 | debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src.b, &pkt->v4.dst.b); |
83fb1e36 A |
14349 | src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src; |
14350 | dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst; | |
9f221bca A |
14351 | if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol)) |
14352 | mDNSCoreReceiveRawTransportPacket(m, ð->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0); | |
83fb1e36 A |
14353 | } |
14354 | // Is IPv6? Length must be at least 14 + 28 = 42 bytes | |
14355 | else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6)) | |
14356 | { | |
14357 | const mDNSu8 *const trans = p + 54; | |
f0cc3e7b | 14358 | debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src.b, &pkt->v6.dst.b); |
83fb1e36 A |
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]); | |
14364 | } | |
14365 | } | |
32bb7e43 A |
14366 | |
14367 | mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name) | |
83fb1e36 A |
14368 | { |
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); | |
14371 | } | |
32bb7e43 | 14372 | |
51601d48 | 14373 | #ifndef SPC_DISABLED |
32bb7e43 | 14374 | mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result) |
83fb1e36 A |
14375 | { |
14376 | if (result == mStatus_NameConflict) | |
14377 | mDNS_RenameAndReregisterService(m, srs, mDNSNULL); | |
14378 | else if (result == mStatus_MemFree) | |
14379 | { | |
14380 | if (m->SleepState) | |
14381 | m->SPSState = 3; | |
14382 | else | |
14383 | { | |
14384 | m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL); | |
14385 | if (m->SPSState) | |
14386 | { | |
14387 | domainlabel name; | |
14388 | ConstructSleepProxyServerName(m, &name); | |
14389 | mDNS_RegisterService(m, srs, | |
14390 | &name, &SleepProxyServiceType, &localdomain, | |
14391 | mDNSNULL, m->SPSSocket->port, // Host, port | |
2682e09e | 14392 | mDNSNULL, |
83fb1e36 A |
14393 | (mDNSu8 *)"", 1, // TXT data, length |
14394 | mDNSNULL, 0, // Subtypes (none) | |
14395 | mDNSInterface_Any, // Interface ID | |
14396 | SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags | |
14397 | } | |
14398 | LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped"); | |
14399 | } | |
14400 | } | |
14401 | } | |
51601d48 | 14402 | #endif |
32bb7e43 | 14403 | |
263eeeab | 14404 | // Called with lock held |
83fb1e36 A |
14405 | mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features) |
14406 | { | |
14407 | // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context | |
14408 | mDNS_DropLockBeforeCallback(); | |
14409 | ||
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; } | |
14413 | ||
14414 | // If turning off, or changing type, deregister old name | |
51601d48 | 14415 | #ifndef SPC_DISABLED |
83fb1e36 A |
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); } | |
51601d48 | 14418 | #endif // SPC_DISABLED |
83fb1e36 A |
14419 | |
14420 | // Record our new SPS parameters | |
14421 | m->SPSType = sps; | |
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 | |
14427 | if (sps) | |
14428 | { | |
14429 | if (!m->SPSSocket) | |
14430 | { | |
12c5fa7a | 14431 | m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort); |
83fb1e36 A |
14432 | if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; } |
14433 | } | |
51601d48 | 14434 | #ifndef SPC_DISABLED |
83fb1e36 | 14435 | if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree); |
51601d48 | 14436 | #endif // SPC_DISABLED |
83fb1e36 A |
14437 | } |
14438 | else if (m->SPSState) | |
14439 | { | |
14440 | LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState); | |
14441 | m->NextScheduledSPS = m->timenow; | |
14442 | } | |
263eeeab | 14443 | fail: |
83fb1e36 A |
14444 | mDNS_ReclaimLockAfterCallback(); |
14445 | } | |
32bb7e43 | 14446 | |
6528fe3e | 14447 | // *************************************************************************** |
c9b9ae52 | 14448 | #if COMPILER_LIKES_PRAGMA_MARK |
6528fe3e | 14449 | #pragma mark - |
6528fe3e A |
14450 | #pragma mark - Startup and Shutdown |
14451 | #endif | |
14452 | ||
283ee3ff | 14453 | mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords) |
83fb1e36 A |
14454 | { |
14455 | if (storage && numrecords) | |
14456 | { | |
14457 | mDNSu32 i; | |
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; | |
14463 | } | |
14464 | } | |
c9b9ae52 | 14465 | |
283ee3ff | 14466 | mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords) |
83fb1e36 A |
14467 | { |
14468 | mDNS_Lock(m); | |
14469 | mDNS_GrowCache_internal(m, storage, numrecords); | |
14470 | mDNS_Unlock(m); | |
14471 | } | |
8e92c31c | 14472 | |
12c5fa7a A |
14473 | mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p, |
14474 | CacheEntity *rrcachestorage, mDNSu32 rrcachesize, | |
14475 | mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context) | |
83fb1e36 A |
14476 | { |
14477 | mDNSu32 slot; | |
14478 | mDNSs32 timenow; | |
14479 | mStatus result; | |
14480 | ||
14481 | if (!rrcachestorage) rrcachesize = 0; | |
14482 | ||
14483 | m->p = p; | |
9f221bca | 14484 | m->NetworkChanged = 0; |
83fb1e36 A |
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; | |
14495 | ||
14496 | // For debugging: To catch and report locking failures | |
14497 | m->mDNS_busy = 0; | |
14498 | m->mDNS_reentrancy = 0; | |
14499 | m->ShutdownTime = 0; | |
14500 | m->lock_rrcache = 0; | |
14501 | m->lock_Questions = 0; | |
14502 | m->lock_Records = 0; | |
14503 | ||
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); | |
14509 | ||
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; | |
12c5fa7a A |
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; | |
9f221bca A |
14522 | m->NextBLEServiceTime = 0; // zero indicates inactive |
14523 | ||
f0cc3e7b | 14524 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca A |
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. | |
f0cc3e7b | 14527 | #endif |
9f221bca | 14528 | |
83fb1e36 A |
14529 | m->RandomQueryDelay = 0; |
14530 | m->RandomReconfirmDelay = 0; | |
14531 | m->PktNum = 0; | |
51601d48 | 14532 | m->MPktNum = 0; |
83fb1e36 A |
14533 | m->LocalRemoveEvents = mDNSfalse; |
14534 | m->SleepState = SleepState_Awake; | |
14535 | m->SleepSeqNum = 0; | |
14536 | m->SystemWakeOnLANEnabled = mDNSfalse; | |
14537 | m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond); | |
83fb1e36 A |
14538 | m->DelaySleep = 0; |
14539 | m->SleepLimit = 0; | |
14540 | ||
51601d48 | 14541 | #if APPLE_OSX_mDNSResponder |
51601d48 A |
14542 | m->UnicastPacketsSent = 0; |
14543 | m->MulticastPacketsSent = 0; | |
14544 | m->RemoteSubnet = 0; | |
14545 | #endif // APPLE_OSX_mDNSResponder | |
14546 | ||
83fb1e36 A |
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; | |
83fb1e36 A |
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; | |
14559 | ||
14560 | for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) | |
14561 | { | |
14562 | m->rrcache_hash[slot] = mDNSNULL; | |
12c5fa7a | 14563 | m->rrcache_nextcheck[slot] = timenow + FutureTime;; |
83fb1e36 A |
14564 | } |
14565 | ||
14566 | mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize); | |
14567 | m->rrauth.rrauth_free = mDNSNULL; | |
14568 | ||
14569 | for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) | |
14570 | m->rrauth.rrauth_hash[slot] = mDNSNULL; | |
14571 | ||
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; | |
f0cc3e7b A |
14576 | #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) |
14577 | m->RandomizedHostname.c[0] = 0; | |
14578 | #endif | |
83fb1e36 A |
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; | |
6528fe3e | 14590 | |
67c8f8a1 | 14591 | #ifndef UNICAST_DISABLED |
12c5fa7a A |
14592 | m->NextuDNSEvent = timenow + FutureTime; |
14593 | m->NextSRVUpdate = timenow + FutureTime; | |
83fb1e36 | 14594 | |
19fa75a9 | 14595 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 | 14596 | m->DNSServers = mDNSNULL; |
19fa75a9 | 14597 | #endif |
83fb1e36 A |
14598 | |
14599 | m->Router = zeroAddr; | |
14600 | m->AdvertisedV4 = zeroAddr; | |
14601 | m->AdvertisedV6 = zeroAddr; | |
14602 | ||
14603 | m->AuthInfoList = mDNSNULL; | |
14604 | ||
14605 | m->ReverseMap.ThisQInterval = -1; | |
14606 | m->StaticHostname.c[0] = 0; | |
14607 | m->FQDN.c[0] = 0; | |
14608 | m->Hostnames = mDNSNULL; | |
83fb1e36 | 14609 | |
51601d48 A |
14610 | m->WABBrowseQueriesCount = 0; |
14611 | m->WABLBrowseQueriesCount = 0; | |
14612 | m->WABRegQueriesCount = 0; | |
51601d48 | 14613 | m->AutoTargetServices = 0; |
83fb1e36 | 14614 | |
f0cc3e7b | 14615 | #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) |
9f221bca A |
14616 | m->NumAllInterfaceRecords = 0; |
14617 | m->NumAllInterfaceQuestions = 0; | |
14618 | #endif | |
83fb1e36 | 14619 | // NAT traversal fields |
51601d48 A |
14620 | m->LLQNAT.clientCallback = mDNSNULL; |
14621 | m->LLQNAT.clientContext = mDNSNULL; | |
83fb1e36 A |
14622 | m->NATTraversals = mDNSNULL; |
14623 | m->CurrentNATTraversal = mDNSNULL; | |
14624 | m->retryIntervalGetAddr = 0; // delta between time sent and retry | |
12c5fa7a | 14625 | m->retryGetAddr = timenow + FutureTime; // absolute time when we retry |
51601d48 A |
14626 | m->ExtAddress = zerov4Addr; |
14627 | m->PCPNonce[0] = mDNSRandom(-1); | |
14628 | m->PCPNonce[1] = mDNSRandom(-1); | |
14629 | m->PCPNonce[2] = mDNSRandom(-1); | |
83fb1e36 A |
14630 | |
14631 | m->NATMcastRecvskt = mDNSNULL; | |
14632 | m->LastNATupseconds = 0; | |
14633 | m->LastNATReplyLocalTime = timenow; | |
14634 | m->LastNATMapResultCode = NATErr_None; | |
14635 | ||
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; | |
14646 | m->SPSType = 0; | |
14647 | m->SPSPortability = 0; | |
14648 | m->SPSMarginalPower = 0; | |
14649 | m->SPSTotalPower = 0; | |
14650 | m->SPSFeatureFlags = 0; | |
14651 | m->SPSState = 0; | |
14652 | m->SPSProxyListChanged = mDNSNULL; | |
14653 | m->SPSSocket = mDNSNULL; | |
14654 | m->SPSBrowseCallback = mDNSNULL; | |
14655 | m->ProxyRecords = 0; | |
32bb7e43 | 14656 | |
9f221bca A |
14657 | m->DNSPushServers = mDNSNULL; |
14658 | m->DNSPushZones = mDNSNULL; | |
67c8f8a1 A |
14659 | #endif |
14660 | ||
f0cc3e7b A |
14661 | #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER) |
14662 | if (WCFConnectionNew) | |
83fb1e36 A |
14663 | { |
14664 | m->WCF = WCFConnectionNew(); | |
14665 | if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; } | |
14666 | } | |
7f0064bd | 14667 | #endif |
19fa75a9 A |
14668 | |
14669 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
14670 | result = init_and_load_trust_anchors(); | |
14671 | if (result != mStatus_NoError) return(result); | |
14672 | #endif | |
67c8f8a1 | 14673 | |
12c5fa7a A |
14674 | return(result); |
14675 | } | |
14676 | ||
14677 | mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p, | |
14678 | CacheEntity *rrcachestorage, mDNSu32 rrcachesize, | |
14679 | mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context) | |
14680 | { | |
14681 | mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context); | |
14682 | if (result != mStatus_NoError) | |
14683 | return(result); | |
f0cc3e7b A |
14684 | |
14685 | #if MDNS_MALLOC_DEBUGGING | |
14686 | static mDNSListValidator lv; | |
14687 | mDNSPlatformAddListValidator(&lv, mDNS_ValidateLists, "mDNS_ValidateLists", m); | |
14688 | #endif | |
83fb1e36 | 14689 | result = mDNSPlatformInit(m); |
c9b9ae52 | 14690 | |
67c8f8a1 | 14691 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
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 | |
67c8f8a1 A |
14695 | #endif |
14696 | ||
83fb1e36 A |
14697 | return(result); |
14698 | } | |
6528fe3e | 14699 | |
32bb7e43 | 14700 | mDNSexport void mDNS_ConfigChanged(mDNS *const m) |
83fb1e36 A |
14701 | { |
14702 | if (m->SPSState == 1) | |
14703 | { | |
14704 | domainlabel name, newname; | |
51601d48 | 14705 | #ifndef SPC_DISABLED |
83fb1e36 A |
14706 | domainname type, domain; |
14707 | DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain); | |
51601d48 | 14708 | #endif // SPC_DISABLED |
83fb1e36 A |
14709 | ConstructSleepProxyServerName(m, &newname); |
14710 | if (!SameDomainLabelCS(name.c, newname.c)) | |
14711 | { | |
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 | |
14715 | m->SPSState = 2; | |
51601d48 | 14716 | #ifndef SPC_DISABLED |
83fb1e36 | 14717 | mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid); |
51601d48 | 14718 | #endif // SPC_DISABLED |
83fb1e36 A |
14719 | } |
14720 | } | |
14721 | ||
14722 | if (m->MainCallback) | |
14723 | m->MainCallback(m, mStatus_ConfigChanged); | |
14724 | } | |
32bb7e43 | 14725 | |
67c8f8a1 | 14726 | mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result) |
83fb1e36 A |
14727 | { |
14728 | (void)m; // unused | |
14729 | debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c); | |
14730 | mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result); | |
14731 | } | |
67c8f8a1 | 14732 | |
19fa75a9 | 14733 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
f0cc3e7b | 14734 | mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr) |
83fb1e36 A |
14735 | { |
14736 | mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative || | |
14737 | cr->resrec.rrtype == kDNSType_A || | |
14738 | cr->resrec.rrtype == kDNSType_AAAA || | |
5a93c909 A |
14739 | cr->resrec.rrtype == kDNSType_SRV || |
14740 | cr->resrec.rrtype == kDNSType_CNAME; | |
83fb1e36 | 14741 | |
f0cc3e7b | 14742 | debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s", |
83fb1e36 | 14743 | purge ? "purging" : "reconfirming", |
f0cc3e7b A |
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)); | |
83fb1e36 A |
14747 | |
14748 | if (purge) | |
14749 | { | |
14750 | LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType); | |
14751 | mDNS_PurgeCacheResourceRecord(m, cr); | |
14752 | } | |
14753 | else | |
14754 | { | |
14755 | LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType); | |
14756 | mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); | |
14757 | } | |
14758 | } | |
19fa75a9 | 14759 | #endif |
263eeeab | 14760 | |
564f2ae2 | 14761 | mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q) |
83fb1e36 | 14762 | { |
12c5fa7a | 14763 | CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); |
83fb1e36 | 14764 | CacheRecord *rp; |
83fb1e36 A |
14765 | for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next) |
14766 | { | |
f0cc3e7b | 14767 | if (SameNameCacheRecordAnswersQuestion(rp, q)) |
83fb1e36 | 14768 | { |
564f2ae2 | 14769 | LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp)); |
83fb1e36 A |
14770 | mDNS_PurgeCacheResourceRecord(m, rp); |
14771 | } | |
14772 | } | |
83fb1e36 A |
14773 | } |
14774 | ||
19fa75a9 | 14775 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
263eeeab | 14776 | mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new) |
83fb1e36 A |
14777 | { |
14778 | DNSQuestion *qptr; | |
14779 | ||
14780 | (void) m; | |
14781 | ||
14782 | if (q->DuplicateOf) | |
14783 | LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c); | |
14784 | ||
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) | |
14790 | { | |
14791 | if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; } | |
14792 | } | |
14793 | } | |
19fa75a9 | 14794 | #endif |
83fb1e36 | 14795 | |
51601d48 A |
14796 | mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete) |
14797 | { | |
14798 | McastResolver *mr; | |
19fa75a9 | 14799 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
51601d48 | 14800 | DNSServer *ptr; |
19fa75a9 | 14801 | #endif |
51601d48 A |
14802 | |
14803 | if (delete) | |
14804 | { | |
19fa75a9 | 14805 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
51601d48 A |
14806 | for (ptr = m->DNSServers; ptr; ptr = ptr->next) |
14807 | { | |
14808 | ptr->penaltyTime = 0; | |
f0cc3e7b A |
14809 | ptr->flags |= DNSServerFlag_Delete; |
14810 | #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS) | |
14811 | if (ptr->flags & DNSServerFlag_Unreachable) | |
9f221bca A |
14812 | NumUnreachableDNSServers--; |
14813 | #endif | |
51601d48 | 14814 | } |
19fa75a9 | 14815 | #endif |
51601d48 A |
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 | |
14818 | // API | |
14819 | for (mr = m->McastResolvers; mr; mr = mr->next) | |
14820 | mr->flags |= McastResolver_FlagDelete; | |
14821 | } | |
14822 | else | |
14823 | { | |
19fa75a9 | 14824 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
51601d48 A |
14825 | for (ptr = m->DNSServers; ptr; ptr = ptr->next) |
14826 | { | |
14827 | ptr->penaltyTime = 0; | |
f0cc3e7b A |
14828 | ptr->flags &= ~DNSServerFlag_Delete; |
14829 | #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS) | |
14830 | if (ptr->flags & DNSServerFlag_Unreachable) | |
9f221bca A |
14831 | NumUnreachableDNSServers++; |
14832 | #endif | |
51601d48 | 14833 | } |
19fa75a9 | 14834 | #endif |
51601d48 A |
14835 | for (mr = m->McastResolvers; mr; mr = mr->next) |
14836 | mr->flags &= ~McastResolver_FlagDelete; | |
14837 | } | |
14838 | } | |
14839 | ||
9f221bca A |
14840 | mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn) |
14841 | { | |
14842 | // Did our FQDN change? | |
14843 | if (!SameDomainName(fqdn, &m->FQDN)) | |
14844 | { | |
14845 | if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN); | |
14846 | ||
14847 | AssignDomainName(&m->FQDN, fqdn); | |
14848 | ||
14849 | if (m->FQDN.c[0]) | |
14850 | { | |
14851 | mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); | |
14852 | mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL); | |
14853 | } | |
14854 | } | |
14855 | } | |
14856 | ||
f0cc3e7b A |
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. | |
67c8f8a1 | 14859 | mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m) |
83fb1e36 | 14860 | { |
19fa75a9 | 14861 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 A |
14862 | mDNSu32 slot; |
14863 | CacheGroup *cg; | |
14864 | CacheRecord *cr; | |
19fa75a9 | 14865 | #endif |
83fb1e36 A |
14866 | mDNSAddr v4, v6, r; |
14867 | domainname fqdn; | |
19fa75a9 | 14868 | #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 A |
14869 | DNSServer *ptr, **p = &m->DNSServers; |
14870 | const DNSServer *oldServers = m->DNSServers; | |
14871 | DNSQuestion *q; | |
19fa75a9 | 14872 | #endif |
83fb1e36 | 14873 | McastResolver *mr, **mres = &m->McastResolvers; |
19fa75a9 | 14874 | #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
f0cc3e7b A |
14875 | DNSPushNotificationServer **psp; |
14876 | #endif | |
14877 | ||
83fb1e36 A |
14878 | debugf("uDNS_SetupDNSConfig: entry"); |
14879 | ||
51601d48 A |
14880 | // Let the platform layer get the current DNS information and setup the WAB queries if needed. |
14881 | uDNS_SetupWABQueries(m); | |
83fb1e36 A |
14882 | |
14883 | mDNS_Lock(m); | |
14884 | ||
51601d48 A |
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. | |
14887 | // | |
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); | |
12c5fa7a | 14893 | if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue)) |
51601d48 | 14894 | { |
9f221bca | 14895 | SetDynDNSHostNameIfChanged(m, &fqdn); |
51601d48 A |
14896 | SetConfigState(m, mDNSfalse); |
14897 | mDNS_Unlock(m); | |
14898 | LogInfo("uDNS_SetupDNSConfig: No configuration change"); | |
14899 | return mStatus_NoError; | |
83fb1e36 A |
14900 | } |
14901 | ||
83fb1e36 A |
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. | |
14906 | while (*mres) | |
14907 | { | |
9f221bca | 14908 | if (((*mres)->flags & McastResolver_FlagDelete) != 0) |
83fb1e36 A |
14909 | { |
14910 | mr = *mres; | |
14911 | *mres = (*mres)->next; | |
14912 | debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c); | |
14913 | mDNSPlatformMemFree(mr); | |
14914 | } | |
14915 | else | |
14916 | { | |
14917 | (*mres)->flags &= ~McastResolver_FlagNew; | |
14918 | mres = &(*mres)->next; | |
14919 | } | |
14920 | } | |
14921 | ||
19fa75a9 A |
14922 | #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
14923 | Querier_ProcessDNSServiceChanges(); | |
14924 | #else | |
83fb1e36 A |
14925 | // Update our qDNSServer pointers before we go and free the DNSServer object memory |
14926 | // | |
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. | |
14931 | // | |
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. | |
14940 | // | |
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. | |
14943 | // | |
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. | |
14947 | // | |
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. | |
14951 | // | |
f0cc3e7b | 14952 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) |
12c5fa7a A |
14953 | DNS64RestartQuestions(m); |
14954 | #endif | |
f0cc3e7b A |
14955 | |
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) | |
51601d48 | 14962 | { |
f0cc3e7b A |
14963 | DNSServer *s; |
14964 | const DNSServer *t; | |
14965 | mDNSBool oldSuppressed; | |
51601d48 | 14966 | |
f0cc3e7b | 14967 | if (mDNSOpaque16IsZero(q->TargetQID)) continue; |
51601d48 | 14968 | |
f0cc3e7b A |
14969 | SetValidDNSServers(m, q); |
14970 | q->triedAllServersOnce = mDNSfalse; | |
14971 | s = GetServerForQuestion(m, q); | |
14972 | t = q->qDNSServer; | |
14973 | if (s != t) | |
14974 | { | |
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), | |
19fa75a9 A |
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); | |
f0cc3e7b A |
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)) | |
14986 | { | |
14987 | if (q->dnsPushServer->qDNSServer == t) | |
14988 | { | |
14989 | q->dnsPushServer->qDNSServer = s; // which might be null | |
14990 | } | |
14991 | // If it is null, do the accounting and drop the push server. | |
14992 | if (q->dnsPushServer->qDNSServer == mDNSNULL) | |
14993 | { | |
14994 | DNSPushReconcileConnection(m, q); | |
83fb1e36 A |
14995 | } |
14996 | } | |
f0cc3e7b A |
14997 | #endif |
14998 | } | |
14999 | oldSuppressed = q->Suppressed; | |
15000 | q->Suppressed = ShouldSuppressUnicastQuery(q, s); | |
15001 | if (!q->Suppressed != !oldSuppressed) q->Restart = mDNStrue; | |
15002 | } | |
15003 | RestartUnicastQuestions(m); | |
15004 | ||
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) | |
15008 | { | |
15009 | DNSServer *s; | |
15010 | const DNSServer *t; | |
15011 | ||
15012 | if (mDNSOpaque16IsZero(q->TargetQID) || q->DuplicateOf) continue; | |
15013 | ||
15014 | SetValidDNSServers(m, q); | |
15015 | q->triedAllServersOnce = mDNSfalse; | |
15016 | s = GetServerForQuestion(m, q); | |
15017 | t = q->qDNSServer; | |
15018 | DNSServerChangeForQuestion(m, q, s); | |
15019 | if (s == t) continue; | |
15020 | ||
15021 | q->Suppressed = ShouldSuppressUnicastQuery(q, s); | |
15022 | q->unansweredQueries = 0; | |
15023 | q->TargetQID = mDNS_NewMessageID(m); | |
15024 | if (!q->Suppressed) ActivateUnicastQuery(m, q, mDNStrue); | |
15025 | } | |
15026 | ||
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; ) | |
15032 | { | |
15033 | DNSPushNotificationServer *server = *psp; | |
15034 | ||
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) | |
15039 | { | |
15040 | server->qDNSServer = mDNSNULL; | |
15041 | } | |
15042 | ||
15043 | if (server->qDNSServer == mDNSNULL) | |
15044 | { | |
15045 | // This would be a programming error, so should never happen. | |
15046 | if (server->numberOfQuestions != 0) | |
83fb1e36 | 15047 | { |
f0cc3e7b | 15048 | LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server->serverName); |
83fb1e36 | 15049 | } |
f0cc3e7b A |
15050 | DNSPushServerDrop(server); |
15051 | *psp = server->next; | |
15052 | mDNSPlatformMemFree(server); | |
15053 | } | |
15054 | else | |
15055 | { | |
15056 | psp = &(*psp)->next; | |
83fb1e36 | 15057 | } |
51601d48 | 15058 | } |
f0cc3e7b | 15059 | #endif |
83fb1e36 A |
15060 | |
15061 | FORALL_CACHERECORDS(slot, cg, cr) | |
15062 | { | |
f0cc3e7b | 15063 | if (cr->resrec.InterfaceID) continue; |
51601d48 A |
15064 | |
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. | |
83fb1e36 | 15071 | // |
51601d48 A |
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. | |
51601d48 A |
15076 | // |
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. | |
15080 | ||
19fa75a9 | 15081 | if (cr->CRActiveQuestion) |
83fb1e36 | 15082 | { |
f0cc3e7b A |
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)) | |
83fb1e36 | 15086 | { |
f0cc3e7b A |
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); | |
15091 | ||
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) | |
15095 | { | |
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; | |
15098 | } | |
83fb1e36 | 15099 | } |
f0cc3e7b A |
15100 | |
15101 | if (cr->resrec.rDNSServer && cr->resrec.rDNSServer->flags & DNSServerFlag_Delete) | |
83fb1e36 | 15102 | { |
f0cc3e7b A |
15103 | DNSQuestion *qptr = cr->CRActiveQuestion; |
15104 | if (qptr->qDNSServer == cr->resrec.rDNSServer) | |
15105 | { | |
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; | |
15113 | } | |
15114 | else | |
15115 | { | |
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; | |
15122 | } | |
15123 | PurgeOrReconfirmCacheRecord(m, cr); | |
83fb1e36 A |
15124 | } |
15125 | } | |
f0cc3e7b | 15126 | else if (!cr->resrec.rDNSServer || cr->resrec.rDNSServer->flags & DNSServerFlag_Delete) |
9f221bca | 15127 | { |
f0cc3e7b A |
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; | |
f0cc3e7b | 15134 | mDNS_PurgeCacheResourceRecord(m, cr); |
9f221bca | 15135 | } |
83fb1e36 A |
15136 | } |
15137 | ||
f0cc3e7b | 15138 | // Delete all the DNS servers that are flagged for deletion |
83fb1e36 A |
15139 | while (*p) |
15140 | { | |
f0cc3e7b | 15141 | if (((*p)->flags & DNSServerFlag_Delete) != 0) |
83fb1e36 | 15142 | { |
83fb1e36 | 15143 | ptr = *p; |
83fb1e36 | 15144 | *p = (*p)->next; |
f0cc3e7b | 15145 | LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c); |
83fb1e36 | 15146 | mDNSPlatformMemFree(ptr); |
83fb1e36 A |
15147 | } |
15148 | else | |
15149 | { | |
83fb1e36 A |
15150 | p = &(*p)->next; |
15151 | } | |
15152 | } | |
f0cc3e7b | 15153 | LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m)); |
83fb1e36 A |
15154 | |
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)) | |
15160 | { | |
15161 | int count = 0; | |
15162 | FORALL_CACHERECORDS(slot, cg, cr) | |
15163 | { | |
15164 | if (!cr->resrec.InterfaceID) | |
15165 | { | |
15166 | mDNS_PurgeCacheResourceRecord(m, cr); | |
15167 | count++; | |
15168 | } | |
15169 | } | |
15170 | LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache", | |
15171 | m->DNSServers ? "DNS server became" : "No DNS servers", count); | |
15172 | ||
15173 | // Force anything that needs to get zone data to get that information again | |
15174 | RestartRecordGetZoneData(m); | |
15175 | } | |
19fa75a9 | 15176 | #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) |
83fb1e36 | 15177 | |
9f221bca | 15178 | SetDynDNSHostNameIfChanged(m, &fqdn); |
83fb1e36 A |
15179 | |
15180 | mDNS_Unlock(m); | |
15181 | ||
15182 | // handle router and primary interface changes | |
15183 | v4 = v6 = r = zeroAddr; | |
15184 | v4.type = r.type = mDNSAddrType_IPv4; | |
15185 | ||
12c5fa7a | 15186 | if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4)) |
83fb1e36 A |
15187 | { |
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); | |
15192 | } | |
15193 | else | |
15194 | { | |
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 | |
15197 | } | |
15198 | ||
f0cc3e7b | 15199 | debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m)); |
83fb1e36 A |
15200 | return mStatus_NoError; |
15201 | } | |
67c8f8a1 | 15202 | |
c9b9ae52 | 15203 | mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result) |
83fb1e36 A |
15204 | { |
15205 | m->mDNSPlatformStatus = result; | |
15206 | if (m->MainCallback) | |
15207 | { | |
15208 | mDNS_Lock(m); | |
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 | |
15212 | mDNS_Unlock(m); | |
15213 | } | |
15214 | } | |
6528fe3e | 15215 | |
32bb7e43 | 15216 | mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start) |
83fb1e36 A |
15217 | { |
15218 | m->CurrentRecord = start; | |
15219 | while (m->CurrentRecord) | |
15220 | { | |
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) | |
15228 | { | |
15229 | rr->AnnounceCount = 1; | |
15230 | rr->LastAPTime = m->timenow - rr->ThisAPInterval; | |
15231 | } | |
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; | |
15236 | } | |
15237 | } | |
32bb7e43 | 15238 | |
030b743d | 15239 | mDNSexport void mDNS_StartExit(mDNS *const m) |
83fb1e36 | 15240 | { |
83fb1e36 | 15241 | AuthRecord *rr; |
030b743d | 15242 | |
83fb1e36 | 15243 | mDNS_Lock(m); |
030b743d | 15244 | |
19fa75a9 | 15245 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit"); |
83fb1e36 | 15246 | m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5); |
6528fe3e | 15247 | |
83fb1e36 | 15248 | mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0); |
263eeeab | 15249 | |
f0cc3e7b A |
15250 | #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER) |
15251 | if (WCFConnectionDealloc) | |
83fb1e36 | 15252 | { |
19fa75a9 A |
15253 | if (m->WCF) |
15254 | { | |
15255 | WCFConnectionDealloc(m->WCF); | |
15256 | m->WCF = mDNSNULL; | |
15257 | } | |
83fb1e36 | 15258 | } |
263eeeab | 15259 | #endif |
32bb7e43 | 15260 | |
67c8f8a1 | 15261 | #ifndef UNICAST_DISABLED |
83fb1e36 A |
15262 | { |
15263 | SearchListElem *s; | |
15264 | SuspendLLQs(m); | |
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); | |
15268 | ||
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) | |
15274 | { | |
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 | |
15278 | } | |
15279 | } | |
7f0064bd | 15280 | #endif |
67c8f8a1 | 15281 | |
f0cc3e7b | 15282 | DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_All); |
83fb1e36 A |
15283 | |
15284 | // Shut down all our active NAT Traversals | |
15285 | while (m->NATTraversals) | |
15286 | { | |
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 | |
15289 | ||
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 | |
15295 | // to not do this. | |
15296 | t->ExternalAddress = zerov4Addr; | |
51601d48 | 15297 | t->NewAddress = zerov4Addr; |
83fb1e36 A |
15298 | t->ExternalPort = zeroIPPort; |
15299 | t->RequestedPort = zeroIPPort; | |
15300 | t->Lifetime = 0; | |
15301 | t->Result = mStatus_NoError; | |
15302 | } | |
15303 | ||
15304 | // Make sure there are nothing but deregistering records remaining in the list | |
15305 | if (m->CurrentRecord) | |
19fa75a9 A |
15306 | { |
15307 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, | |
15308 | "mDNS_StartExit: ERROR m->CurrentRecord already set " PRI_S, ARDisplayString(m, m->CurrentRecord)); | |
15309 | } | |
83fb1e36 A |
15310 | |
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. | |
19fa75a9 | 15315 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering duplicate resource records"); |
83fb1e36 | 15316 | DeregLoop(m, m->DuplicateRecords); |
19fa75a9 | 15317 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering resource records"); |
83fb1e36 A |
15318 | DeregLoop(m, m->ResourceRecords); |
15319 | ||
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) | |
15323 | { | |
15324 | m->NextScheduledResponse = m->timenow; | |
15325 | m->SuppressSending = 0; | |
15326 | } | |
15327 | ||
19fa75a9 A |
15328 | if (m->ResourceRecords) |
15329 | { | |
15330 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Sending final record deregistrations"); | |
15331 | } | |
15332 | else | |
15333 | { | |
15334 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: No deregistering records remain"); | |
15335 | } | |
83fb1e36 A |
15336 | |
15337 | for (rr = m->DuplicateRecords; rr; rr = rr->next) | |
19fa75a9 A |
15338 | { |
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)); | |
15342 | } | |
83fb1e36 A |
15343 | |
15344 | // If any deregistering records remain, send their deregistration announcements before we exit | |
15345 | if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m); | |
15346 | ||
15347 | mDNS_Unlock(m); | |
15348 | ||
19fa75a9 | 15349 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: done"); |
83fb1e36 | 15350 | } |
030b743d A |
15351 | |
15352 | mDNSexport void mDNS_FinalExit(mDNS *const m) | |
83fb1e36 A |
15353 | { |
15354 | mDNSu32 rrcache_active = 0; | |
9f221bca | 15355 | mDNSu32 rrcache_totalused = m->rrcache_totalused; |
83fb1e36 A |
15356 | mDNSu32 slot; |
15357 | AuthRecord *rr; | |
15358 | ||
19fa75a9 | 15359 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: mDNSPlatformClose"); |
83fb1e36 A |
15360 | mDNSPlatformClose(m); |
15361 | ||
83fb1e36 A |
15362 | for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) |
15363 | { | |
15364 | while (m->rrcache_hash[slot]) | |
15365 | { | |
15366 | CacheGroup *cg = m->rrcache_hash[slot]; | |
15367 | while (cg->members) | |
15368 | { | |
15369 | CacheRecord *cr = cg->members; | |
15370 | cg->members = cg->members->next; | |
15371 | if (cr->CRActiveQuestion) rrcache_active++; | |
15372 | ReleaseCacheRecord(m, cr); | |
15373 | } | |
15374 | cg->rrcache_tail = &cg->members; | |
15375 | ReleaseCacheGroup(m, &m->rrcache_hash[slot]); | |
15376 | } | |
15377 | } | |
15378 | debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active); | |
15379 | if (rrcache_active != m->rrcache_active) | |
9f221bca | 15380 | LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active); |
83fb1e36 A |
15381 | |
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)); | |
15384 | ||
19fa75a9 A |
15385 | #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) |
15386 | uninit_trust_anchors(); | |
15387 | #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) | |
15388 | ||
15389 | LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: done"); | |
83fb1e36 | 15390 | } |
12c5fa7a A |
15391 | |
15392 | #ifdef UNIT_TEST | |
15393 | #include "../unittests/mdns_ut.c" | |
15394 | #endif |