1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
2 *
3 * Copyright (c) 2002-2020 Apple Inc. All rights reserved.
4 *
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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
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.
19 *
20 * The previous point is very important: This file does not depend on any external
21 * header files. It should compile on *any* platform that has a C compiler, without
22 * making *any* assumptions about availability of so-called "standard" C functions,
23 * routines, or types (which may or may not be present on any given platform).
24 */
25
26 #include <stddef.h>
27 #include "DNSCommon.h" // Defines general DNS utility routines
28 #include "uDNS.h" // Defines entry points into unicast-specific routines
29
30 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
31 #include "D2D.h"
32 #endif
33
34 #if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
35 #include <bsm/libbsm.h>
36 #endif
37
38 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
39 #include "dnssd_analytics.h"
40 #endif
41
42 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
43 #include "QuerierSupport.h"
44 #endif
45
46 // Disable certain benign warnings with Microsoft compilers
47 #if (defined(_MSC_VER))
48 // Disable "conditional expression is constant" warning for debug macros.
49 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
50 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
51 #pragma warning(disable:4127)
52
53 // Disable "assignment within conditional expression".
54 // Other compilers understand the convention that if you place the assignment expression within an extra pair
55 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
56 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
57 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
58 #pragma warning(disable:4706)
59 #endif
60
61 #include "dns_sd.h" // for kDNSServiceFlags* definitions
62 #include "dns_sd_internal.h"
63
64 #if APPLE_OSX_mDNSResponder
65 // Delay in seconds before disabling multicast after there are no active queries or registrations.
66 #define BONJOUR_DISABLE_DELAY 60
67 #endif
68
69 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
70 #include <WebFilterDNS/WebFilterDNS.h>
71
72 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
73 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
74 #endif
75
76 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
77 #include "Metrics.h"
78 #endif
79
80 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
81 #include "DNS64.h"
82 #endif
83
84 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
85 #include "dnssec_v2.h"
86 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
87
88 // Forward declarations
89 mDNSlocal void BeginSleepProcessing(mDNS *const m);
90 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
91 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly);
92 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
93 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
94 #endif
95 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
96 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
97 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
98 mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
99
100 typedef mDNSu32 DeadvertiseFlags;
101 #define kDeadvertiseFlag_NormalHostname (1U << 0)
102 #define kDeadvertiseFlag_RandHostname (1U << 1)
103 #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
104
105 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags);
106 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set);
107 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
108
109 // ***************************************************************************
110 #if COMPILER_LIKES_PRAGMA_MARK
111 #pragma mark - Program Constants
112 #endif
113
114 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
115 #define MDNS_TRACER 1
116
117 // Any records bigger than this are considered 'large' records
118 #define SmallRecordLimit 1024
119
120 #define kMaxUpdateCredits 10
121 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
122
123 // define special NR_AnswerTo values
124 #define NR_AnswerMulticast (mDNSu8*)~0
125 #define NR_AnswerUnicast (mDNSu8*)~1
126
127 // Question default timeout values
128 #define DEFAULT_MCAST_TIMEOUT 5
129 #define DEFAULT_LO_OR_P2P_TIMEOUT 5
130
131 // The code (see SendQueries() and BuildQuestion()) needs to have the
132 // RequestUnicast value set to a value one greater than the number of times you want the query
133 // sent with the "request unicast response" (QU) bit set.
134 #define SET_QU_IN_FIRST_QUERY 2
135 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
136
137 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
138 #define DARK_WAKE_DELAY_SLEEP 5
139 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
140
141 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
142 #define MAX_CONFLICT_PROCESSING_DELAYS 3
143
144 // RFC 6762 defines Passive Observation Of Failures (POOF)
145 //
146 // A host observes the multicast queries issued by the other hosts on
147 // the network. One of the major benefits of also sending responses
148 // using multicast is that it allows all hosts to see the responses
149 // (or lack thereof) to those queries.
150 //
151 // If a host sees queries, for which a record in its cache would be
152 // expected to be given as an answer in a multicast response, but no
153 // such answer is seen, then the host may take this as an indication
154 // that the record may no longer be valid.
155 //
156 // After seeing two or more of these queries, and seeing no multicast
157 // response containing the expected answer within ten seconds, then even
158 // though its TTL may indicate that it is not yet due to expire, that
159 // record SHOULD be flushed from the cache.
160 //
161 // <https://tools.ietf.org/html/rfc6762#section-10.5>
162
163 #define POOF_ENABLED 1
164
165 mDNSexport const char *const mDNS_DomainTypeNames[] =
166 {
167 "b._dns-sd._udp.", // Browse
168 "db._dns-sd._udp.", // Default Browse
169 "lb._dns-sd._udp.", // Automatic Browse
170 "r._dns-sd._udp.", // Registration
171 "dr._dns-sd._udp." // Default Registration
172 };
173
174 #ifdef UNICAST_DISABLED
175 #define uDNS_IsActiveQuery(q, u) mDNSfalse
176 #endif
177
178 // ***************************************************************************
179 #if COMPILER_LIKES_PRAGMA_MARK
180 #pragma mark -
181 #pragma mark - General Utility Functions
182 #endif
183
184 #if MDNS_MALLOC_DEBUGGING
185 // When doing memory allocation debugging, this function traverses all lists in the mDNS query
186 // structures and caches and checks each entry in the list to make sure it's still good.
mDNS_ValidateLists(void * context)187 mDNSlocal void mDNS_ValidateLists(void *context)
188 {
189 mDNS *m = context;
190 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
191 mDNSu32 NumAllInterfaceRecords = 0;
192 mDNSu32 NumAllInterfaceQuestions = 0;
193 #endif
194
195 // Check core mDNS lists
196 AuthRecord *rr;
197 for (rr = m->ResourceRecords; rr; rr=rr->next)
198 {
199 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
200 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
201 if (rr->resrec.name != &rr->namestorage)
202 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
203 rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
204 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
205 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
206 #endif
207 }
208
209 for (rr = m->DuplicateRecords; rr; rr=rr->next)
210 {
211 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
212 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
213 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
214 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
215 #endif
216 }
217
218 rr = m->NewLocalRecords;
219 if (rr)
220 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
221 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType);
222
223 rr = m->CurrentRecord;
224 if (rr)
225 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
226 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType);
227
228 DNSQuestion *q;
229 for (q = m->Questions; q; q=q->next)
230 {
231 if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0)
232 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next);
233 if (q->DuplicateOf && q->LocalSocket)
234 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
235 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
236 if (!LocalOnlyOrP2PInterface(q->InterfaceID) && mDNSOpaque16IsZero(q->TargetQID))
237 NumAllInterfaceQuestions++;
238 #endif
239 }
240
241 CacheGroup *cg;
242 CacheRecord *cr;
243 mDNSu32 slot;
244 FORALL_CACHERECORDS(slot, cg, cr)
245 {
246 if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
247 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType);
248 if (cr->CRActiveQuestion)
249 {
250 for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break;
251 if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr));
252 }
253 }
254
255 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
256 if (m->NumAllInterfaceRecords != NumAllInterfaceRecords)
257 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords);
258
259 if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions)
260 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions);
261 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
262 }
263 #endif // MDNS_MALLOC_DEBUGGING
264
265 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
266 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
267 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
268 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
269 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
270 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
271 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
272 (rr)->resrec.rrtype == kDNSType_CNAME || \
273 (rr)->resrec.rrtype == kDNSType_PTR))
274
SetNextQueryStopTime(mDNS * const m,const DNSQuestion * const q)275 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
276 {
277 mDNS_CheckLock(m);
278
279 if (m->NextScheduledStopTime - q->StopTime > 0)
280 m->NextScheduledStopTime = q->StopTime;
281 }
282
SetNextQueryTime(mDNS * const m,const DNSQuestion * const q)283 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
284 {
285 mDNS_CheckLock(m);
286
287 if (ActiveQuestion(q))
288 {
289 // Depending on whether this is a multicast or unicast question we want to set either:
290 // m->NextScheduledQuery = NextQSendTime(q) or
291 // m->NextuDNSEvent = NextQSendTime(q)
292 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
293 if (*timer - NextQSendTime(q) > 0)
294 *timer = NextQSendTime(q);
295 }
296 }
297
ReleaseAuthEntity(AuthHash * r,AuthEntity * e)298 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
299 {
300 #if MDNS_MALLOC_DEBUGGING >= 1
301 unsigned int i;
302 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
303 #endif
304 e->next = r->rrauth_free;
305 r->rrauth_free = e;
306 r->rrauth_totalused--;
307 }
308
ReleaseAuthGroup(AuthHash * r,AuthGroup ** cp)309 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
310 {
311 AuthEntity *e = (AuthEntity *)(*cp);
312 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c);
313 if ((*cp)->rrauth_tail != &(*cp)->members)
314 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
315 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
316 (*cp)->name = mDNSNULL;
317 *cp = (*cp)->next; // Cut record from list
318 ReleaseAuthEntity(r, e);
319 }
320
GetAuthEntity(AuthHash * r,const AuthGroup * const PreserveAG)321 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
322 {
323 AuthEntity *e = mDNSNULL;
324
325 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
326 r->rrauth_lock = 1;
327
328 if (!r->rrauth_free)
329 {
330 // We allocate just one AuthEntity at a time because we need to be able
331 // free them all individually which normally happens when we parse /etc/hosts into
332 // AuthHash where we add the "new" entries and discard (free) the already added
333 // entries. If we allocate as chunks, we can't free them individually.
334 AuthEntity *storage = (AuthEntity *) mDNSPlatformMemAllocateClear(sizeof(*storage));
335 storage->next = mDNSNULL;
336 r->rrauth_free = storage;
337 }
338
339 // If we still have no free records, recycle all the records we can.
340 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
341 if (!r->rrauth_free)
342 {
343 mDNSu32 oldtotalused = r->rrauth_totalused;
344 mDNSu32 slot;
345 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
346 {
347 AuthGroup **cp = &r->rrauth_hash[slot];
348 while (*cp)
349 {
350 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
351 else ReleaseAuthGroup(r, cp);
352 }
353 }
354 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
355 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
356 }
357
358 if (r->rrauth_free) // If there are records in the free list, take one
359 {
360 e = r->rrauth_free;
361 r->rrauth_free = e->next;
362 if (++r->rrauth_totalused >= r->rrauth_report)
363 {
364 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
365 if (r->rrauth_report < 100) r->rrauth_report += 10;
366 else if (r->rrauth_report < 1000) r->rrauth_report += 100;
367 else r->rrauth_report += 1000;
368 }
369 mDNSPlatformMemZero(e, sizeof(*e));
370 }
371
372 r->rrauth_lock = 0;
373
374 return(e);
375 }
376
AuthGroupForName(AuthHash * r,const mDNSu32 namehash,const domainname * const name)377 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name)
378 {
379 AuthGroup *ag;
380 const mDNSu32 slot = namehash % AUTH_HASH_SLOTS;
381
382 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
383 if (ag->namehash == namehash && SameDomainName(ag->name, name))
384 break;
385 return(ag);
386 }
387
AuthGroupForRecord(AuthHash * r,const ResourceRecord * const rr)388 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr)
389 {
390 return(AuthGroupForName(r, rr->namehash, rr->name));
391 }
392
GetAuthGroup(AuthHash * r,const ResourceRecord * const rr)393 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr)
394 {
395 mDNSu16 namelen = DomainNameLength(rr->name);
396 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
397 const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS;
398 if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
399 ag->next = r->rrauth_hash[slot];
400 ag->namehash = rr->namehash;
401 ag->members = mDNSNULL;
402 ag->rrauth_tail = &ag->members;
403 ag->NewLocalOnlyRecords = mDNSNULL;
404 if (namelen > sizeof(ag->namestorage))
405 ag->name = (domainname *) mDNSPlatformMemAllocate(namelen);
406 else
407 ag->name = (domainname*)ag->namestorage;
408 if (!ag->name)
409 {
410 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
411 ReleaseAuthEntity(r, (AuthEntity*)ag);
412 return(mDNSNULL);
413 }
414 AssignDomainName(ag->name, rr->name);
415
416 if (AuthGroupForRecord(r, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
417 r->rrauth_hash[slot] = ag;
418 if (AuthGroupForRecord(r, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
419
420 return(ag);
421 }
422
423 // Returns the AuthGroup in which the AuthRecord was inserted
InsertAuthRecord(mDNS * const m,AuthHash * r,AuthRecord * rr)424 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
425 {
426 AuthGroup *ag;
427
428 (void)m;
429 ag = AuthGroupForRecord(r, &rr->resrec);
430 if (!ag) ag = GetAuthGroup(r, &rr->resrec); // If we don't have a AuthGroup for this name, make one now
431 if (ag)
432 {
433 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list
434 ag->rrauth_tail = &(rr->next); // Advance tail pointer
435 }
436 return ag;
437 }
438
RemoveAuthRecord(mDNS * const m,AuthHash * r,AuthRecord * rr)439 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
440 {
441 AuthGroup *a;
442 AuthRecord **rp;
443
444 a = AuthGroupForRecord(r, &rr->resrec);
445 if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
446 rp = &a->members;
447 while (*rp)
448 {
449 if (*rp != rr)
450 rp=&(*rp)->next;
451 else
452 {
453 // We don't break here, so that we can set the tail below without tracking "prev" pointers
454
455 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
456 *rp = (*rp)->next; // Cut record from list
457 }
458 }
459 // TBD: If there are no more members, release authgroup ?
460 a->rrauth_tail = rp;
461 return a;
462 }
463
CacheGroupForName(const mDNS * const m,const mDNSu32 namehash,const domainname * const name)464 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name)
465 {
466 CacheGroup *cg;
467 mDNSu32 slot = HashSlotFromNameHash(namehash);
468 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
469 if (cg->namehash == namehash && SameDomainName(cg->name, name))
470 break;
471 return(cg);
472 }
473
CacheGroupForRecord(const mDNS * const m,const ResourceRecord * const rr)474 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr)
475 {
476 return(CacheGroupForName(m, rr->namehash, rr->name));
477 }
478
mDNS_AddressIsLocalSubnet(mDNS * const m,const mDNSInterfaceID InterfaceID,const mDNSAddr * addr)479 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
480 {
481 NetworkInterfaceInfo *intf;
482
483 if (addr->type == mDNSAddrType_IPv4)
484 {
485 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
486 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
487 for (intf = m->HostInterfaces; intf; intf = intf->next)
488 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
489 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
490 return(mDNStrue);
491 }
492
493 if (addr->type == mDNSAddrType_IPv6)
494 {
495 if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
496 for (intf = m->HostInterfaces; intf; intf = intf->next)
497 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
498 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
499 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
500 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
501 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
502 return(mDNStrue);
503 }
504
505 return(mDNSfalse);
506 }
507
FirstInterfaceForID(mDNS * const m,const mDNSInterfaceID InterfaceID)508 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
509 {
510 NetworkInterfaceInfo *intf = m->HostInterfaces;
511 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
512 return(intf);
513 }
514
FirstIPv4LLInterfaceForID(mDNS * const m,const mDNSInterfaceID InterfaceID)515 mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
516 {
517 NetworkInterfaceInfo *intf;
518
519 if (!InterfaceID)
520 return mDNSNULL;
521
522 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
523 // we still want to find the first IPv4 Link-Local interface
524 for (intf = m->HostInterfaces; intf; intf = intf->next)
525 {
526 if (intf->InterfaceID == InterfaceID &&
527 intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
528 {
529 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
530 return intf;
531 }
532 }
533 return (mDNSNULL);
534 }
535
InterfaceNameForID(mDNS * const m,const mDNSInterfaceID InterfaceID)536 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
537 {
538 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
539 return(intf ? intf->ifname : mDNSNULL);
540 }
541
542 // Caller should hold the lock
GenerateNegativeResponseEx(mDNS * const m,mDNSInterfaceID InterfaceID,QC_result qc,mDNSBool noData)543 mDNSlocal void GenerateNegativeResponseEx(mDNS *const m, mDNSInterfaceID InterfaceID, QC_result qc, mDNSBool noData)
544 {
545 DNSQuestion *q;
546 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
547 q = m->CurrentQuestion;
548 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
549 "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME " (" PUB_S ")",
550 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
551
552 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, InterfaceID, mDNSNULL);
553 m->rec.r.resrec.negativeRecordType = noData ? kNegativeRecordType_NoData : kNegativeRecordType_Unspecified;
554
555 // We need to force the response through in the following cases
556 //
557 // a) SuppressUnusable questions that are suppressed
558 // b) Append search domains and retry the question
559 //
560 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
561 // through we use "QC_forceresponse".
562 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
563 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question
564 // Don't touch the question after this
565 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
566 }
567 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
568
AnswerQuestionByFollowingCNAME(mDNS * const m,DNSQuestion * q,ResourceRecord * rr)569 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
570 {
571 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
572 if (q->CNAMEReferrals >= 10 || selfref)
573 {
574 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
575 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ") NOT following CNAME referral %d" PUB_S " for " PRI_S,
576 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype),
577 q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
578
579 }
580 else
581 {
582 UDPSocket *sock = q->LocalSocket;
583 mDNSOpaque16 id = q->TargetQID;
584 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
585 uDNSMetrics metrics;
586 #endif
587
588 q->LocalSocket = mDNSNULL;
589
590 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
591 // themselves. Without that check we can get into a case where we have two duplicate questions,
592 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
593 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
594 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
595 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
596 // for either of them. This is not a problem for CNAME loops of two or more records because in
597 // those cases the newly re-appended question A has a different target name and therefore cannot be
598 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
599
600 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
601 // and track CNAMEs coming and going, we should really create a subordinate query here,
602 // which we would subsequently cancel and retract if the CNAME referral record were removed.
603 // In reality this is such a corner case we'll ignore it until someone actually needs it.
604
605 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
606 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ") following CNAME referral %d for " PRI_S,
607 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype),
608 q->CNAMEReferrals, RRDisplayString(m, rr));
609
610 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
611 if (!mDNSOpaque16IsZero(q->TargetQID))
612 {
613 // Must be called before zeroing out q->metrics below.
614 Querier_PrepareQuestionForCNAMERestart(q);
615 }
616 #endif
617 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
618 if ((q->CNAMEReferrals == 0) && !q->metrics.originalQName)
619 {
620 domainname * qName;
621 mDNSu16 qNameLen;
622
623 qNameLen = DomainNameLength(&q->qname);
624 if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
625 {
626 qName = (domainname *) mDNSPlatformMemAllocate(qNameLen);
627 if (qName)
628 {
629 mDNSPlatformMemCopy(qName->c, q->qname.c, qNameLen);
630 q->metrics.originalQName = qName;
631 }
632 }
633 }
634 metrics = q->metrics;
635 // The metrics will be transplanted to the restarted question, so zero out the old copy instead of using
636 // uDNSMetricsClear(), which will free any pointers to allocated memory.
637 mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics));
638 #endif
639 mDNS_StopQuery_internal(m, q); // Stop old query
640 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname
641 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
642 // If a unicast query results in a CNAME that points to a .local, we need to re-try
643 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
644 // to try this as unicast query even though it is a .local name
645 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
646 {
647 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
648 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME " (" PUB_S ") Record " PRI_S,
649 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), RRDisplayString(m, rr));
650 q->IsUnicastDotLocal = mDNStrue;
651 }
652 q->CNAMEReferrals += 1; // Increment value before calling mDNS_StartQuery_internal
653 const mDNSu32 c = q->CNAMEReferrals; // Stash a copy of the new q->CNAMEReferrals value
654 mDNS_StartQuery_internal(m, q); // start new query
655 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
656 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
657 q->CNAMEReferrals = c;
658 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
659 metrics.expiredAnswerState = q->metrics.expiredAnswerState; // We want the newly initialized state for this value
660 metrics.dnsOverTCPState = q->metrics.dnsOverTCPState; // We want the newly initialized state for this value
661 q->metrics = metrics;
662 #endif
663 if (sock)
664 {
665 // 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.
666 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
667 else
668 {
669 // Transplant the old socket into the new question, and copy the query ID across too.
670 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
671 q->LocalSocket = sock;
672 q->TargetQID = id;
673 }
674 }
675 }
676 }
677
678 #ifdef USE_LIBIDN
679
680 #include <unicode/uidna.h>
681
682 // #define DEBUG_PUNYCODE 1
683
PunycodeConvert(const mDNSu8 * const src,mDNSu8 * const dst,const mDNSu8 * const end)684 mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end)
685 {
686 UErrorCode errorCode = U_ZERO_ERROR;
687 UIDNAInfo info = UIDNA_INFO_INITIALIZER;
688 UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode);
689 int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, (int32_t)(end-(dst+1)), &info, &errorCode);
690 uidna_close(uts46);
691 #if DEBUG_PUNYCODE
692 if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode);
693 if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors);
694 if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len);
695 #endif
696 if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL;
697 *dst = len;
698 return(dst + 1 + len);
699 }
700
IsHighASCIILabel(const mDNSu8 * d)701 mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d)
702 {
703 int i;
704 for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue;
705 return mDNSfalse;
706 }
707
FindLastHighASCIILabel(const domainname * const d)708 mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d)
709 {
710 const mDNSu8 *ptr = d->c;
711 const mDNSu8 *ans = mDNSNULL;
712 while (ptr[0])
713 {
714 const mDNSu8 *const next = ptr + 1 + ptr[0];
715 if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL;
716 if (IsHighASCIILabel(ptr)) ans = ptr;
717 ptr = next;
718 }
719 return ans;
720 }
721
PerformNextPunycodeConversion(const DNSQuestion * const q,domainname * const newname)722 mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname)
723 {
724 const mDNSu8 *h = FindLastHighASCIILabel(&q->qname);
725 #if DEBUG_PUNYCODE
726 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h);
727 #endif
728 if (!h) return mDNSfalse; // There are no high-ascii labels to convert
729
730 mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME);
731 if (!dst)
732 return mDNSfalse; // The label was not convertible to Punycode
733 else
734 {
735 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
736 const mDNSu8 *const src = h + 1 + h[0];
737 const mDNSu8 remainder = DomainNameLength((domainname*)src);
738 if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse; // Name too long -- cannot be converted to Punycode
739
740 mDNSPlatformMemCopy(newname->c, q->qname.c, (mDNSu32)(h - q->qname.c)); // Fill in the leading part
741 mDNSPlatformMemCopy(dst, src, remainder); // Fill in the trailing part
742 #if DEBUG_PUNYCODE
743 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c);
744 #endif
745 return mDNStrue;
746 }
747 }
748
749 #endif // USE_LIBIDN
750
751 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
752 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
AnswerLocalQuestionWithLocalAuthRecord(mDNS * const m,AuthRecord * rr,QC_result AddRecord)753 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
754 {
755 DNSQuestion *q = m->CurrentQuestion;
756 mDNSBool followcname;
757
758 if (!q)
759 {
760 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
761 return;
762 }
763
764 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
765
766 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
767 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
768 {
769 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
770 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
771 return;
772 }
773
774 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
775 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
776 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
777 if (q->QuestionCallback && !q->NoAnswer)
778 {
779 q->CurrentAnswers += AddRecord ? 1 : -1;
780 if (UniqueLocalOnlyRecord(rr))
781 {
782 if (!followcname || q->ReturnIntermed)
783 {
784 // Don't send this packet on the wire as we answered from /etc/hosts
785 q->ThisQInterval = 0;
786 q->LOAddressAnswers += AddRecord ? 1 : -1;
787 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
788 }
789 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
790 // The callback above could have caused the question to stop. Detect that
791 // using m->CurrentQuestion
792 if (followcname && m->CurrentQuestion == q)
793 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
794 return;
795 }
796 else
797 {
798 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
799 }
800 }
801 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
802 }
803
AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS * const m,AuthRecord * ar,QC_result AddRecord)804 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
805 {
806 if (m->CurrentQuestion)
807 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
808 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
809 m->CurrentQuestion = m->Questions;
810 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
811 {
812 mDNSBool answered;
813 DNSQuestion *q = m->CurrentQuestion;
814 if (RRAny(ar))
815 answered = AuthRecordAnswersQuestion(ar, q);
816 else
817 answered = LocalOnlyRecordAnswersQuestion(ar, q);
818 if (answered)
819 AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again
820 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
821 m->CurrentQuestion = q->next;
822 }
823 m->CurrentQuestion = mDNSNULL;
824 }
825
826 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
827 // delivers the appropriate add/remove events to listening questions:
828 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
829 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
830 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
831 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
832 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
833 //
834 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
835 // and by mDNS_Deregister_internal()
836
AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS * const m,AuthRecord * ar,QC_result AddRecord)837 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
838 {
839 if (m->CurrentQuestion)
840 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
841 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
842
843 m->CurrentQuestion = m->LocalOnlyQuestions;
844 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
845 {
846 mDNSBool answered;
847 DNSQuestion *q = m->CurrentQuestion;
848 // We are called with both LocalOnly/P2P record or a regular AuthRecord
849 if (RRAny(ar))
850 answered = AuthRecordAnswersQuestion(ar, q);
851 else
852 answered = LocalOnlyRecordAnswersQuestion(ar, q);
853 if (answered)
854 AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again
855 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
856 m->CurrentQuestion = q->next;
857 }
858
859 m->CurrentQuestion = mDNSNULL;
860
861 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
862 if (ar->ARType == AuthRecordLocalOnly || ar->ARType == AuthRecordP2P)
863 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, ar, AddRecord);
864
865 }
866
867 // ***************************************************************************
868 #if COMPILER_LIKES_PRAGMA_MARK
869 #pragma mark -
870 #pragma mark - Resource Record Utility Functions
871 #endif
872
873 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
874
ResourceRecordIsValidAnswer(const AuthRecord * const rr)875 mDNSlocal mDNSBool ResourceRecordIsValidAnswer(const AuthRecord *const rr)
876 {
877 if ((rr->resrec.RecordType & kDNSRecordTypeActiveMask) &&
878 ((rr->Additional1 == mDNSNULL) || (rr->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
879 ((rr->Additional2 == mDNSNULL) || (rr->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
880 ((rr->DependentOn == mDNSNULL) || (rr->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)))
881 {
882 return mDNStrue;
883 }
884 else
885 {
886 return mDNSfalse;
887 }
888 }
889
IsInterfaceValidForAuthRecord(const AuthRecord * const rr,const mDNSInterfaceID InterfaceID)890 mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *const rr, const mDNSInterfaceID InterfaceID)
891 {
892 if (rr->resrec.InterfaceID == mDNSInterface_Any)
893 {
894 return mDNSPlatformValidRecordForInterface(rr, InterfaceID);
895 }
896 else
897 {
898 return ((rr->resrec.InterfaceID == InterfaceID) ? mDNStrue : mDNSfalse);
899 }
900 }
901
ResourceRecordIsValidInterfaceAnswer(const AuthRecord * const rr,const mDNSInterfaceID interfaceID)902 mDNSlocal mDNSBool ResourceRecordIsValidInterfaceAnswer(const AuthRecord *const rr, const mDNSInterfaceID interfaceID)
903 {
904 return ((IsInterfaceValidForAuthRecord(rr, interfaceID) && ResourceRecordIsValidAnswer(rr)) ? mDNStrue : mDNSfalse);
905 }
906
907 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
908 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
909
910 // Parameters for handling probing conflicts
911 #define kMaxAllowedMCastProbingConflicts 1 // Maximum number of conflicts to allow from mcast messages.
912 #define kProbingConflictPauseDuration mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
913
914 // See RFC 6762: "8.3 Announcing"
915 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
916 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
917 #define InitialAnnounceCount ((mDNSu8)4)
918
919 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
920 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
921 // and then if the machine fails to wake, 3 goodbye packets).
922 #define GoodbyeCount ((mDNSu8)3)
923 #define WakeupCount ((mDNSu8)18)
924 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
925 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week
926
927 // Number of wakeups we send if WakeOnResolve is set in the question
928 #define InitialWakeOnResolveCount ((mDNSu8)3)
929
930 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
931 // This means that because the announce interval is doubled after sending the first packet, the first
932 // observed on-the-wire inter-packet interval between announcements is actually one second.
933 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
934 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
935 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
936 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
937
938 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
939 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
940 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
941
942 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
943 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
944 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
945
946 // Adjustment factor to avoid race condition (used for unicast cache entries) :
947 // 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.
948 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
949 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
950 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
951 // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
952 // the cached copy at our local caching server will already have expired, so the server will be forced
953 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
954
955 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
956 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
957
958 #define MaxUnansweredQueries 4
959
960 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
961 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
962 // TTL and rdata may differ.
963 // This is used for cache flush management:
964 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
965 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
966
967 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
968
969 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
970
SameResourceRecordNameClassInterface(const AuthRecord * const r1,const AuthRecord * const r2)971 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
972 {
973 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
974 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
975 if (r1->resrec.InterfaceID &&
976 r2->resrec.InterfaceID &&
977 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
978 return (mDNSBool)(
979 r1->resrec.rrclass == r2->resrec.rrclass &&
980 r1->resrec.namehash == r2->resrec.namehash &&
981 SameDomainName(r1->resrec.name, r2->resrec.name));
982 }
983
984 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
985 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
986 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
987 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
988 // so a response of any type should match, even if it is not actually the type the client plans to use.
989
990 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
991 // and require the rrtypes to match for the rdata to be considered potentially conflicting
PacketRRMatchesSignature(const CacheRecord * const pktrr,const AuthRecord * const authrr)992 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
993 {
994 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
995 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
996 if (pktrr->resrec.InterfaceID &&
997 authrr->resrec.InterfaceID &&
998 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
999 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
1000 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
1001 if ((authrr->resrec.InterfaceID == mDNSInterface_Any) &&
1002 !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse);
1003 return (mDNSBool)(
1004 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
1005 pktrr->resrec.namehash == authrr->resrec.namehash &&
1006 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
1007 }
1008
1009 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
1010 // This is the information that the requester believes to be correct.
1011 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
1012 // This is the information that we believe to be correct.
1013 // We've already determined that we plan to give this answer on this interface
1014 // (either the record is non-specific, or it is specific to this interface)
1015 // so now we just need to check the name, type, class, rdata and TTL.
ShouldSuppressKnownAnswer(const CacheRecord * const ka,const AuthRecord * const rr)1016 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
1017 {
1018 // If RR signature is different, or data is different, then don't suppress our answer
1019 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
1020
1021 // If the requester's indicated TTL is less than half the real TTL,
1022 // we need to give our answer before the requester's copy expires.
1023 // If the requester's indicated TTL is at least half the real TTL,
1024 // then we can suppress our answer this time.
1025 // If the requester's indicated TTL is greater than the TTL we believe,
1026 // then that's okay, and we don't need to do anything about it.
1027 // (If two responders on the network are offering the same information,
1028 // that's okay, and if they are offering the information with different TTLs,
1029 // the one offering the lower TTL should defer to the one offering the higher TTL.)
1030 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
1031 }
1032
SetNextAnnounceProbeTime(mDNS * const m,const AuthRecord * const rr)1033 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
1034 {
1035 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1036 {
1037 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
1038 {
1039 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
1040 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
1041 }
1042 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1043 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
1044 // Some defensive code:
1045 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1046 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1047 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1048 if (m->NextScheduledProbe - m->timenow < 0)
1049 m->NextScheduledProbe = m->timenow;
1050 }
1051 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
1052 {
1053 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1054 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
1055 }
1056 }
1057
InitializeLastAPTime(mDNS * const m,AuthRecord * const rr)1058 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
1059 {
1060 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1061 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
1062
1063 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1064 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1065 // records that are going to probe, then we delay its first announcement so that it will
1066 // go out synchronized with the first announcement for the other records that *are* probing.
1067 // This is a minor performance tweak that helps keep groups of related records synchronized together.
1068 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1069 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1070 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1071 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
1072 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1073
1074 if (rr->ProbeCount)
1075 {
1076 rr->ProbingConflictCount = 0;
1077 // If we have no probe suppression time set, or it is in the past, set it now
1078 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
1079 {
1080 // To allow us to aggregate probes when a group of services are registered together,
1081 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1082 // This means the common-case behaviour is:
1083 // randomized wait; probe
1084 // 1/4 second wait; probe
1085 // 1/4 second wait; probe
1086 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1087 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1088
1089 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1090 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
1091 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
1092 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
1093 m->SuppressProbes = m->timenow;
1094
1095 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1096 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
1097 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
1098 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
1099 m->SuppressProbes = m->timenow;
1100
1101 // except... don't expect to be able to send before the m->SuppressSending timer fires
1102 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
1103 m->SuppressProbes = NonZeroTime(m->SuppressSending);
1104
1105 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
1106 {
1107 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1108 m->SuppressProbes - m->timenow,
1109 m->NextScheduledProbe - m->timenow,
1110 m->NextScheduledQuery - m->timenow,
1111 m->SuppressSending,
1112 m->SuppressSending - m->timenow);
1113 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1114 }
1115 }
1116 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
1117 }
1118 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1119 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1120 else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0))
1121 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
1122 else
1123 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1124
1125 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1126 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1127 // After three probes one second apart with no answer, we conclude the client is now sleeping
1128 // and we can begin broadcasting our announcements to take over ownership of that IP address.
1129 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1130 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1131 if (rr->AddressProxy.type)
1132 rr->LastAPTime = m->timenow;
1133
1134 // Set LastMCTime to now, to inhibit multicast responses
1135 // (no need to send additional multicast responses when we're announcing anyway)
1136 rr->LastMCTime = m->timenow;
1137 rr->LastMCInterface = mDNSInterfaceMark;
1138
1139 SetNextAnnounceProbeTime(m, rr);
1140 }
1141
SetUnicastTargetToHostName(mDNS * const m,AuthRecord * rr)1142 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
1143 {
1144 const domainname *target;
1145 if (rr->AutoTarget)
1146 {
1147 rr->AutoTarget = Target_AutoHostAndNATMAP;
1148 }
1149
1150 target = GetServiceTarget(m, rr);
1151 if (!target || target->c[0] == 0)
1152 {
1153 // defer registration until we've got a target
1154 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
1155 rr->state = regState_NoTarget;
1156 return mDNSNULL;
1157 }
1158 else
1159 {
1160 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
1161 return target;
1162 }
1163 }
1164
1165 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
AuthRecordIncludesOrIsAWDL(const AuthRecord * const ar)1166 mDNSlocal mDNSBool AuthRecordIncludesOrIsAWDL(const AuthRecord *const ar)
1167 {
1168 return ((AuthRecordIncludesAWDL(ar) || mDNSPlatformInterfaceIsAWDL(ar->resrec.InterfaceID)) ? mDNStrue : mDNSfalse);
1169 }
1170 #endif
1171
1172 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1173 // Eventually we should unify this with GetServiceTarget() in uDNS.c
SetTargetToHostName(mDNS * const m,AuthRecord * const rr)1174 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
1175 {
1176 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
1177 const domainname *newname;
1178
1179 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1180 if (AuthRecordIncludesOrIsAWDL(rr))
1181 {
1182 newname = &m->RandomizedHostname;
1183 }
1184 else
1185 #endif
1186 {
1187 newname = &m->MulticastHostname;
1188 }
1189 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
1190
1191 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
1192 {
1193 const domainname *const n = SetUnicastTargetToHostName(m, rr);
1194 if (n) newname = n;
1195 else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
1196 }
1197
1198 if (target && SameDomainName(target, newname))
1199 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
1200
1201 if (target && !SameDomainName(target, newname))
1202 {
1203 AssignDomainName(target, newname);
1204 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
1205
1206 // If we're in the middle of probing this record, we need to start again,
1207 // because changing its rdata may change the outcome of the tie-breaker.
1208 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1209 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1210
1211 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1212 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1213 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1214 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
1215 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1216 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1217
1218 rr->AnnounceCount = InitialAnnounceCount;
1219 rr->RequireGoodbye = mDNSfalse;
1220 rr->ProbeRestartCount = 0;
1221 InitializeLastAPTime(m, rr);
1222 }
1223 }
1224
AcknowledgeRecord(mDNS * const m,AuthRecord * const rr)1225 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
1226 {
1227 if (rr->RecordCallback)
1228 {
1229 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1230 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1231 rr->Acknowledged = mDNStrue;
1232 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1233 rr->RecordCallback(m, rr, mStatus_NoError);
1234 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1235 }
1236 }
1237
ActivateUnicastRegistration(mDNS * const m,AuthRecord * const rr)1238 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
1239 {
1240 // Make sure that we don't activate the SRV record and associated service records, if it is in
1241 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1242 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1243 // the target becomes available, the records will be reregistered.
1244 if (rr->resrec.rrtype != kDNSType_SRV)
1245 {
1246 AuthRecord *srvRR = mDNSNULL;
1247 if (rr->resrec.rrtype == kDNSType_PTR)
1248 srvRR = rr->Additional1;
1249 else if (rr->resrec.rrtype == kDNSType_TXT)
1250 srvRR = rr->DependentOn;
1251 if (srvRR)
1252 {
1253 if (srvRR->resrec.rrtype != kDNSType_SRV)
1254 {
1255 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1256 }
1257 else
1258 {
1259 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1260 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1261 rr->state = srvRR->state;
1262 }
1263 }
1264 }
1265
1266 if (rr->state == regState_NoTarget)
1267 {
1268 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1269 return;
1270 }
1271 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1272 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1273 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1274 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1275 // 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.
1276 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1277 {
1278 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1279 rr->state = regState_DeregPending;
1280 }
1281 else
1282 {
1283 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1284 rr->state = regState_Pending;
1285 }
1286 rr->ProbingConflictCount = 0;
1287 rr->LastConflictPktNum = 0;
1288 rr->ProbeRestartCount = 0;
1289 rr->ProbeCount = 0;
1290 rr->AnnounceCount = 0;
1291 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1292 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1293 rr->expire = 0; // Forget about all the leases, start fresh
1294 rr->uselease = mDNStrue;
1295 rr->updateid = zeroID;
1296 rr->SRVChanged = mDNSfalse;
1297 rr->updateError = mStatus_NoError;
1298 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1299 // The records might already be registered with the server and hence could have NAT state.
1300 if (rr->NATinfo.clientContext)
1301 {
1302 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1303 rr->NATinfo.clientContext = mDNSNULL;
1304 }
1305 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1306 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1307 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1308 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1309 }
1310
1311 // Two records qualify to be local duplicates if:
1312 // (a) the RecordTypes are the same, or
1313 // (b) one is Unique and the other Verified
1314 // (c) either is in the process of deregistering
1315 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1316 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1317 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1318
1319 #define RecordIsLocalDuplicate(A,B) \
1320 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1321
CheckAuthIdenticalRecord(AuthHash * r,AuthRecord * rr)1322 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1323 {
1324 const AuthGroup *a;
1325 AuthRecord *rp;
1326
1327 a = AuthGroupForRecord(r, &rr->resrec);
1328 if (!a) return mDNSNULL;
1329 rp = a->members;
1330 while (rp)
1331 {
1332 if (!RecordIsLocalDuplicate(rp, rr))
1333 rp = rp->next;
1334 else
1335 {
1336 if (rp->resrec.RecordType == kDNSRecordTypeDeregistering)
1337 {
1338 rp->AnnounceCount = 0;
1339 rp = rp->next;
1340 }
1341 else return rp;
1342 }
1343 }
1344 return (mDNSNULL);
1345 }
1346
CheckAuthRecordConflict(AuthHash * r,AuthRecord * rr)1347 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1348 {
1349 const AuthGroup *a;
1350 const AuthRecord *rp;
1351
1352 a = AuthGroupForRecord(r, &rr->resrec);
1353 if (!a) return mDNSfalse;
1354 rp = a->members;
1355 while (rp)
1356 {
1357 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1358 const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp;
1359 if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec))
1360 return mDNStrue;
1361 else
1362 rp = rp->next;
1363 }
1364 return (mDNSfalse);
1365 }
1366
1367 // checks to see if "rr" is already present
CheckAuthSameRecord(AuthHash * r,AuthRecord * rr)1368 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1369 {
1370 const AuthGroup *a;
1371 AuthRecord *rp;
1372
1373 a = AuthGroupForRecord(r, &rr->resrec);
1374 if (!a) return mDNSNULL;
1375 rp = a->members;
1376 while (rp)
1377 {
1378 if (rp != rr)
1379 rp = rp->next;
1380 else
1381 {
1382 return rp;
1383 }
1384 }
1385 return (mDNSNULL);
1386 }
1387
DecrementAutoTargetServices(mDNS * const m,AuthRecord * const rr)1388 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1389 {
1390 if (RRLocalOnly(rr))
1391 {
1392 // A sanity check, this should be prevented in calling code.
1393 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1394 return;
1395 }
1396
1397 if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1398 {
1399 NetworkInterfaceInfo *intf;
1400 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1401 DeadvertiseFlags flags = 0; // DeadvertiseFlags for non-AWDL interfaces.
1402 DeadvertiseFlags flagsAWDL = 0; // DeadvertiseFlags for AWDL interfaces.
1403 if (AuthRecordIncludesOrIsAWDL(rr))
1404 {
1405 if (AuthRecordIncludesAWDL(rr))
1406 {
1407 m->AutoTargetAWDLIncludedCount--;
1408 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1409 "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1410 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1411 if (m->AutoTargetAWDLIncludedCount == 0)
1412 {
1413 flags |= kDeadvertiseFlag_RandHostname;
1414 if (m->AutoTargetAWDLOnlyCount == 0) flagsAWDL |= kDeadvertiseFlag_RandHostname;
1415 }
1416 }
1417 else
1418 {
1419 m->AutoTargetAWDLOnlyCount--;
1420 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1421 "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1422 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1423 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1424 {
1425 flagsAWDL |= kDeadvertiseFlag_RandHostname;
1426 }
1427 }
1428 if (flags || flagsAWDL)
1429 {
1430 for (intf = m->HostInterfaces; intf; intf = intf->next)
1431 {
1432 if (!intf->Advertise) continue;
1433 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID))
1434 {
1435 if (flagsAWDL) DeadvertiseInterface(m, intf, flagsAWDL);
1436 }
1437 else
1438 {
1439 if (flags) DeadvertiseInterface(m, intf, flags);
1440 }
1441 }
1442 }
1443 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1444 {
1445 GetRandomUUIDLocalHostname(&m->RandomizedHostname);
1446 }
1447 }
1448 else
1449 #endif
1450 {
1451 m->AutoTargetServices--;
1452 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1453 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1454 m->AutoTargetServices, ARDisplayString(m, rr));
1455 if (m->AutoTargetServices == 0)
1456 {
1457 for (intf = m->HostInterfaces; intf; intf = intf->next)
1458 {
1459 if (intf->Advertise) DeadvertiseInterface(m, intf, kDeadvertiseFlag_NormalHostname);
1460 }
1461 }
1462 }
1463 }
1464
1465 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1466 if (!AuthRecord_uDNS(rr))
1467 {
1468 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1469 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
1470 m->NumAllInterfaceRecords--;
1471 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1472 "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1473 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1474 }
1475 #endif
1476 }
1477
AdvertiseNecessaryInterfaceRecords(mDNS * const m)1478 mDNSlocal void AdvertiseNecessaryInterfaceRecords(mDNS *const m)
1479 {
1480 NetworkInterfaceInfo *intf;
1481 for (intf = m->HostInterfaces; intf; intf = intf->next)
1482 {
1483 if (intf->Advertise) AdvertiseInterfaceIfNeeded(m, intf);
1484 }
1485 }
1486
IncrementAutoTargetServices(mDNS * const m,AuthRecord * const rr)1487 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1488 {
1489 mDNSBool enablingBonjour = mDNSfalse;
1490
1491 if (RRLocalOnly(rr))
1492 {
1493 // A sanity check, this should be prevented in calling code.
1494 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1495 return;
1496 }
1497
1498 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1499 if (!AuthRecord_uDNS(rr))
1500 {
1501 m->NumAllInterfaceRecords++;
1502 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1503 "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1504 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1505 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1506 {
1507 m->NextBonjourDisableTime = 0;
1508 if (m->BonjourEnabled == 0)
1509 {
1510 // Enable Bonjour immediately by scheduling network changed processing where
1511 // we will join the multicast group on each active interface.
1512 m->BonjourEnabled = 1;
1513 enablingBonjour = mDNStrue;
1514 m->NetworkChanged = m->timenow;
1515 }
1516 }
1517 }
1518 #endif
1519
1520 if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1521 {
1522 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1523 if (AuthRecordIncludesAWDL(rr))
1524 {
1525 m->AutoTargetAWDLIncludedCount++;
1526 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1527 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1528 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1529 }
1530 else if (mDNSPlatformInterfaceIsAWDL(rr->resrec.InterfaceID))
1531 {
1532 m->AutoTargetAWDLOnlyCount++;
1533 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1534 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1535 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1536 }
1537 else
1538 #endif
1539 {
1540 m->AutoTargetServices++;
1541 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1542 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1543 m->AutoTargetServices, ARDisplayString(m, rr));
1544 }
1545 // If this is the first advertised service and we did not just enable Bonjour above, then
1546 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1547 // be advertised during the network changed processing scheduled above, so no need
1548 // to do it here.
1549 if (!enablingBonjour) AdvertiseNecessaryInterfaceRecords(m);
1550 }
1551 }
1552
getKeepaliveRaddr(mDNS * const m,AuthRecord * rr,mDNSAddr * raddr)1553 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1554 {
1555 mDNSAddr laddr = zeroAddr;
1556 mDNSEthAddr eth = zeroEthAddr;
1557 mDNSIPPort lport = zeroIPPort;
1558 mDNSIPPort rport = zeroIPPort;
1559 mDNSu32 timeout = 0;
1560 mDNSu32 seq = 0;
1561 mDNSu32 ack = 0;
1562 mDNSu16 win = 0;
1563
1564 if (mDNS_KeepaliveRecord(&rr->resrec))
1565 {
1566 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, ð, &seq, &ack, &lport, &rport, &win);
1567 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1568 {
1569 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1570 return;
1571 }
1572 }
1573 }
1574
1575 // Exported so uDNS.c can call this
mDNS_Register_internal(mDNS * const m,AuthRecord * const rr)1576 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1577 {
1578 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1579 AuthRecord *r;
1580 AuthRecord **p = &m->ResourceRecords;
1581 AuthRecord **d = &m->DuplicateRecords;
1582
1583 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1584 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1585
1586 if (!rr->resrec.RecordType)
1587 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1588
1589 if (m->ShutdownTime)
1590 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1591
1592 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1593 {
1594 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1595 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1596 {
1597 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1598 rr->ARType = AuthRecordLocalOnly;
1599 }
1600 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1601 {
1602 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1603 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1604 }
1605 if (rr->resrec.InterfaceID != previousID)
1606 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1607 }
1608
1609 if (RRLocalOnly(rr))
1610 {
1611 if (CheckAuthSameRecord(&m->rrauth, rr))
1612 {
1613 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1614 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1615 return(mStatus_AlreadyRegistered);
1616 }
1617 }
1618 else
1619 {
1620 while (*p && *p != rr) p=&(*p)->next;
1621 if (*p)
1622 {
1623 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1624 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1625 return(mStatus_AlreadyRegistered);
1626 }
1627 }
1628
1629 while (*d && *d != rr) d=&(*d)->next;
1630 if (*d)
1631 {
1632 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1633 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1634 return(mStatus_AlreadyRegistered);
1635 }
1636
1637 if (rr->DependentOn)
1638 {
1639 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1640 rr->resrec.RecordType = kDNSRecordTypeVerified;
1641 else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique)
1642 {
1643 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1644 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1645 return(mStatus_Invalid);
1646 }
1647 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1648 {
1649 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1650 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1651 return(mStatus_Invalid);
1652 }
1653 }
1654
1655 rr->next = mDNSNULL;
1656
1657 // Field Group 1: The actual information pertaining to this resource record
1658 // Set up by client prior to call
1659
1660 // Field Group 2: Persistent metadata for Authoritative Records
1661 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1662 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1663 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1664 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1665 // rr->Callback = already set in mDNS_SetupResourceRecord
1666 // rr->Context = already set in mDNS_SetupResourceRecord
1667 // rr->RecordType = already set in mDNS_SetupResourceRecord
1668 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1669 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1670 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1671 if (rr->AutoTarget && target) target->c[0] = 0;
1672
1673 // Field Group 3: Transient state for Authoritative Records
1674 rr->Acknowledged = mDNSfalse;
1675 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1676 rr->ProbeRestartCount = 0;
1677 rr->AnnounceCount = InitialAnnounceCount;
1678 rr->RequireGoodbye = mDNSfalse;
1679 rr->AnsweredLocalQ = mDNSfalse;
1680 rr->IncludeInProbe = mDNSfalse;
1681 rr->ImmedUnicast = mDNSfalse;
1682 rr->SendNSECNow = mDNSNULL;
1683 rr->ImmedAnswer = mDNSNULL;
1684 rr->ImmedAdditional = mDNSNULL;
1685 rr->SendRNow = mDNSNULL;
1686 rr->v4Requester = zerov4Addr;
1687 rr->v6Requester = zerov6Addr;
1688 rr->NextResponse = mDNSNULL;
1689 rr->NR_AnswerTo = mDNSNULL;
1690 rr->NR_AdditionalTo = mDNSNULL;
1691 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1692 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1693 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1694 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1695 rr->NewRData = mDNSNULL;
1696 rr->newrdlength = 0;
1697 rr->UpdateCallback = mDNSNULL;
1698 rr->UpdateCredits = kMaxUpdateCredits;
1699 rr->NextUpdateCredit = 0;
1700 rr->UpdateBlocked = 0;
1701
1702 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1703 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1704
1705 // Field Group 4: Transient uDNS state for Authoritative Records
1706 rr->state = regState_Zero;
1707 rr->uselease = 0;
1708 rr->expire = 0;
1709 rr->Private = 0;
1710 rr->updateid = zeroID;
1711 rr->updateIntID = zeroOpaque64;
1712 rr->zone = rr->resrec.name;
1713 rr->nta = mDNSNULL;
1714 rr->tcp = mDNSNULL;
1715 rr->OrigRData = 0;
1716 rr->OrigRDLen = 0;
1717 rr->InFlightRData = 0;
1718 rr->InFlightRDLen = 0;
1719 rr->QueuedRData = 0;
1720 rr->QueuedRDLen = 0;
1721 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1722 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1723 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1724 // times with different values if the external NAT port changes during the lifetime of the service registration.
1725 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1726
1727 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1728 // rr->resrec.name->c = MUST be set by client
1729 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1730 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1731 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1732 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1733
1734 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1735 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1736 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1737 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1738
1739 if (rr->AutoTarget)
1740 {
1741 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1742 #ifndef UNICAST_DISABLED
1743 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1744 // 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.
1745 if (rr->state == regState_NoTarget)
1746 {
1747 // Initialize the target so that we don't crash while logging etc.
1748 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1749 if (tar) tar->c[0] = 0;
1750 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1751 }
1752 #endif
1753 }
1754 else
1755 {
1756 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1757 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1758 }
1759
1760 if (!ValidateDomainName(rr->resrec.name))
1761 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1762
1763 // Don't do this until *after* we've set rr->resrec.rdlength
1764 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1765 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1766
1767 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1768 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1769
1770 if (RRLocalOnly(rr))
1771 {
1772 // If this is supposed to be unique, make sure we don't have any name conflicts.
1773 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1774 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1775 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1776 // Hence, just bail out.
1777 // This comment is doesn’t make any sense. -- SC
1778 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1779 {
1780 if (CheckAuthRecordConflict(&m->rrauth, rr))
1781 {
1782 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1783 return mStatus_NameConflict;
1784 }
1785 }
1786 }
1787
1788 // For uDNS records, we don't support duplicate checks at this time.
1789 #ifndef UNICAST_DISABLED
1790 if (AuthRecord_uDNS(rr))
1791 {
1792 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1793 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1794 // 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.
1795 while (*p) p=&(*p)->next;
1796 *p = rr;
1797 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1798 rr->ProbeCount = 0;
1799 rr->ProbeRestartCount = 0;
1800 rr->AnnounceCount = 0;
1801 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1802 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1803 }
1804 #endif
1805
1806 // Now that we've finished building our new record, make sure it's not identical to one we already have
1807 if (RRLocalOnly(rr))
1808 {
1809 rr->ProbeCount = 0;
1810 rr->ProbeRestartCount = 0;
1811 rr->AnnounceCount = 0;
1812 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1813 }
1814 else
1815 {
1816 for (r = m->ResourceRecords; r; r=r->next)
1817 if (RecordIsLocalDuplicate(r, rr))
1818 {
1819 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1820 else break;
1821 }
1822 }
1823
1824 if (r)
1825 {
1826 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr));
1827 *d = rr;
1828 // If the previous copy of this record is already verified unique,
1829 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1830 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1831 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1832 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1833 rr->ProbeCount = 0;
1834 }
1835 else
1836 {
1837 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1838 if (RRLocalOnly(rr))
1839 {
1840 AuthGroup *ag;
1841 ag = InsertAuthRecord(m, &m->rrauth, rr);
1842 if (ag && !ag->NewLocalOnlyRecords)
1843 {
1844 m->NewLocalOnlyRecords = mDNStrue;
1845 ag->NewLocalOnlyRecords = rr;
1846 }
1847 // No probing for LocalOnly records; acknowledge them right away
1848 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1849 AcknowledgeRecord(m, rr);
1850 return(mStatus_NoError);
1851 }
1852 else
1853 {
1854 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1855 *p = rr;
1856 }
1857 }
1858
1859 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1860 {
1861 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1862 IncrementAutoTargetServices(m, rr);
1863
1864 // For records that are not going to probe, acknowledge them right away
1865 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1866 AcknowledgeRecord(m, rr);
1867
1868 // Adding a record may affect whether or not we should sleep
1869 mDNS_UpdateAllowSleep(m);
1870 }
1871
1872 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1873 // This is used by the in-NIC proxy to send the keepalive packets.
1874 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1875 {
1876 mDNSAddr raddr;
1877 // Set the record type to known unique to prevent probing keep alive records.
1878 // Also make sure we do not announce the keepalive records.
1879 rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1880 rr->AnnounceCount = 0;
1881 getKeepaliveRaddr(m, rr, &raddr);
1882 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1883 // asynchronous task to update the resource record
1884 mDNSPlatformGetRemoteMacAddr(&raddr);
1885 }
1886
1887 return(mStatus_NoError);
1888 }
1889
RecordProbeFailure(mDNS * const m,const AuthRecord * const rr)1890 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1891 {
1892 m->ProbeFailTime = m->timenow;
1893 m->NumFailedProbes++;
1894 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1895 // If a bunch of hosts have all been configured with the same name, then they'll all
1896 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1897 // up to name-10. After that they'll start adding random increments in the range 1-100,
1898 // so they're more likely to branch out in the available namespace and settle on a set of
1899 // unique names quickly. If after five more tries the host is still conflicting, then we
1900 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1901 if (m->NumFailedProbes >= 15)
1902 {
1903 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1904 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1905 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1906 }
1907 }
1908
CompleteRDataUpdate(mDNS * const m,AuthRecord * const rr)1909 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1910 {
1911 RData *OldRData = rr->resrec.rdata;
1912 mDNSu16 OldRDLen = rr->resrec.rdlength;
1913 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1914 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1915 if (rr->UpdateCallback)
1916 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1917 }
1918
1919 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1920 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1921 // Exported so uDNS.c can call this
mDNS_Deregister_internal(mDNS * const m,AuthRecord * const rr,mDNS_Dereg_type drt)1922 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1923 {
1924 AuthRecord *r2;
1925 mDNSu8 RecordType = rr->resrec.RecordType;
1926 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1927 mDNSBool dupList = mDNSfalse;
1928
1929 if (RRLocalOnly(rr))
1930 {
1931 AuthGroup *a;
1932 AuthRecord **rp;
1933
1934 a = AuthGroupForRecord(&m->rrauth, &rr->resrec);
1935 if (!a) return mDNSfalse;
1936 rp = &a->members;
1937 while (*rp && *rp != rr) rp=&(*rp)->next;
1938 p = rp;
1939 }
1940 else
1941 {
1942 while (*p && *p != rr) p=&(*p)->next;
1943 }
1944
1945 if (*p)
1946 {
1947 // We found our record on the main list. See if there are any duplicates that need special handling.
1948 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1949 {
1950 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1951 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1952 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1953 }
1954 else
1955 {
1956 // Before we delete the record (and potentially send a goodbye packet)
1957 // first see if we have a record on the duplicate list ready to take over from it.
1958 AuthRecord **d = &m->DuplicateRecords;
1959 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1960 if (*d)
1961 {
1962 AuthRecord *dup = *d;
1963 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1964 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1965 *d = dup->next; // Cut replacement record from DuplicateRecords list
1966 if (RRLocalOnly(rr))
1967 {
1968 dup->next = mDNSNULL;
1969 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1970 }
1971 else
1972 {
1973 dup->next = rr->next; // And then...
1974 rr->next = dup; // ... splice it in right after the record we're about to delete
1975 }
1976 dup->resrec.RecordType = rr->resrec.RecordType;
1977 dup->ProbeCount = rr->ProbeCount;
1978 dup->ProbeRestartCount = rr->ProbeRestartCount;
1979 dup->AnnounceCount = rr->AnnounceCount;
1980 dup->RequireGoodbye = rr->RequireGoodbye;
1981 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1982 dup->ImmedAnswer = rr->ImmedAnswer;
1983 dup->ImmedUnicast = rr->ImmedUnicast;
1984 dup->ImmedAdditional = rr->ImmedAdditional;
1985 dup->v4Requester = rr->v4Requester;
1986 dup->v6Requester = rr->v6Requester;
1987 dup->ThisAPInterval = rr->ThisAPInterval;
1988 dup->LastAPTime = rr->LastAPTime;
1989 dup->LastMCTime = rr->LastMCTime;
1990 dup->LastMCInterface = rr->LastMCInterface;
1991 dup->Private = rr->Private;
1992 dup->state = rr->state;
1993 rr->RequireGoodbye = mDNSfalse;
1994 rr->AnsweredLocalQ = mDNSfalse;
1995 }
1996 }
1997 }
1998 else
1999 {
2000 // We didn't find our record on the main list; try the DuplicateRecords list instead.
2001 p = &m->DuplicateRecords;
2002 while (*p && *p != rr) p=&(*p)->next;
2003 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2004 if (*p)
2005 {
2006 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
2007 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
2008 // also that have been marked above in this function. In that case, we come here and if we don't
2009 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
2010 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
2011 // details.
2012 rr->WakeUp.HMAC = zeroEthAddr;
2013 rr->RequireGoodbye = mDNSfalse;
2014 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2015 dupList = mDNStrue;
2016 }
2017 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
2018 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2019 }
2020
2021 if (!*p)
2022 {
2023 // No need to log an error message if we already know this is a potentially repeated deregistration
2024 if (drt != mDNS_Dereg_repeat)
2025 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
2026 return(mStatus_BadReferenceErr);
2027 }
2028
2029 // If this is a shared record and we've announced it at least once,
2030 // we need to retract that announcement before we delete the record
2031
2032 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2033 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2034 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2035 // mechanism to cope with the client callback modifying the question list while that's happening.
2036 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2037 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2038 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2039 // records, thereby invoking yet more callbacks, without limit.
2040 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2041 // actual goodbye packets.
2042
2043 #ifndef UNICAST_DISABLED
2044 if (AuthRecord_uDNS(rr))
2045 {
2046 if (rr->RequireGoodbye)
2047 {
2048 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2049 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2050 m->LocalRemoveEvents = mDNStrue;
2051 uDNS_DeregisterRecord(m, rr);
2052 // At this point unconditionally we bail out
2053 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2054 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2055 // process and will complete asynchronously. Either way we don't need to do anything more here.
2056 return(mStatus_NoError);
2057 }
2058 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2059 // from the server. In that case, if the records have been part of a group update, clear the
2060 // state here.
2061 rr->updateid = zeroID;
2062
2063 // We defer cleaning up NAT state only after sending goodbyes. This is important because
2064 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2065 // This happens today when we turn on/off interface where we get multiple network transitions
2066 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2067 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2068 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2069 // NAT state here takes care of the case where we did not send goodbyes at all.
2070 if (rr->NATinfo.clientContext)
2071 {
2072 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2073 rr->NATinfo.clientContext = mDNSNULL;
2074 }
2075 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
2076 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2077 }
2078 #endif // UNICAST_DISABLED
2079
2080 if (RecordType == kDNSRecordTypeUnregistered)
2081 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
2082 else if (RecordType == kDNSRecordTypeDeregistering)
2083 {
2084 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
2085 return(mStatus_BadReferenceErr);
2086 }
2087
2088 if (rr->WakeUp.HMAC.l[0] ||
2089 (((RecordType == kDNSRecordTypeShared) || (rr->ARType == AuthRecordLocalOnly)) &&
2090 (rr->RequireGoodbye || rr->AnsweredLocalQ)))
2091 {
2092 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
2093 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2094 rr->resrec.rroriginalttl = 0;
2095 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
2096 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
2097 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
2098 m->LocalRemoveEvents = mDNStrue;
2099 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
2100 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
2101 }
2102 else
2103 {
2104 if (!dupList && RRLocalOnly(rr))
2105 {
2106 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
2107 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
2108 }
2109 else
2110 {
2111 *p = rr->next; // Cut this record from the list
2112 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
2113 DecrementAutoTargetServices(m, rr);
2114 }
2115 // If someone is about to look at this, bump the pointer forward
2116 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
2117 rr->next = mDNSNULL;
2118
2119 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
2120 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
2121
2122 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
2123 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2124 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2125
2126 // If we have an update queued up which never executed, give the client a chance to free that memory
2127 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
2128
2129
2130 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2131 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2132 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2133 // so any attempt to touch rr after this is likely to lead to a crash.
2134 if (drt != mDNS_Dereg_conflict)
2135 {
2136 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2137 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr));
2138 if (rr->RecordCallback)
2139 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
2140 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2141 }
2142 else
2143 {
2144 RecordProbeFailure(m, rr);
2145 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2146 if (rr->RecordCallback)
2147 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
2148 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2149 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2150 // Note that with all the client callbacks going on, by the time we get here all the
2151 // records we marked may have been explicitly deregistered by the client anyway.
2152 r2 = m->DuplicateRecords;
2153 while (r2)
2154 {
2155 if (r2->ProbeCount != 0xFF)
2156 {
2157 r2 = r2->next;
2158 }
2159 else
2160 {
2161 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2162 // See if this record was also registered with any D2D plugins.
2163 D2D_stop_advertising_record(r2);
2164 #endif
2165 mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
2166 // As this is a duplicate record, it will be unlinked from the list
2167 // immediately
2168 r2 = m->DuplicateRecords;
2169 }
2170 }
2171 }
2172 }
2173 mDNS_UpdateAllowSleep(m);
2174 return(mStatus_NoError);
2175 }
2176
2177 // ***************************************************************************
2178 #if COMPILER_LIKES_PRAGMA_MARK
2179 #pragma mark -
2180 #pragma mark - Packet Sending Functions
2181 #endif
2182
AddRecordToResponseList(AuthRecord *** nrpp,AuthRecord * rr,AuthRecord * add)2183 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
2184 {
2185 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
2186 {
2187 **nrpp = rr;
2188 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2189 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2190 // The referenced record will definitely be acceptable (by recursive application of this rule)
2191 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
2192 rr->NR_AdditionalTo = add;
2193 *nrpp = &rr->NextResponse;
2194 }
2195 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2196 }
2197
AddRRSetAdditionalsToResponseList(mDNS * const m,AuthRecord *** nrpp,AuthRecord * rr,AuthRecord * additional,const mDNSInterfaceID InterfaceID)2198 mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID)
2199 {
2200 AuthRecord *rr2;
2201 if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask)
2202 {
2203 for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next)
2204 {
2205 if ((rr2->resrec.namehash == additional->resrec.namehash) &&
2206 (rr2->resrec.rrtype == additional->resrec.rrtype) &&
2207 (rr2 != additional) &&
2208 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) &&
2209 (rr2->resrec.rrclass == additional->resrec.rrclass) &&
2210 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&
2211 SameDomainName(rr2->resrec.name, additional->resrec.name))
2212 {
2213 AddRecordToResponseList(nrpp, rr2, rr);
2214 }
2215 }
2216 }
2217 }
2218
AddAdditionalsToResponseList(mDNS * const m,AuthRecord * ResponseRecords,AuthRecord *** nrpp,const mDNSInterfaceID InterfaceID)2219 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
2220 {
2221 AuthRecord *rr, *rr2;
2222 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
2223 {
2224 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2225 // later in the "for" loop, and we will follow further "additional" links then.)
2226 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
2227 {
2228 AddRecordToResponseList(nrpp, rr->Additional1, rr);
2229 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID);
2230 }
2231
2232 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
2233 {
2234 AddRecordToResponseList(nrpp, rr->Additional2, rr);
2235 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID);
2236 }
2237
2238 // For SRV records, automatically add the Address record(s) for the target host
2239 if (rr->resrec.rrtype == kDNSType_SRV)
2240 {
2241 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2242 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2243 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2244 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
2245 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
2246 AddRecordToResponseList(nrpp, rr2, rr);
2247 }
2248 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
2249 {
2250 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2251 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2252 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2253 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
2254 SameDomainName(rr->resrec.name, rr2->resrec.name))
2255 AddRecordToResponseList(nrpp, rr2, rr);
2256 }
2257 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
2258 {
2259 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
2260 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2261 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
2262 }
2263 }
2264 }
2265
SendDelayedUnicastResponse(mDNS * const m,const mDNSAddr * const dest,const mDNSInterfaceID InterfaceID)2266 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
2267 {
2268 AuthRecord *rr;
2269 AuthRecord *ResponseRecords = mDNSNULL;
2270 AuthRecord **nrp = &ResponseRecords;
2271 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2272
2273 // Make a list of all our records that need to be unicast to this destination
2274 for (rr = m->ResourceRecords; rr; rr=rr->next)
2275 {
2276 // If we find we can no longer unicast this answer, clear ImmedUnicast
2277 if (rr->ImmedAnswer == mDNSInterfaceMark ||
2278 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
2279 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
2280 rr->ImmedUnicast = mDNSfalse;
2281
2282 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
2283 {
2284 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
2285 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
2286 {
2287 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
2288 rr->ImmedUnicast = mDNSfalse;
2289 rr->v4Requester = zerov4Addr;
2290 rr->v6Requester = zerov6Addr;
2291
2292 // Only sent records registered for P2P over P2P interfaces
2293 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))
2294 {
2295 continue;
2296 }
2297
2298 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
2299 {
2300 rr->NR_AnswerTo = NR_AnswerMulticast;
2301 *nrp = rr;
2302 nrp = &rr->NextResponse;
2303 }
2304 }
2305 }
2306 }
2307
2308 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
2309
2310 while (ResponseRecords)
2311 {
2312 mDNSu8 *responseptr = m->omsg.data;
2313 mDNSu8 *newptr;
2314 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2315
2316 // Put answers in the packet
2317 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
2318 {
2319 rr = ResponseRecords;
2320 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2321 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2322
2323 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
2324
2325 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2326 if (!newptr && m->omsg.h.numAnswers)
2327 {
2328 break; // If packet full, send it now
2329 }
2330 if (newptr) responseptr = newptr;
2331 ResponseRecords = rr->NextResponse;
2332 rr->NextResponse = mDNSNULL;
2333 rr->NR_AnswerTo = mDNSNULL;
2334 rr->NR_AdditionalTo = mDNSNULL;
2335 rr->RequireGoodbye = mDNStrue;
2336 }
2337
2338 // Add additionals, if there's space
2339 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2340 {
2341 rr = ResponseRecords;
2342 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2343 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2344 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2345 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2346
2347 if (newptr) responseptr = newptr;
2348 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2349 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2350 ResponseRecords = rr->NextResponse;
2351 rr->NextResponse = mDNSNULL;
2352 rr->NR_AnswerTo = mDNSNULL;
2353 rr->NR_AdditionalTo = mDNSNULL;
2354 }
2355
2356 if (m->omsg.h.numAnswers)
2357 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSfalse);
2358 }
2359 }
2360
2361 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2362 // and the client's mStatus_MemFree callback will have been invoked
CompleteDeregistration(mDNS * const m,AuthRecord * rr)2363 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2364 {
2365 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2366 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2367 // it should go ahead and immediately dispose of this registration
2368 rr->resrec.RecordType = kDNSRecordTypeShared;
2369 rr->RequireGoodbye = mDNSfalse;
2370 rr->WakeUp.HMAC = zeroEthAddr;
2371 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; }
2372 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
2373 }
2374
2375 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2376 // any deregistering records that remain in the m->ResourceRecords list.
2377 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2378 // which may change the record list and/or question list.
2379 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
DiscardDeregistrations(mDNS * const m)2380 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2381 {
2382 if (m->CurrentRecord)
2383 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2384 m->CurrentRecord = m->ResourceRecords;
2385
2386 while (m->CurrentRecord)
2387 {
2388 AuthRecord *rr = m->CurrentRecord;
2389 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2390 CompleteDeregistration(m, rr); // Don't touch rr after this
2391 else
2392 m->CurrentRecord = rr->next;
2393 }
2394 }
2395
GetLabelDecimalValue(const mDNSu8 * const src,mDNSu8 * dst)2396 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2397 {
2398 int i, val = 0;
2399 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2400 for (i=1; i<=src[0]; i++)
2401 {
2402 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2403 val = val * 10 + src[i] - '0';
2404 }
2405 if (val > 255) return(mStatus_Invalid);
2406 *dst = (mDNSu8)val;
2407 return(mStatus_NoError);
2408 }
2409
GetIPv4FromName(mDNSAddr * const a,const domainname * const name)2410 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2411 {
2412 int skip = CountLabels(name) - 6;
2413 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2414 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2415 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2416 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2417 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2418 a->type = mDNSAddrType_IPv4;
2419 return(mStatus_NoError);
2420 }
2421
2422 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2423 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2424 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2425
GetIPv6FromName(mDNSAddr * const a,const domainname * const name)2426 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2427 {
2428 int i, h, l;
2429 const domainname *n;
2430
2431 int skip = CountLabels(name) - 34;
2432 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2433
2434 n = SkipLeadingLabels(name, skip);
2435 for (i=0; i<16; i++)
2436 {
2437 if (n->c[0] != 1) return mStatus_Invalid;
2438 l = HexVal(n->c[1]);
2439 n = (const domainname *)(n->c + 2);
2440
2441 if (n->c[0] != 1) return mStatus_Invalid;
2442 h = HexVal(n->c[1]);
2443 n = (const domainname *)(n->c + 2);
2444
2445 if (l<0 || h<0) return mStatus_Invalid;
2446 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2447 }
2448
2449 a->type = mDNSAddrType_IPv6;
2450 return(mStatus_NoError);
2451 }
2452
ReverseMapDomainType(const domainname * const name)2453 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2454 {
2455 int skip = CountLabels(name) - 2;
2456 if (skip >= 0)
2457 {
2458 const domainname *suffix = SkipLeadingLabels(name, skip);
2459 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2460 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
2461 }
2462 return(mDNSAddrType_None);
2463 }
2464
SendARP(mDNS * const m,const mDNSu8 op,const AuthRecord * const rr,const mDNSv4Addr * const spa,const mDNSEthAddr * const tha,const mDNSv4Addr * const tpa,const mDNSEthAddr * const dst)2465 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2466 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2467 {
2468 int i;
2469 mDNSu8 *ptr = m->omsg.data;
2470 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2471 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2472
2473 // 0x00 Destination address
2474 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2475
2476 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2477 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2478
2479 // 0x0C ARP Ethertype (0x0806)
2480 *ptr++ = 0x08; *ptr++ = 0x06;
2481
2482 // 0x0E ARP header
2483 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
2484 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
2485 *ptr++ = 6; // Hardware address length
2486 *ptr++ = 4; // Protocol address length
2487 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
2488
2489 // 0x16 Sender hardware address (our MAC address)
2490 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2491
2492 // 0x1C Sender protocol address
2493 for (i=0; i<4; i++) *ptr++ = spa->b[i];
2494
2495 // 0x20 Target hardware address
2496 for (i=0; i<6; i++) *ptr++ = tha->b[i];
2497
2498 // 0x26 Target protocol address
2499 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2500
2501 // 0x2A Total ARP Packet length 42 bytes
2502 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2503 }
2504
CheckSum(const void * const data,mDNSs32 length,mDNSu32 sum)2505 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2506 {
2507 const mDNSu16 *ptr = data;
2508 while (length > 0) { length -= 2; sum += *ptr++; }
2509 sum = (sum & 0xFFFF) + (sum >> 16);
2510 sum = (sum & 0xFFFF) + (sum >> 16);
2511 return(sum != 0xFFFF ? sum : 0);
2512 }
2513
IPv6CheckSum(const mDNSv6Addr * const src,const mDNSv6Addr * const dst,const mDNSu8 protocol,const void * const data,const mDNSu32 length)2514 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2515 {
2516 IPv6PseudoHeader ph;
2517 ph.src = *src;
2518 ph.dst = *dst;
2519 ph.len.b[0] = length >> 24;
2520 ph.len.b[1] = length >> 16;
2521 ph.len.b[2] = length >> 8;
2522 ph.len.b[3] = length;
2523 ph.pro.b[0] = 0;
2524 ph.pro.b[1] = 0;
2525 ph.pro.b[2] = 0;
2526 ph.pro.b[3] = protocol;
2527 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2528 }
2529
SendNDP(mDNS * const m,const mDNSu8 op,const mDNSu8 flags,const AuthRecord * const rr,const mDNSv6Addr * const spa,const mDNSEthAddr * const tha,const mDNSv6Addr * const tpa,const mDNSEthAddr * const dst)2530 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2531 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2532 {
2533 int i;
2534 mDNSOpaque16 checksum;
2535 mDNSu8 *ptr = m->omsg.data;
2536 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2537 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2538 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2539 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] } };
2540 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2541 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2542 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2543
2544 // 0x00 Destination address
2545 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2546 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2547 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2548 // link with a pointless link-layer multicast.
2549 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2550 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2551 // *ptr++ = 0x33;
2552 // *ptr++ = 0x33;
2553 // *ptr++ = 0xFF;
2554 // *ptr++ = tpa->b[0xD];
2555 // *ptr++ = tpa->b[0xE];
2556 // *ptr++ = tpa->b[0xF];
2557
2558 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2559 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2560
2561 // 0x0C IPv6 Ethertype (0x86DD)
2562 *ptr++ = 0x86; *ptr++ = 0xDD;
2563
2564 // 0x0E IPv6 header
2565 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
2566 *ptr++ = 0x00; *ptr++ = 0x20; // Length
2567 *ptr++ = 0x3A; // Protocol == ICMPv6
2568 *ptr++ = 0xFF; // Hop Limit
2569
2570 // 0x16 Sender IPv6 address
2571 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2572
2573 // 0x26 Destination IPv6 address
2574 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2575
2576 // 0x36 NDP header
2577 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2578 *ptr++ = 0x00; // Code
2579 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
2580 *ptr++ = flags;
2581 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2582
2583 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
2584 {
2585 // 0x3E NDP target.
2586 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2587 // 0x4E Source Link-layer Address
2588 // <http://www.ietf.org/rfc/rfc2461.txt>
2589 // MUST NOT be included when the source IP address is the unspecified address.
2590 // Otherwise, on link layers that have addresses this option MUST be included
2591 // in multicast solicitations and SHOULD be included in unicast solicitations.
2592 if (!mDNSIPv6AddressIsZero(*spa))
2593 {
2594 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2595 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2596 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2597 }
2598 }
2599 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2600 {
2601 // 0x3E NDP target.
2602 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2603 // 0x4E Target Link-layer Address
2604 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2605 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2606 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2607 }
2608
2609 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2610 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
2611 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2612 m->omsg.data[0x38] = checksum.b[0];
2613 m->omsg.data[0x39] = checksum.b[1];
2614
2615 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2616 }
2617
SetupTracerOpt(const mDNS * const m,rdataOPT * const Trace)2618 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2619 {
2620 mDNSu32 DNS_VERS = _DNS_SD_H;
2621 Trace->u.tracer.platf = m->mDNS_plat;
2622 Trace->u.tracer.mDNSv = DNS_VERS;
2623
2624 Trace->opt = kDNSOpt_Trace;
2625 Trace->optlen = DNSOpt_TraceData_Space - 4;
2626 }
2627
SetupOwnerOpt(const mDNS * const m,const NetworkInterfaceInfo * const intf,rdataOPT * const owner)2628 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2629 {
2630 owner->u.owner.vers = 0;
2631 owner->u.owner.seq = m->SleepSeqNum;
2632 owner->u.owner.HMAC = m->PrimaryMAC;
2633 owner->u.owner.IMAC = intf->MAC;
2634 owner->u.owner.password = zeroEthAddr;
2635
2636 // Don't try to compute the optlen until *after* we've set up the data fields
2637 // 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
2638 owner->opt = kDNSOpt_Owner;
2639 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2640 }
2641
GrantUpdateCredit(AuthRecord * rr)2642 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2643 {
2644 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2645 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2646 }
2647
ShouldSendGoodbyesBeforeSleep(mDNS * const m,const NetworkInterfaceInfo * intf,AuthRecord * rr)2648 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2649 {
2650 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2651 // and hence there is no need to check for Transfering state. But if we have sleep
2652 // proxies and partially sending goodbyes for some records, we will be in Transfering
2653 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2654 // we are not awake handles both cases.
2655 if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2656 {
2657 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2658 return mDNStrue;
2659 }
2660
2661 if (m->SleepState != SleepState_Sleeping)
2662 return mDNSfalse;
2663
2664 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2665 // whether you can send goodbyes or not.
2666 if (!intf->SendGoodbyes)
2667 {
2668 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2669 return mDNSfalse;
2670 }
2671 else
2672 {
2673 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2674 return mDNStrue;
2675 }
2676 }
2677
2678 // Note about acceleration of announcements to facilitate automatic coalescing of
2679 // multiple independent threads of announcements into a single synchronized thread:
2680 // The announcements in the packet may be at different stages of maturity;
2681 // One-second interval, two-second interval, four-second interval, and so on.
2682 // After we've put in all the announcements that are due, we then consider
2683 // whether there are other nearly-due announcements that are worth accelerating.
2684 // To be eligible for acceleration, a record MUST NOT be older (further along
2685 // its timeline) than the most mature record we've already put in the packet.
2686 // In other words, younger records can have their timelines accelerated to catch up
2687 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2688 // Older records cannot have their timelines accelerated; this would just widen
2689 // the gap between them and their younger bretheren and get them even more out of sync.
2690
2691 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2692 // the record list and/or question list.
2693 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
SendResponses(mDNS * const m)2694 mDNSlocal void SendResponses(mDNS *const m)
2695 {
2696 int pktcount = 0;
2697 AuthRecord *rr, *r2;
2698 mDNSs32 maxExistingAnnounceInterval = 0;
2699 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2700
2701 m->NextScheduledResponse = m->timenow + FutureTime;
2702
2703 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2704
2705 for (rr = m->ResourceRecords; rr; rr=rr->next)
2706 if (rr->ImmedUnicast)
2707 {
2708 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2709 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2710 v4.ip.v4 = rr->v4Requester;
2711 v6.ip.v6 = rr->v6Requester;
2712 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2713 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2714 if (rr->ImmedUnicast)
2715 {
2716 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2717 rr->ImmedUnicast = mDNSfalse;
2718 }
2719 }
2720
2721 // ***
2722 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2723 // ***
2724
2725 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2726 for (rr = m->ResourceRecords; rr; rr=rr->next)
2727 {
2728 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2729 if (TimeToAnnounceThisRecord(rr, m->timenow))
2730 {
2731 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2732 {
2733 if (!rr->WakeUp.HMAC.l[0])
2734 {
2735 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2736 }
2737 else
2738 {
2739 mDNSBool unicastOnly;
2740 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2741 unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse;
2742 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly);
2743 for (r2 = rr; r2; r2=r2->next)
2744 if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2745 mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2746 {
2747 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2748 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2749 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2750 {
2751 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2752 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2753 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2754 }
2755 r2->LastAPTime = m->timenow;
2756 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2757 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2758 }
2759 }
2760 }
2761 else if (ResourceRecordIsValidAnswer(rr))
2762 {
2763 if (rr->AddressProxy.type)
2764 {
2765 if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2766 {
2767 rr->AnnounceCount--;
2768 rr->ThisAPInterval *= 2;
2769 rr->LastAPTime = m->timenow;
2770 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2771 {
2772 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2773 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2774 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2775 }
2776 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2777 {
2778 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2779 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2780 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2781 }
2782 }
2783 }
2784 else
2785 {
2786 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2787 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2788 maxExistingAnnounceInterval = rr->ThisAPInterval;
2789 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2790 }
2791 }
2792 }
2793 }
2794
2795 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2796 // Eligible records that are more than half-way to their announcement time are accelerated
2797 for (rr = m->ResourceRecords; rr; rr=rr->next)
2798 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2799 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2800 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2801 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2802 ResourceRecordIsValidAnswer(rr)))
2803 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2804
2805 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2806 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2807 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2808 // then all that means is that it won't get sent -- which would not be the end of the world.
2809 for (rr = m->ResourceRecords; rr; rr=rr->next)
2810 {
2811 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2812 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2813 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2814 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2815 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2816 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2817 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2818 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2819 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2820 // We also make sure we send the DeviceInfo TXT record too, if necessary
2821 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2822 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2823 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2824 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2825 {
2826 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2827 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2828 }
2829 }
2830
2831 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2832 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2833 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2834 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2835 // -- 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
2836 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2837 for (rr = m->ResourceRecords; rr; rr=rr->next)
2838 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2839 {
2840 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2841 {
2842 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2843 {
2844 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2845 (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) &&
2846 SameResourceRecordSignature(r2, rr) &&
2847 ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer)))
2848 {
2849 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2850 }
2851 }
2852 }
2853 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2854 {
2855 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2856 {
2857 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2858 (r2->ImmedAdditional != rr->ImmedAdditional) &&
2859 SameResourceRecordSignature(r2, rr) &&
2860 IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional))
2861 {
2862 r2->ImmedAdditional = rr->ImmedAdditional;
2863 }
2864 }
2865 }
2866 }
2867
2868 // Now set SendRNow state appropriately
2869 for (rr = m->ResourceRecords; rr; rr=rr->next)
2870 {
2871 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2872 {
2873 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2874 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2875 rr->LastMCTime = m->timenow;
2876 rr->LastMCInterface = rr->ImmedAnswer;
2877 rr->ProbeRestartCount = 0; // Reset the probe restart count
2878 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2879 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2880 {
2881 rr->AnnounceCount--;
2882 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2883 rr->ThisAPInterval *= 2;
2884 rr->LastAPTime = m->timenow;
2885 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2886 }
2887 }
2888 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2889 {
2890 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2891 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2892 rr->LastMCTime = m->timenow;
2893 rr->LastMCInterface = rr->ImmedAnswer;
2894 }
2895 SetNextAnnounceProbeTime(m, rr);
2896 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2897 }
2898
2899 // ***
2900 // *** 2. Loop through interface list, sending records as appropriate
2901 // ***
2902
2903 while (intf)
2904 {
2905 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2906 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2907 int numDereg = 0;
2908 int numAnnounce = 0;
2909 int numAnswer = 0;
2910 mDNSu8 *responseptr = m->omsg.data;
2911 mDNSu8 *newptr;
2912 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2913
2914 // First Pass. Look for:
2915 // 1. Deregistering records that need to send their goodbye packet
2916 // 2. Updated records that need to retract their old data
2917 // 3. Answers and announcements we need to send
2918 for (rr = m->ResourceRecords; rr; rr=rr->next)
2919 {
2920
2921 // Skip this interface if the record InterfaceID is *Any and the record is not
2922 // appropriate for the interface type.
2923 if ((rr->SendRNow == intf->InterfaceID) &&
2924 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)))
2925 {
2926 rr->SendRNow = GetNextActiveInterfaceID(intf);
2927 }
2928 else if (rr->SendRNow == intf->InterfaceID)
2929 {
2930 RData *OldRData = rr->resrec.rdata;
2931 mDNSu16 oldrdlength = rr->resrec.rdlength;
2932 mDNSu8 active = (mDNSu8)
2933 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2934 newptr = mDNSNULL;
2935 if (rr->NewRData && active)
2936 {
2937 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2938 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2939 {
2940 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2941 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2942 else continue; // If this packet is already too full to hold the goodbye for this record, skip it for now and we'll retry later
2943 }
2944 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2945 }
2946
2947 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2948 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2949 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2950 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2951 if (newptr)
2952 {
2953 responseptr = newptr;
2954 rr->RequireGoodbye = active;
2955 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2956 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2957 }
2958
2959 if (rr->NewRData && active)
2960 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2961
2962 // The first time through (pktcount==0), if this record is verified unique
2963 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2964 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2965 rr->SendNSECNow = mDNSInterfaceMark;
2966
2967 if (newptr) // If succeeded in sending, advance to next interface
2968 {
2969 // If sending on all interfaces, go to next interface; else we're finished now
2970 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2971 rr->SendRNow = GetNextActiveInterfaceID(intf);
2972 else
2973 rr->SendRNow = mDNSNULL;
2974 }
2975 }
2976 }
2977
2978 // Second Pass. Add additional records, if there's space.
2979 newptr = responseptr;
2980 for (rr = m->ResourceRecords; rr; rr=rr->next)
2981 if (rr->ImmedAdditional == intf->InterfaceID)
2982 if (ResourceRecordIsValidAnswer(rr))
2983 {
2984 // If we have at least one answer already in the packet, then plan to add additionals too
2985 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2986
2987 // If we're not planning to send any additionals, but this record is a unique one, then
2988 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2989 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2990 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2991 {
2992 const AuthRecord *a;
2993 for (a = m->ResourceRecords; a; a=a->next)
2994 if (a->LastMCTime == m->timenow &&
2995 a->LastMCInterface == intf->InterfaceID &&
2996 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2997 }
2998 if (!SendAdditional) // If we don't want to send this after all,
2999 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
3000 else if (newptr) // Else, try to add it if we can
3001 {
3002 // The first time through (pktcount==0), if this record is verified unique
3003 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
3004 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
3005 rr->SendNSECNow = mDNSInterfaceMark;
3006
3007 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
3008 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
3009 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
3010 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
3011 if (newptr)
3012 {
3013 responseptr = newptr;
3014 rr->ImmedAdditional = mDNSNULL;
3015 rr->RequireGoodbye = mDNStrue;
3016 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
3017 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
3018 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3019 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3020 rr->LastMCTime = m->timenow;
3021 rr->LastMCInterface = intf->InterfaceID;
3022 }
3023 }
3024 }
3025
3026 // Third Pass. Add NSEC records, if there's space.
3027 // When we're generating an NSEC record in response to a specify query for that type
3028 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3029 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3030 for (rr = m->ResourceRecords; rr; rr=rr->next)
3031 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
3032 {
3033 AuthRecord nsec;
3034 mDNSu8 *ptr;
3035 int len;
3036 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3037 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
3038 AssignDomainName(&nsec.namestorage, rr->resrec.name);
3039 ptr = nsec.rdatastorage.u.data;
3040 len = DomainNameLength(rr->resrec.name);
3041 // We have a nxt name followed by window number, window length and a window bitmap
3042 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
3043 if (nsec.resrec.rdlength <= StandardAuthRDSize)
3044 {
3045 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
3046 AssignDomainName((domainname *)ptr, rr->resrec.name);
3047 ptr += len;
3048 *ptr++ = 0; // window number
3049 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
3050 for (r2 = m->ResourceRecords; r2; r2=r2->next)
3051 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
3052 {
3053 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
3054 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
3055 }
3056 newptr = responseptr;
3057 if (!r2) // If we successfully built our NSEC record, add it to the packet now
3058 {
3059 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
3060 if (newptr) responseptr = newptr;
3061 }
3062 }
3063 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength);
3064
3065 // If we successfully put the NSEC record, clear the SendNSECNow flag
3066 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3067 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
3068 {
3069 rr->SendNSECNow = mDNSNULL;
3070 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3071 for (r2 = rr->next; r2; r2=r2->next)
3072 if (SameResourceRecordNameClassInterface(r2, rr))
3073 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
3074 r2->SendNSECNow = mDNSNULL;
3075 }
3076 }
3077
3078 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
3079 {
3080 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3081 if (OwnerRecordSpace || TraceRecordSpace)
3082 {
3083 AuthRecord opt;
3084 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3085 opt.resrec.rrclass = NormalMaxDNSMessageData;
3086 opt.resrec.rdlength = sizeof(rdataOPT);
3087 opt.resrec.rdestimate = sizeof(rdataOPT);
3088 if (OwnerRecordSpace && TraceRecordSpace)
3089 {
3090 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
3091 opt.resrec.rdestimate += sizeof(rdataOPT);
3092 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3093 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3094 }
3095 else if (OwnerRecordSpace)
3096 {
3097 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3098 }
3099 else if (TraceRecordSpace)
3100 {
3101 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3102 }
3103 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
3104 if (newptr)
3105 {
3106 responseptr = newptr;
3107 }
3108 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
3109 {
3110 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3111 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3112 }
3113 else
3114 {
3115 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3116 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3117 }
3118 }
3119
3120 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3121 numDereg, numDereg == 1 ? "" : "s",
3122 numAnnounce, numAnnounce == 1 ? "" : "s",
3123 numAnswer, numAnswer == 1 ? "" : "s",
3124 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
3125
3126 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSfalse);
3127 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSfalse);
3128 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3129 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
3130 // There might be more things to send on this interface, so go around one more time and try again.
3131 }
3132 else // Nothing more to send on this interface; go to next
3133 {
3134 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3135 #if MDNS_DEBUGMSGS && 0
3136 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3137 debugf(msg, intf, next);
3138 #endif
3139 intf = next;
3140 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3141 }
3142 }
3143
3144 // ***
3145 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3146 // ***
3147
3148 if (m->CurrentRecord)
3149 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3150 m->CurrentRecord = m->ResourceRecords;
3151 while (m->CurrentRecord)
3152 {
3153 rr = m->CurrentRecord;
3154 m->CurrentRecord = rr->next;
3155
3156 if (rr->SendRNow)
3157 {
3158 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
3159 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3160 IIDPrintable(rr->SendRNow), IIDPrintable(rr->resrec.InterfaceID), rr->resrec.RecordType, ARDisplayString(m, rr));
3161 rr->SendRNow = mDNSNULL;
3162 }
3163
3164 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3165 {
3166 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
3167
3168 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
3169 {
3170 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3171 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
3172 }
3173 else
3174 {
3175 rr->ImmedAnswer = mDNSNULL;
3176 rr->ImmedUnicast = mDNSfalse;
3177 rr->v4Requester = zerov4Addr;
3178 rr->v6Requester = zerov6Addr;
3179 }
3180 }
3181 }
3182 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
3183 }
3184
3185 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3186 // so we want to be lazy about how frequently we do it.
3187 // 1. If a cache record is currently referenced by *no* active questions,
3188 // then we don't mind expiring it up to a minute late (who will know?)
3189 // 2. Else, if a cache record is due for some of its final expiration queries,
3190 // we'll allow them to be late by up to 2% of the TTL
3191 // 3. Else, if a cache record has completed all its final expiration queries without success,
3192 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3193 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3194 // so allow at most 1/10 second lateness
3195 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3196 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3197 #define CacheCheckGracePeriod(CR) ( \
3198 ((CR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3199 ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50) : \
3200 ((CR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3201 ((CR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3202
3203 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3204
ScheduleNextCacheCheckTime(mDNS * const m,const mDNSu32 slot,const mDNSs32 event)3205 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
3206 {
3207 if (m->rrcache_nextcheck[slot] - event > 0)
3208 m->rrcache_nextcheck[slot] = event;
3209 if (m->NextCacheCheck - event > 0)
3210 m->NextCacheCheck = event;
3211 }
3212
3213 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3214 // rr->TimeRcvd
3215 // rr->resrec.rroriginalttl
3216 // rr->UnansweredQueries
3217 // rr->CRActiveQuestion
SetNextCacheCheckTimeForRecord(mDNS * const m,CacheRecord * const rr)3218 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
3219 {
3220 rr->NextRequiredQuery = RRExpireTime(rr);
3221
3222 // If we have an active question, then see if we want to schedule a refresher query for this record.
3223 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3224 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3225 {
3226 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3227 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3228 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3229 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
3230 }
3231 ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr));
3232 }
3233
3234 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3235 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3236 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3237
3238 // Delay before restarting questions on a flapping interface.
3239 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3240 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3241 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3242 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3243
mDNS_Reconfirm_internal(mDNS * const m,CacheRecord * const rr,mDNSu32 interval)3244 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3245 {
3246 if (interval < kMinimumReconfirmTime)
3247 interval = kMinimumReconfirmTime;
3248 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3249 interval = 0x10000000;
3250
3251 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3252 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3253 {
3254 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3255 // For all the reconfirmations in a given batch, we want to use the same random value
3256 // so that the reconfirmation questions can be grouped into a single query packet
3257 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime);
3258 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
3259 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
3260 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
3261 SetNextCacheCheckTimeForRecord(m, rr);
3262 }
3263 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3264 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
3265 return(mStatus_NoError);
3266 }
3267
3268 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3269 // It also appends to the list of known answer records that need to be included,
3270 // and updates the forcast for the size of the known answer section.
BuildQuestion(mDNS * const m,const NetworkInterfaceInfo * intf,DNSMessage * query,mDNSu8 ** queryptr,DNSQuestion * q,CacheRecord *** kalistptrptr,mDNSu32 * answerforecast)3271 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
3272 DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3273 {
3274 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3275 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3276 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3277 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3278 if (!newptr)
3279 {
3280 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3281 return(mDNSfalse);
3282 }
3283 else
3284 {
3285 mDNSu32 forecast = *answerforecast;
3286 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3287 CacheRecord *cr;
3288 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
3289
3290 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // If we have a resource record in our cache,
3291 if (cr->resrec.InterfaceID == q->SendQNow && // received on this interface
3292 !(cr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
3293 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList && // which is not already in the known answer list
3294 cr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3295 SameNameCacheRecordAnswersQuestion(cr, q) && // which answers our question
3296 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
3297 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
3298 {
3299 // We don't want to include unique records in the Known Answer section. The Known Answer section
3300 // is intended to suppress floods of shared-record replies from many other devices on the network.
3301 // That concept really does not apply to unique records, and indeed if we do send a query for
3302 // which we have a unique record already in our cache, then including that unique record as a
3303 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3304
3305 *ka = cr; // Link this record into our known answer chain
3306 ka = &cr->NextInKAList;
3307 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3308 forecast += 12 + cr->resrec.rdestimate;
3309 // If we're trying to put more than one question in this packet, and it doesn't fit
3310 // then undo that last question and try again next time
3311 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3312 {
3313 query->h.numQuestions--;
3314 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3315 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3316 ka = *kalistptrptr; // Go back to where we started and retract these answer records
3317 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3318 return(mDNSfalse); // Return false, so we'll try again in the next packet
3319 }
3320 }
3321
3322 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3323 *queryptr = newptr; // Update the packet pointer
3324 *answerforecast = forecast; // Update the forecast
3325 *kalistptrptr = ka; // Update the known answer list pointer
3326 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3327
3328 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // For every resource record in our cache,
3329 if (cr->resrec.InterfaceID == q->SendQNow && // received on this interface
3330 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList && // which is not in the known answer list
3331 SameNameCacheRecordAnswersQuestion(cr, q)) // which answers our question
3332 {
3333 cr->UnansweredQueries++; // indicate that we're expecting a response
3334 cr->LastUnansweredTime = m->timenow;
3335 SetNextCacheCheckTimeForRecord(m, cr);
3336 }
3337
3338 return(mDNStrue);
3339 }
3340 }
3341
3342 // When we have a query looking for a specified name, but there appear to be no answers with
3343 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3344 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3345 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3346 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3347 // A typical reconfirmation scenario might go like this:
3348 // Depth 0: Name "myhost.local" has no address records
3349 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3350 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3351 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3352 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3353 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
ReconfirmAntecedents(mDNS * const m,const domainname * const name,const mDNSu32 namehash,const mDNSInterfaceID InterfaceID,const int depth)3354 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth)
3355 {
3356 mDNSu32 slot;
3357 const CacheGroup *cg;
3358 CacheRecord *cr;
3359 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3360 if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3361 FORALL_CACHERECORDS(slot, cg, cr)
3362 {
3363 const domainname *crtarget;
3364 if (cr->resrec.InterfaceID != InterfaceID) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3365 if (cr->resrec.rdatahash != namehash) continue; // Skip records whose rdata hash doesn't match the name hash.
3366 crtarget = GetRRDomainNameTarget(&cr->resrec);
3367 if (crtarget && SameDomainName(crtarget, name))
3368 {
3369 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth, InterfaceID, CRDisplayString(m, cr));
3370 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3371 if (depth < 5)
3372 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1);
3373 }
3374 }
3375 }
3376
3377 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3378 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3379 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3380 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
CacheHasAddressTypeForName(mDNS * const m,const domainname * const name,const mDNSu32 namehash)3381 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3382 {
3383 CacheGroup *const cg = CacheGroupForName(m, namehash, name);
3384 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3385 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3386 return(cr);
3387 }
3388
3389
FindSPSInCache1(mDNS * const m,const DNSQuestion * const q,const CacheRecord * const c0,const CacheRecord * const c1)3390 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3391 {
3392 #ifndef SPC_DISABLED
3393 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3394 const CacheRecord *cr, *bestcr = mDNSNULL;
3395 mDNSu32 bestmetric = 1000000;
3396 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3397 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
3398 if (cr != c0 && cr != c1) // that's not one we've seen before,
3399 if (SameNameCacheRecordAnswersQuestion(cr, q)) // and answers our browse query,
3400 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
3401 {
3402 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3403 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3404 }
3405 return(bestcr);
3406 #else // SPC_DISABLED
3407 (void) m;
3408 (void) q;
3409 (void) c0;
3410 (void) c1;
3411 (void) c1;
3412 return mDNSNULL;
3413 #endif // SPC_DISABLED
3414 }
3415
CheckAndSwapSPS(const CacheRecord ** sps1,const CacheRecord ** sps2)3416 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3417 {
3418 const CacheRecord *swap_sps;
3419 mDNSu32 metric1, metric2;
3420
3421 if (!(*sps1) || !(*sps2)) return;
3422 metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3423 metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3424 if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3425 {
3426 swap_sps = *sps1;
3427 *sps1 = *sps2;
3428 *sps2 = swap_sps;
3429 }
3430 }
3431
ReorderSPSByFeature(const CacheRecord * sps[3])3432 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3433 {
3434 CheckAndSwapSPS(&sps[0], &sps[1]);
3435 CheckAndSwapSPS(&sps[0], &sps[2]);
3436 CheckAndSwapSPS(&sps[1], &sps[2]);
3437 }
3438
3439
3440 // Finds the three best Sleep Proxies we currently have in our cache
FindSPSInCache(mDNS * const m,const DNSQuestion * const q,const CacheRecord * sps[3])3441 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3442 {
3443 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3444 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
3445 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
3446
3447 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3448 // only if they have equally good metric and support features.
3449 ReorderSPSByFeature(sps);
3450 }
3451
3452 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize],mDNSs32 time)3453 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3454 {
3455 int i;
3456 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3457 }
3458
ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize],mDNSs32 time,mDNSInterfaceID InterfaceID)3459 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3460 {
3461 int i;
3462 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3463 }
3464
SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize],const NetworkInterfaceInfo * const intf)3465 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3466 {
3467 int i;
3468 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3469 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3470 for (i=0; i<DupSuppressInfoSize; i++)
3471 if (ds[i].InterfaceID == intf->InterfaceID)
3472 {
3473 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3474 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3475 if (v4 && v6) return(mDNStrue);
3476 }
3477 return(mDNSfalse);
3478 }
3479
RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize],mDNSs32 Time,mDNSInterfaceID InterfaceID,mDNSs32 Type)3480 mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3481 {
3482 int i, j;
3483
3484 // See if we have this one in our list somewhere already
3485 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3486
3487 // If not, find a slot we can re-use
3488 if (i >= DupSuppressInfoSize)
3489 {
3490 i = 0;
3491 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3492 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3493 i = j;
3494 }
3495
3496 // Record the info about this query we saw
3497 ds[i].Time = Time;
3498 ds[i].InterfaceID = InterfaceID;
3499 ds[i].Type = Type;
3500 }
3501
mDNSSendWakeOnResolve(mDNS * const m,DNSQuestion * q)3502 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3503 {
3504 int len, i, cnt;
3505 mDNSInterfaceID InterfaceID = q->InterfaceID;
3506 domainname *d = &q->qname;
3507
3508 // We can't send magic packets without knowing which interface to send it on.
3509 if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID))
3510 {
3511 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3512 return;
3513 }
3514
3515 // Split MAC@IPAddress and pass them separately
3516 len = d->c[0];
3517 cnt = 0;
3518 for (i = 1; i < len; i++)
3519 {
3520 if (d->c[i] == '@')
3521 {
3522 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3523 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3524 if (cnt != 5)
3525 {
3526 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3527 return;
3528 }
3529 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3530 {
3531 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3532 return;
3533 }
3534 if ((len - i) > (int)(sizeof(IPAddr) - 1))
3535 {
3536 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3537 return;
3538 }
3539 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3540 EthAddr[i - 1] = 0;
3541 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3542 IPAddr[len - i] = 0;
3543 m->mDNSStats.WakeOnResolves++;
3544 mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3545 return;
3546 }
3547 else if (d->c[i] == ':')
3548 cnt++;
3549 }
3550 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3551 }
3552
3553
AccelerateThisQuery(mDNS * const m,DNSQuestion * q)3554 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3555 {
3556 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3557 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3558 return(mDNStrue);
3559
3560 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3561 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3562 {
3563 // We forecast: qname (n) type (2) class (2)
3564 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3565 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3566 const CacheRecord *cr;
3567 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // If we have a resource record in our cache,
3568 if (cr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3569 SameNameCacheRecordAnswersQuestion(cr, q) && // which answers our question
3570 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3571 cr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3572 {
3573 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3574 forecast += 12 + cr->resrec.rdestimate;
3575 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3576 }
3577 return(mDNStrue);
3578 }
3579
3580 return(mDNSfalse);
3581 }
3582
3583 // How Standard Queries are generated:
3584 // 1. The Question Section contains the question
3585 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3586
3587 // How Probe Queries are generated:
3588 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3589 // if some other host is already using *any* records with this name, we want to know about it.
3590 // 2. The Authority Section contains the proposed values we intend to use for one or more
3591 // of our records with that name (analogous to the Update section of DNS Update packets)
3592 // because if some other host is probing at the same time, we each want to know what the other is
3593 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3594
SendQueries(mDNS * const m)3595 mDNSlocal void SendQueries(mDNS *const m)
3596 {
3597 mDNSu32 slot;
3598 CacheGroup *cg;
3599 CacheRecord *cr;
3600 AuthRecord *ar;
3601 int pktcount = 0;
3602 DNSQuestion *q;
3603 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3604 mDNSs32 maxExistingQuestionInterval = 0;
3605 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3606 CacheRecord *KnownAnswerList = mDNSNULL;
3607
3608 // 1. If time for a query, work out what we need to do
3609
3610 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3611 // to their NextRequiredQuery to be worth batching them together with this one
3612 FORALL_CACHERECORDS(slot, cg, cr)
3613 {
3614 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3615 {
3616 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3617 {
3618 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3619 q = cr->CRActiveQuestion;
3620 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3621 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3622 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3623 if (!mDNSOpaque16IsZero(q->TargetQID))
3624 {
3625 q->LastQTime = m->timenow - q->ThisQInterval;
3626 cr->UnansweredQueries++;
3627 m->mDNSStats.CacheRefreshQueries++;
3628 }
3629 else if (q->SendQNow == mDNSNULL)
3630 {
3631 q->SendQNow = cr->resrec.InterfaceID;
3632 }
3633 else if (q->SendQNow != cr->resrec.InterfaceID)
3634 {
3635 q->SendQNow = mDNSInterfaceMark;
3636 }
3637
3638 // Indicate that this question was marked for sending
3639 // to update an existing cached answer record.
3640 // The browse throttling logic below uses this to determine
3641 // if the query should be sent.
3642 if (mDNSOpaque16IsZero(q->TargetQID))
3643 q->CachedAnswerNeedsUpdate = mDNStrue;
3644 }
3645 }
3646 }
3647
3648 // Scan our list of questions to see which:
3649 // *WideArea* queries need to be sent
3650 // *unicast* queries need to be sent
3651 // *multicast* queries we're definitely going to send
3652 if (m->CurrentQuestion)
3653 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3654 m->CurrentQuestion = m->Questions;
3655 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3656 {
3657 q = m->CurrentQuestion;
3658 if (mDNSOpaque16IsZero(q->TargetQID) && TimeToSendThisQuestion(q, m->timenow))
3659 {
3660 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3661 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3662 if (maxExistingQuestionInterval < q->ThisQInterval)
3663 maxExistingQuestionInterval = q->ThisQInterval;
3664 }
3665 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3666 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3667 // m->CurrentQuestion point to the right question
3668 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3669 }
3670 while (m->CurrentQuestion)
3671 {
3672 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3673 m->CurrentQuestion = m->CurrentQuestion->next;
3674 }
3675 m->CurrentQuestion = mDNSNULL;
3676
3677 // Scan our list of questions
3678 // (a) to see if there are any more that are worth accelerating, and
3679 // (b) to update the state variables for *all* the questions we're going to send
3680 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3681 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3682 // 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.
3683 m->NextScheduledQuery = m->timenow + FutureTime;
3684 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3685 {
3686 if (mDNSOpaque16IsZero(q->TargetQID)
3687 && (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3688 {
3689 // If at least halfway to next query time, advance to next interval
3690 // If less than halfway to next query time, then
3691 // treat this as logically a repeat of the last transmission, without advancing the interval
3692 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3693 {
3694 // If we have reached the answer threshold for this question,
3695 // don't send it again until MaxQuestionInterval unless:
3696 // one of its cached answers needs to be refreshed,
3697 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3698 if (q->BrowseThreshold
3699 && (q->CurrentAnswers >= q->BrowseThreshold)
3700 && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3701 && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3702 {
3703 q->SendQNow = mDNSNULL;
3704 q->ThisQInterval = MaxQuestionInterval;
3705 q->LastQTime = m->timenow;
3706 q->RequestUnicast = 0;
3707 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3708 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3709 }
3710 else
3711 {
3712 // Mark this question for sending on all interfaces
3713 q->SendQNow = mDNSInterfaceMark;
3714 q->ThisQInterval *= QuestionIntervalStep;
3715 }
3716
3717 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3718 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3719
3720 if (q->ThisQInterval > MaxQuestionInterval)
3721 {
3722 q->ThisQInterval = MaxQuestionInterval;
3723 }
3724 else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID &&
3725 q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3726 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3727 {
3728 // Generally don't need to log this.
3729 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3730 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3731 // and when there simply happen to be no instances of the service the client is looking
3732 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3733 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3734 q->qname.c, DNSTypeName(q->qtype));
3735 // Sending third query, and no answers yet; time to begin doubting the source
3736 ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0);
3737 }
3738 }
3739
3740 // Mark for sending. (If no active interfaces, then don't even try.)
3741 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3742 if (q->SendOnAll)
3743 {
3744 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3745 q->LastQTime = m->timenow;
3746 }
3747
3748 // If we recorded a duplicate suppression for this question less than half an interval ago,
3749 // then we consider it recent enough that we don't need to do an identical query ourselves.
3750 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3751
3752 q->LastQTxTime = m->timenow;
3753 q->RecentAnswerPkts = 0;
3754 if (q->RequestUnicast) q->RequestUnicast--;
3755 }
3756 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3757 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3758 SetNextQueryTime(m,q);
3759 }
3760
3761 // 2. Scan our authoritative RR list to see what probes we might need to send
3762
3763 m->NextScheduledProbe = m->timenow + FutureTime;
3764
3765 if (m->CurrentRecord)
3766 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3767 m->CurrentRecord = m->ResourceRecords;
3768 while (m->CurrentRecord)
3769 {
3770 ar = m->CurrentRecord;
3771 m->CurrentRecord = ar->next;
3772 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3773 {
3774 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3775 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3776 {
3777 SetNextAnnounceProbeTime(m, ar);
3778 }
3779 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3780 else if (ar->ProbeCount)
3781 {
3782 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3783 {
3784 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3785 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3786 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3787 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3788 // A similar concern may apply to the NDP Probe too. -- SC
3789 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3790 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3791 }
3792 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3793 {
3794 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3795 // IPv6 source = zero
3796 // No target hardware address
3797 // IPv6 target address is address we're probing
3798 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3799 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3800 }
3801 // Mark for sending. (If no active interfaces, then don't even try.)
3802 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3803 ar->LastAPTime = m->timenow;
3804 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3805 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3806 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3807 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3808 ar->ProbeCount--;
3809 SetNextAnnounceProbeTime(m, ar);
3810 if (ar->ProbeCount == 0)
3811 {
3812 // If this is the last probe for this record, then see if we have any matching records
3813 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3814 AuthRecord *r2;
3815 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3816 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3817 r2->ProbeCount = 0;
3818 // ... then acknowledge this record to the client.
3819 // We do this optimistically, just as we're about to send the third probe.
3820 // This helps clients that both advertise and browse, and want to filter themselves
3821 // from the browse results list, because it helps ensure that the registration
3822 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3823 // A potential downside is that we could deliver a registration confirmation and then find out
3824 // moments later that there's a name conflict, but applications have to be prepared to handle
3825 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3826 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3827 }
3828 }
3829 // else, if it has now finished probing, move it to state Verified,
3830 // and update m->NextScheduledResponse so it will be announced
3831 else
3832 {
3833 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3834 ar->resrec.RecordType = kDNSRecordTypeVerified;
3835 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3836 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3837 SetNextAnnounceProbeTime(m, ar);
3838 }
3839 }
3840 }
3841 m->CurrentRecord = m->DuplicateRecords;
3842 while (m->CurrentRecord)
3843 {
3844 ar = m->CurrentRecord;
3845 m->CurrentRecord = ar->next;
3846 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3847 AcknowledgeRecord(m, ar);
3848 }
3849
3850 // 3. Now we know which queries and probes we're sending,
3851 // go through our interface list sending the appropriate queries on each interface
3852 while (intf)
3853 {
3854 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3855 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3856 mDNSu8 *queryptr = m->omsg.data;
3857 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class
3858
3859 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3860 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3861 if (!KnownAnswerList)
3862 {
3863 // Start a new known-answer list
3864 CacheRecord **kalistptr = &KnownAnswerList;
3865 mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3866
3867 // Put query questions in this packet
3868 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3869 {
3870 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3871 {
3872 mDNSBool Suppress = mDNSfalse;
3873 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3874 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3875 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3876
3877 // If interface is P2P type, verify that query should be sent over it.
3878 if (!mDNSPlatformValidQuestionForInterface(q, intf))
3879 {
3880 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3881 }
3882 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3883 else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3884 BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3885 {
3886 if (Suppress)
3887 m->mDNSStats.DupQuerySuppressions++;
3888
3889 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3890 if (q->WakeOnResolveCount)
3891 {
3892 mDNSSendWakeOnResolve(m, q);
3893 q->WakeOnResolveCount--;
3894 }
3895
3896 // use background traffic class if any included question requires it
3897 if (q->UseBackgroundTraffic)
3898 {
3899 useBackgroundTrafficClass = mDNStrue;
3900 }
3901 }
3902 }
3903 }
3904
3905 // Put probe questions in this packet
3906 for (ar = m->ResourceRecords; ar; ar=ar->next)
3907 {
3908 if (ar->SendRNow != intf->InterfaceID)
3909 continue;
3910
3911 // If interface is a P2P variant, verify that the probe should be sent over it.
3912 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID))
3913 {
3914 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3915 ar->IncludeInProbe = mDNSfalse;
3916 }
3917 else
3918 {
3919 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3920 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3921 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3922 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3923 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3924 mDNSBool putProbe = mDNStrue;
3925 mDNSu16 qclass = ar->resrec.rrclass | ucbit;
3926
3927 {// Determine if this probe question is already in packet's dns message
3928 const mDNSu8 *questionptr = m->omsg.data;
3929 DNSQuestion question;
3930 mDNSu16 n;
3931 for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++)
3932 {
3933 questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question);
3934 if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) &&
3935 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name))
3936 {
3937 putProbe = mDNSfalse; // set to false if already in message
3938 break;
3939 }
3940 }
3941 }
3942
3943 if (putProbe)
3944 {
3945 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass);
3946 if (newptr)
3947 {
3948 queryptr = newptr;
3949 answerforecast = forecast;
3950 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3951 ar->IncludeInProbe = mDNStrue;
3952 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3953 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast);
3954 }
3955 }
3956 else
3957 {
3958 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3959 ar->IncludeInProbe = mDNStrue;
3960 }
3961 }
3962 }
3963 }
3964
3965 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3966 while (KnownAnswerList)
3967 {
3968 CacheRecord *ka = KnownAnswerList;
3969 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3970 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3971 m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3972 if (newptr)
3973 {
3974 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3975 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3976 queryptr = newptr;
3977 KnownAnswerList = ka->NextInKAList;
3978 ka->NextInKAList = mDNSNULL;
3979 }
3980 else
3981 {
3982 // If we ran out of space and we have more than one question in the packet, that's an error --
3983 // we shouldn't have put more than one question if there was a risk of us running out of space.
3984 if (m->omsg.h.numQuestions > 1)
3985 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3986 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3987 break;
3988 }
3989 }
3990
3991 for (ar = m->ResourceRecords; ar; ar=ar->next)
3992 {
3993 if (ar->IncludeInProbe)
3994 {
3995 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3996 ar->IncludeInProbe = mDNSfalse;
3997 if (newptr) queryptr = newptr;
3998 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3999 }
4000 }
4001
4002 if (queryptr > m->omsg.data)
4003 {
4004 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
4005 if (OwnerRecordSpace || TraceRecordSpace)
4006 {
4007 AuthRecord opt;
4008 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
4009 opt.resrec.rrclass = NormalMaxDNSMessageData;
4010 opt.resrec.rdlength = sizeof(rdataOPT);
4011 opt.resrec.rdestimate = sizeof(rdataOPT);
4012 if (OwnerRecordSpace && TraceRecordSpace)
4013 {
4014 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
4015 opt.resrec.rdestimate += sizeof(rdataOPT);
4016 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4017 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
4018 }
4019 else if (OwnerRecordSpace)
4020 {
4021 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4022 }
4023 else if (TraceRecordSpace)
4024 {
4025 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
4026 }
4027 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
4028 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4029 if (!queryptr)
4030 {
4031 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
4032 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4033 }
4034 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
4035 {
4036 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
4037 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
4038 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
4039 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4040 }
4041 }
4042
4043 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
4044 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
4045 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4046 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
4047 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
4048 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", IIDPrintable(intf->InterfaceID), intf->ifname);
4049 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4050 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4051 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
4052 if (++pktcount >= 1000)
4053 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
4054 // There might be more records left in the known answer list, or more questions to send
4055 // on this interface, so go around one more time and try again.
4056 }
4057 else // Nothing more to send on this interface; go to next
4058 {
4059 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
4060 #if MDNS_DEBUGMSGS && 0
4061 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4062 debugf(msg, intf, next);
4063 #endif
4064 intf = next;
4065 }
4066 }
4067
4068 // 4. Final housekeeping
4069
4070 // 4a. Debugging check: Make sure we announced all our records
4071 for (ar = m->ResourceRecords; ar; ar=ar->next)
4072 if (ar->SendRNow)
4073 {
4074 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
4075 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4076 IIDPrintable(ar->SendRNow), IIDPrintable(ar->resrec.InterfaceID), ARDisplayString(m, ar));
4077 ar->SendRNow = mDNSNULL;
4078 }
4079
4080 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4081 // that their interface which went away might come back again, the logic will want to send queries
4082 // for those records, but we can't because their interface isn't here any more, so to keep the
4083 // state machine ticking over we just pretend we did so.
4084 // If the interface does not come back in time, the cache record will expire naturally
4085 FORALL_CACHERECORDS(slot, cg, cr)
4086 {
4087 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
4088 {
4089 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
4090 {
4091 cr->UnansweredQueries++;
4092 cr->CRActiveQuestion->SendQNow = mDNSNULL;
4093 SetNextCacheCheckTimeForRecord(m, cr);
4094 }
4095 }
4096 }
4097
4098 // 4c. Debugging check: Make sure we sent all our planned questions
4099 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4100 // we legitimately couldn't send because the interface is no longer available
4101 for (q = m->Questions; q; q=q->next)
4102 {
4103 if (q->SendQNow)
4104 {
4105 DNSQuestion *x;
4106 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
4107 // There will not be an active interface for questions applied to mDNSInterface_BLE
4108 // so don't log the warning in that case.
4109 if (q->InterfaceID != mDNSInterface_BLE)
4110 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4111 IIDPrintable(q->SendQNow), x ? "new" : "old", IIDPrintable(q->InterfaceID), q->qname.c, DNSTypeName(q->qtype));
4112 q->SendQNow = mDNSNULL;
4113 }
4114 q->CachedAnswerNeedsUpdate = mDNSfalse;
4115 }
4116 }
4117
SendWakeup(mDNS * const m,mDNSInterfaceID InterfaceID,mDNSEthAddr * EthAddr,mDNSOpaque48 * password,mDNSBool unicastOnly)4118 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly)
4119 {
4120 int i, j;
4121
4122 mDNSu8 *ptr = m->omsg.data;
4123 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
4124 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
4125
4126 // 0x00 Destination address
4127 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4128
4129 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4130 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
4131
4132 // 0x0C Ethertype (0x0842)
4133 *ptr++ = 0x08;
4134 *ptr++ = 0x42;
4135
4136 // 0x0E Wakeup sync sequence
4137 for (i=0; i<6; i++) *ptr++ = 0xFF;
4138
4139 // 0x14 Wakeup data
4140 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4141
4142 // 0x74 Password
4143 for (i=0; i<6; i++) *ptr++ = password->b[i];
4144
4145 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4146
4147 if (!unicastOnly)
4148 {
4149 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4150 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4151 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4152 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4153 // So, we send one of each, unicast first, then broadcast second.
4154 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
4155 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4156 }
4157 }
4158
4159 // ***************************************************************************
4160 #if COMPILER_LIKES_PRAGMA_MARK
4161 #pragma mark -
4162 #pragma mark - RR List Management & Task Management
4163 #endif
4164
4165 // Whenever a question is answered, reset its state so that we don't query
4166 // the network repeatedly. This happens first time when we answer the question and
4167 // and later when we refresh the cache.
ResetQuestionState(mDNS * const m,DNSQuestion * q)4168 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
4169 {
4170 q->LastQTime = m->timenow;
4171 q->LastQTxTime = m->timenow;
4172 q->RecentAnswerPkts = 0;
4173 q->ThisQInterval = MaxQuestionInterval;
4174 q->RequestUnicast = 0;
4175 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4176 // Reset unansweredQueries so that we don't penalize this server later when we
4177 // start sending queries when the cache expires.
4178 q->unansweredQueries = 0;
4179 #endif
4180 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4181 }
4182
AdjustUnansweredQueries(mDNS * const m,CacheRecord * const rr)4183 mDNSlocal void AdjustUnansweredQueries(mDNS *const m, CacheRecord *const rr)
4184 {
4185 const mDNSs32 expireTime = RRExpireTime(rr);
4186 const mDNSu32 interval = TicksTTL(rr) / 20; // Calculate 5% of the cache record's TTL.
4187 mDNSu32 rem;
4188
4189 // If the record is expired or UnansweredQueries is already at the max, then return early.
4190 if (((m->timenow - expireTime) >= 0) || (rr->UnansweredQueries >= MaxUnansweredQueries)) return;
4191
4192 if (interval == 0)
4193 {
4194 LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr), CRDisplayString(m, rr));
4195 return;
4196 }
4197
4198 // Calculate the number of whole 5% TTL intervals between now and expiration time.
4199 rem = ((mDNSu32)(expireTime - m->timenow)) / interval;
4200
4201 // Calculate the expected number of remaining refresher queries.
4202 // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4203 if (rem > MaxUnansweredQueries) rem = MaxUnansweredQueries;
4204
4205 // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4206 // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4207 // refresher queries would have been sent if the cache record did have an active question. The cache record's
4208 // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4209 // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4210 // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4211 // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4212 // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4213 // Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4214 if ((MaxUnansweredQueries - rr->UnansweredQueries) > (mDNSs32)rem)
4215 {
4216 if (rem == 0) rem++;
4217 rr->UnansweredQueries = (mDNSu8)(MaxUnansweredQueries - rem);
4218 }
4219 }
4220
4221 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4222 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4223 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4224 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
AnswerCurrentQuestionWithResourceRecord(mDNS * const m,CacheRecord * const rr,const QC_result AddRecord)4225 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
4226 {
4227 DNSQuestion *const q = m->CurrentQuestion;
4228 const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
4229
4230 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4231 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", MortalityDisplayString(rr->resrec.mortality),
4232 rr->resrec.rroriginalttl, CRDisplayString(m, rr));
4233
4234 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4235 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4236 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4237 // we check to see if that query already has a unique local answer.
4238 if (q->LOAddressAnswers)
4239 {
4240 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4241 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
4242 q->LOAddressAnswers);
4243 return;
4244 }
4245
4246 if (q->Suppressed && (AddRecord != QC_suppressed))
4247 {
4248 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4249 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4250 // that are timing out, which we know are answered with negative cache record when timing out.
4251 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
4252 return;
4253 }
4254
4255 // Set the record to immortal if appropriate
4256 if (AddRecord == QC_add && Question_uDNS(q) && rr->resrec.RecordType != kDNSRecordTypePacketNegative &&
4257 q->allowExpired != AllowExpired_None && rr->resrec.mortality == Mortality_Mortal ) rr->resrec.mortality = Mortality_Immortal; // Update a non-expired cache record to immortal if appropriate
4258
4259 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4260 if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname && !q->metrics.answered)
4261 {
4262 mDNSBool skipUpdate = mDNSfalse;
4263 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4264 if (!q->dnsservice || (mdns_dns_service_get_resolver_type(q->dnsservice) != mdns_resolver_type_normal))
4265 {
4266 skipUpdate = mDNStrue;
4267 }
4268 #endif
4269 if (!skipUpdate)
4270 {
4271 const domainname * queryName;
4272 mDNSu32 responseLatencyMs, querySendCount;
4273 mDNSBool isForCellular;
4274
4275 queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname;
4276 querySendCount = q->metrics.querySendCount;
4277 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4278 if (q->querier)
4279 {
4280 querySendCount += mdns_querier_get_send_count(q->querier);
4281 }
4282 isForCellular = mdns_dns_service_interface_is_cellular(q->dnsservice);
4283 #else
4284 isForCellular = (q->qDNSServer && q->qDNSServer->isCell);
4285 #endif
4286 if (q->metrics.querySendCount > 0)
4287 {
4288 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
4289 }
4290 else
4291 {
4292 responseLatencyMs = 0;
4293 }
4294 MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, querySendCount, q->metrics.expiredAnswerState,
4295 q->metrics.dnsOverTCPState, responseLatencyMs, isForCellular);
4296 }
4297 q->metrics.answered = mDNStrue;
4298 }
4299 #endif
4300 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4301 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4302 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4303
4304 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost)
4305 {
4306 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4307 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
4308 if (!rr->CRActiveQuestion)
4309 {
4310 m->rrcache_active++; // If not previously active, increment rrcache_active count
4311 AdjustUnansweredQueries(m, rr); // Adjust UnansweredQueries in case the record missed out on refresher queries
4312 }
4313 rr->CRActiveQuestion = q; // We know q is non-null
4314 SetNextCacheCheckTimeForRecord(m, rr);
4315 }
4316
4317 // If this is:
4318 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4319 // (b) a normal add, where we have at least one unique-type answer,
4320 // then there's no need to keep polling the network.
4321 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4322 // We do this for mDNS questions and uDNS one-shot questions, but not for
4323 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4324 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
4325 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
4326 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4327 {
4328 ResetQuestionState(m, q);
4329 }
4330
4331 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4332
4333 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4334 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4335 if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return;
4336 #endif
4337
4338 #ifdef USE_LIBIDN
4339 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) // If negative answer, check if we need to try Punycode conversion
4340 {
4341 domainname newname;
4342 if (PerformNextPunycodeConversion(q, &newname)) // Itertative Punycode conversion succeeded, so reissue question with new name
4343 {
4344 UDPSocket *const sock = q->LocalSocket; // Save old socket and transaction ID
4345 const mDNSOpaque16 id = q->TargetQID;
4346 q->LocalSocket = mDNSNULL;
4347 mDNS_StopQuery_internal(m, q); // Stop old query
4348 AssignDomainName(&q->qname, &newname); // Update qname
4349 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
4350 mDNS_StartQuery_internal(m, q); // Start new query
4351
4352 if (sock) // Transplant saved socket, if appropriate
4353 {
4354 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
4355 else { q->LocalSocket = sock; q->TargetQID = id; }
4356 }
4357 return; // All done for now; wait until we get the next answer
4358 }
4359 }
4360 #endif // USE_LIBIDN
4361
4362 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4363 // for the purpose of retrying search domains/timeout OR the question is suppressed
4364 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4365 if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4366
4367 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4368 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4369 {
4370 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4371 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4372 {
4373 if (mDNSOpaque16IsZero(q->TargetQID))
4374 {
4375 CacheRecord neg;
4376 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4377 mDNSPlatformMemZero(&neg, sizeof(neg));
4378 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->dnsservice);
4379 #else
4380 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4381 #endif
4382 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4383 }
4384 }
4385 else
4386 {
4387 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4388 if (DNS64ShouldAnswerQuestion(q, &rr->resrec))
4389 {
4390 DNS64AnswerCurrentQuestion(m, &rr->resrec, AddRecord);
4391 }
4392 else
4393 #endif
4394 {
4395 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4396 get_denial_records_from_negative_cache_to_dnssec_context(q->DNSSECStatus.enable_dnssec,
4397 q->DNSSECStatus.context, rr);
4398 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4399 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4400 }
4401 }
4402 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4403 }
4404 // Note: Proceed with caution after this point because client callback function
4405 // invoked above is allowed to do anything, such as starting/stopping queries
4406 // (including this one itself, or the next or previous query in the linked list),
4407 // registering/deregistering records, starting/stopping NAT traversals, etc.
4408
4409 if (m->CurrentQuestion == q)
4410 {
4411 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4412 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4413 // first before following it
4414 if (followcname) AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
4415
4416 // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4417 if (rr->resrec.mortality == Mortality_Ghost && !q->firstExpiredQname.c[0] && (q->allowExpired == AllowExpired_AllowExpiredAnswers) && rr->resrec.RecordType != kDNSRecordTypePacketNegative)
4418 {
4419 debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m,rr), q);
4420 // Note: question->qname is already changed at this point if following a CNAME
4421 AssignDomainName(&q->firstExpiredQname, rr->resrec.name); // Update firstExpiredQname
4422 }
4423 }
4424 }
4425
CacheRecordDeferredAdd(mDNS * const m,CacheRecord * cr)4426 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *cr)
4427 {
4428 cr->DelayDelivery = 0;
4429 if (m->CurrentQuestion)
4430 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4431 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4432 m->CurrentQuestion = m->Questions;
4433 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4434 {
4435 DNSQuestion *q = m->CurrentQuestion;
4436 if (CacheRecordAnswersQuestion(cr, q))
4437 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4438 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4439 m->CurrentQuestion = q->next;
4440 }
4441 m->CurrentQuestion = mDNSNULL;
4442 }
4443
CheckForSoonToExpireRecords(mDNS * const m,const domainname * const name,const mDNSu32 namehash)4444 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
4445 {
4446 const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
4447 const mDNSs32 start = m->timenow - 0x10000000;
4448 mDNSs32 delay = start;
4449 CacheGroup *cg = CacheGroupForName(m, namehash, name);
4450 const CacheRecord *rr;
4451
4452 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4453 {
4454 if (threshold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
4455 {
4456 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
4457 delay = RRExpireTime(rr);
4458 }
4459 }
4460 if (delay - start > 0)
4461 return(NonZeroTime(delay));
4462 else
4463 return(0);
4464 }
4465
4466 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4467 // If new questions are created as a result of invoking client callbacks, they will be added to
4468 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4469 // rr is a new CacheRecord just received into our cache
4470 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4471 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4472 // which may change the record list and/or question list.
4473 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
CacheRecordAdd(mDNS * const m,CacheRecord * cr)4474 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *cr)
4475 {
4476 DNSQuestion *q;
4477
4478 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4479 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4480 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4481 {
4482 if (CacheRecordAnswersQuestion(cr, q))
4483 {
4484 // If this question is one that's actively sending queries, and it's received ten answers within one
4485 // second of sending the last query packet, then that indicates some radical network topology change,
4486 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4487 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4488 // because we will anyway send another query within a few seconds. The first reset query is sent out
4489 // randomized over the next four seconds to reduce possible synchronization between machines.
4490 if (q->LastAnswerPktNum != m->PktNum)
4491 {
4492 q->LastAnswerPktNum = m->PktNum;
4493 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4494 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4495 {
4496 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4497 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4498 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4499 q->ThisQInterval = InitialQuestionInterval;
4500 SetNextQueryTime(m,q);
4501 }
4502 }
4503 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr, cr->resrec.name->c,
4504 DNSTypeName(cr->resrec.rrtype), cr->resrec.rroriginalttl, cr->resrec.rDNSServer ?
4505 &cr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(cr->resrec.rDNSServer ?
4506 cr->resrec.rDNSServer->port : zeroIPPort), q);
4507 q->CurrentAnswers++;
4508
4509 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4510 q->unansweredQueries = 0;
4511 #endif
4512 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4513 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4514 if (q->CurrentAnswers > 4000)
4515 {
4516 static int msgcount = 0;
4517 if (msgcount++ < 10)
4518 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4519 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4520 cr->resrec.rroriginalttl = 0;
4521 cr->UnansweredQueries = MaxUnansweredQueries;
4522 }
4523 }
4524 }
4525
4526 if (!cr->DelayDelivery)
4527 {
4528 if (m->CurrentQuestion)
4529 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4530 m->CurrentQuestion = m->Questions;
4531 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4532 {
4533 q = m->CurrentQuestion;
4534 if (CacheRecordAnswersQuestion(cr, q))
4535 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4536 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4537 m->CurrentQuestion = q->next;
4538 }
4539 m->CurrentQuestion = mDNSNULL;
4540 }
4541
4542 SetNextCacheCheckTimeForRecord(m, cr);
4543 }
4544
4545 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4546 // If new questions are created as a result of invoking client callbacks, they will be added to
4547 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4548 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4549 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4550 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4551 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4552 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4553 // which may change the record list and/or question list.
4554 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
NoCacheAnswer(mDNS * const m,CacheRecord * cr)4555 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *cr)
4556 {
4557 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4558 if (m->CurrentQuestion)
4559 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4560 m->CurrentQuestion = m->Questions;
4561 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4562 // since we're not caching the record and we'll get no opportunity to do this later
4563 while (m->CurrentQuestion)
4564 {
4565 DNSQuestion *q = m->CurrentQuestion;
4566 if (CacheRecordAnswersQuestion(cr, q))
4567 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
4568 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4569 m->CurrentQuestion = q->next;
4570 }
4571 m->CurrentQuestion = mDNSNULL;
4572 }
4573
4574 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4575 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4576 // If new questions are created as a result of invoking client callbacks, they will be added to
4577 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4578 // cr is an existing cache CacheRecord that just expired and is being deleted
4579 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4580 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4581 // which may change the record list and/or question list.
4582 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
CacheRecordRmv(mDNS * const m,CacheRecord * cr)4583 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *cr)
4584 {
4585 if (m->CurrentQuestion)
4586 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4587 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4588 m->CurrentQuestion = m->Questions;
4589
4590 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4591 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4592 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4593 {
4594 DNSQuestion *q = m->CurrentQuestion;
4595 // When a question enters suppressed state, we generate RMV events and generate a negative
4596 // response. A cache may be present that answers this question e.g., cache entry generated
4597 // before the question became suppressed. We need to skip the suppressed questions here as
4598 // the RMV event has already been generated.
4599 if (!q->Suppressed && CacheRecordAnswersQuestion(cr, q) &&
4600 (q->allowExpired == AllowExpired_None || cr->resrec.mortality == Mortality_Mortal))
4601 {
4602 verbosedebugf("CacheRecordRmv %p %s", cr, CRDisplayString(m, cr));
4603 q->FlappingInterface1 = mDNSNULL;
4604 q->FlappingInterface2 = mDNSNULL;
4605
4606 if (q->CurrentAnswers == 0)
4607 {
4608 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4609 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4610 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4611 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4612 #endif
4613 }
4614 else
4615 {
4616 q->CurrentAnswers--;
4617 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4618 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4619 }
4620
4621 // If we have dropped below the answer threshold for this mDNS question,
4622 // restart the queries at InitialQuestionInterval.
4623 if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4624 {
4625 q->ThisQInterval = InitialQuestionInterval;
4626 q->LastQTime = m->timenow - q->ThisQInterval;
4627 SetNextQueryTime(m,q);
4628 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4629 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4630 }
4631 if (cr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4632 {
4633 if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID))
4634 {
4635 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4636 q->qname.c, DNSTypeName(q->qtype));
4637 ReconfirmAntecedents(m, &q->qname, q->qnamehash, cr->resrec.InterfaceID, 0);
4638 }
4639 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
4640 }
4641 }
4642 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4643 m->CurrentQuestion = q->next;
4644 }
4645 m->CurrentQuestion = mDNSNULL;
4646 }
4647
ReleaseCacheEntity(mDNS * const m,CacheEntity * e)4648 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4649 {
4650 #if MDNS_MALLOC_DEBUGGING >= 1
4651 unsigned int i;
4652 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4653 #endif
4654 e->next = m->rrcache_free;
4655 m->rrcache_free = e;
4656 m->rrcache_totalused--;
4657 }
4658
ReleaseCacheGroup(mDNS * const m,CacheGroup ** cp)4659 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4660 {
4661 CacheEntity *e = (CacheEntity *)(*cp);
4662 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4663 if ((*cp)->rrcache_tail != &(*cp)->members)
4664 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4665 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4666 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4667 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4668 (*cp)->name = mDNSNULL;
4669 *cp = (*cp)->next; // Cut record from list
4670 ReleaseCacheEntity(m, e);
4671 }
4672
ReleaseAdditionalCacheRecords(mDNS * const m,CacheRecord ** rp)4673 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4674 {
4675 while (*rp)
4676 {
4677 CacheRecord *rr = *rp;
4678 *rp = (*rp)->next; // Cut record from list
4679 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4680 {
4681 mDNSPlatformMemFree(rr->resrec.rdata);
4682 rr->resrec.rdata = mDNSNULL;
4683 }
4684 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4685 // of the CacheGroup.
4686 if (rr->resrec.name)
4687 {
4688 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4689 mDNSPlatformMemFree((void *)rr->resrec.name);
4690 rr->resrec.name = mDNSNULL;
4691 }
4692 // Don't count the NSEC3 records used by anonymous browse/reg
4693 if (!rr->resrec.InterfaceID)
4694 {
4695 m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4696 }
4697 ReleaseCacheEntity(m, (CacheEntity *)rr);
4698 }
4699 }
4700
ReleaseCacheRecord(mDNS * const m,CacheRecord * r)4701 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4702 {
4703 CacheGroup *cg;
4704
4705 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4706 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4707 r->resrec.rdata = mDNSNULL;
4708 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4709 mdns_forget(&r->resrec.dnsservice);
4710 #endif
4711
4712 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4713 release_denial_records_in_cache_record(r);
4714 #endif
4715
4716 cg = CacheGroupForRecord(m, &r->resrec);
4717
4718 if (!cg)
4719 {
4720 // It is okay to have this printed for NSEC/NSEC3s
4721 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4722 }
4723 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4724 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4725 // (which is handled below) and in that case it should be freed here.
4726 if (r->resrec.name && cg && r->resrec.name != cg->name)
4727 {
4728 debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4729 mDNSPlatformMemFree((void *)r->resrec.name);
4730 }
4731 r->resrec.name = mDNSNULL;
4732
4733 if (!r->resrec.InterfaceID)
4734 {
4735 m->rrcache_totalused_unicast -= r->resrec.rdlength;
4736 }
4737
4738 ReleaseAdditionalCacheRecords(m, &r->soa);
4739
4740 ReleaseCacheEntity(m, (CacheEntity *)r);
4741 }
4742
4743 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4744 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4745 // callbacks for old records are delivered before callbacks for newer records.
CheckCacheExpiration(mDNS * const m,const mDNSu32 slot,CacheGroup * const cg)4746 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4747 {
4748 CacheRecord **rp = &cg->members;
4749
4750 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4751 m->lock_rrcache = 1;
4752
4753 while (*rp)
4754 {
4755 CacheRecord *const rr = *rp;
4756 mDNSBool recordReleased = mDNSfalse;
4757 mDNSs32 event = RRExpireTime(rr);
4758 if (m->timenow - event >= 0) // If expired, delete it
4759 {
4760 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
4761 {
4762 DNSQuestion *q = rr->CRActiveQuestion;
4763 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4764 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4765 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4766 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4767 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4768 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4769 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4770 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4771 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4772 if (((mDNSOpaque16IsZero(q->TargetQID) && (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) ||
4773 (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived)) && ActiveQuestion(q))
4774 {
4775 q->ThisQInterval = InitialQuestionInterval;
4776 q->LastQTime = m->timenow - q->ThisQInterval;
4777 SetNextQueryTime(m, q);
4778 }
4779 CacheRecordRmv(m, rr);
4780 m->rrcache_active--;
4781 }
4782
4783 event += MAX_GHOST_TIME; // Adjust so we can check for a ghost expiration
4784 if (rr->resrec.mortality == Mortality_Mortal || // Normal expired mortal record that needs released
4785 rr->resrec.rroriginalttl == 0 || // Non-mortal record that is set to be purged
4786 (rr->resrec.mortality == Mortality_Ghost && m->timenow - event >= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago
4787 { // Release as normal
4788 *rp = rr->next; // Cut it from the list before ReleaseCacheRecord
4789 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4790 MortalityDisplayString(rr->resrec.mortality),
4791 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4792 ReleaseCacheRecord(m, rr);
4793 recordReleased = mDNStrue;
4794 }
4795 else // An immortal record needs to become a ghost when it expires
4796 { // Don't release this entry
4797 if (rr->resrec.mortality == Mortality_Immortal)
4798 {
4799 rr->resrec.mortality = Mortality_Ghost; // Expired immortal records become ghosts
4800 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4801 MortalityDisplayString(rr->resrec.mortality),
4802 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4803 }
4804 }
4805 }
4806 else // else, not expired; see if we need to query
4807 {
4808 // If waiting to delay delivery, do nothing until then
4809 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4810 event = rr->DelayDelivery;
4811 else
4812 {
4813 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4814 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4815 {
4816 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
4817 event = NextCacheCheckEvent(rr); // then just record when we want the next query
4818 else // else trigger our question to go out now
4819 {
4820 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4821 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4822 m->NextScheduledQuery = m->timenow;
4823 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4824 // which will correctly update m->NextCacheCheck for us.
4825 event = m->timenow + FutureTime;
4826 }
4827 }
4828 }
4829 }
4830
4831 if (!recordReleased) // Schedule if we did not release the record
4832 {
4833 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4834 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4835 if (m->rrcache_nextcheck[slot] - event > 0)
4836 m->rrcache_nextcheck[slot] = event;
4837 rp = &rr->next;
4838 }
4839 }
4840 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4841 cg->rrcache_tail = rp;
4842 m->lock_rrcache = 0;
4843 }
4844
4845 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4846 //
4847 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4848 // returns true if there is an answer.
4849 //
4850 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4851 // returns true to indicate the same.
AnswerQuestionWithLORecord(mDNS * const m,DNSQuestion * q,mDNSBool checkOnly)4852 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4853 {
4854 AuthRecord *lr;
4855 AuthGroup *ag;
4856
4857 if (m->CurrentRecord)
4858 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4859
4860 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4861 if (ag)
4862 {
4863 m->CurrentRecord = ag->members;
4864 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4865 {
4866 AuthRecord *rr = m->CurrentRecord;
4867 m->CurrentRecord = rr->next;
4868 //
4869 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4870 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4871 //
4872 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4873 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4874 // we handle both mDNSInterface_Any and scoped questions.
4875
4876 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE)))
4877 if (LocalOnlyRecordAnswersQuestion(rr, q))
4878 {
4879 if (checkOnly)
4880 {
4881 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4882 ARDisplayString(m, rr));
4883 m->CurrentRecord = mDNSNULL;
4884 return mDNStrue;
4885 }
4886 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4887 if (m->CurrentQuestion != q)
4888 break; // If callback deleted q, then we're finished here
4889 }
4890 }
4891 }
4892 m->CurrentRecord = mDNSNULL;
4893
4894 if (m->CurrentQuestion != q)
4895 {
4896 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4897 return mDNStrue;
4898 }
4899
4900 if (q->LOAddressAnswers)
4901 {
4902 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4903 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4904 return mDNStrue;
4905 }
4906
4907 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4908 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4909 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4910 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4911 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4912 if (ag)
4913 {
4914 lr = ag->NewLocalOnlyRecords;
4915 while (lr)
4916 {
4917 if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4918 {
4919 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4920 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4921 return mDNStrue;
4922 }
4923 lr = lr->next;
4924 }
4925 }
4926 return mDNSfalse;
4927 }
4928
4929 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4930 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4931 // DNS requests.
AnswerSuppressedQuestion(mDNS * const m,DNSQuestion * q)4932 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4933 {
4934 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4935 // just deactivate the DNSQuestion.
4936 if (q->ReturnIntermed)
4937 {
4938 GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed);
4939 }
4940 else
4941 {
4942 q->ThisQInterval = 0;
4943 }
4944 }
4945
AnswerNewQuestion(mDNS * const m)4946 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4947 {
4948 mDNSBool ShouldQueryImmediately = mDNStrue;
4949 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
4950 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4951 if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q);
4952 #endif
4953 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
4954
4955 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4956
4957 if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg);
4958 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4959 m->NewQuestions = q->next;
4960 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4961 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4962 //
4963 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4964 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4965 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4966 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4967 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4968 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4969 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4970 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4971 //
4972 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4973 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4974 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4975 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4976
4977 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4978 // This should be safe, because calling the client's question callback may cause the
4979 // question list to be modified, but should not ever cause the rrcache list to be modified.
4980 // If the client's question callback deletes the question, then m->CurrentQuestion will
4981 // be advanced, and we'll exit out of the loop
4982 m->lock_rrcache = 1;
4983 if (m->CurrentQuestion) {
4984 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
4985 "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME " (" PUB_S ")",
4986 m->CurrentQuestion->request_id, mDNSVal16(m->CurrentQuestion->TargetQID),
4987 DM_NAME_PARAM(&m->CurrentQuestion->qname), DNSTypeName(m->CurrentQuestion->qtype));
4988 }
4989
4990 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4991
4992 if (q->NoAnswer == NoAnswer_Fail)
4993 {
4994 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
4995 "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME " (" PUB_S ")",
4996 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
4997
4998 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4999 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->dnsservice);
5000 #else
5001 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
5002 #endif
5003 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
5004 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
5005 // Don't touch the question if it has been stopped already
5006 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
5007 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
5008 }
5009
5010 if (m->CurrentQuestion != q)
5011 {
5012 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
5013 goto exit;
5014 }
5015
5016 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
5017 // or P2P record, then we are done.
5018 if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
5019 goto exit;
5020
5021 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5022 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5023 // the question out.
5024 if (q->Suppressed)
5025 {
5026 AnswerSuppressedQuestion(m, q);
5027 }
5028 else
5029 {
5030 CacheRecord *cr;
5031 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5032 if (SameNameCacheRecordAnswersQuestion(cr, q))
5033 {
5034 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5035 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - cr->TimeRcvd)) / mDNSPlatformOneSecond;
5036 mDNSBool IsExpired = (cr->resrec.rroriginalttl <= SecsSinceRcvd);
5037 if (IsExpired && q->allowExpired != AllowExpired_AllowExpiredAnswers) continue; // Go to next one in loop
5038
5039 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5040 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5041 if ((cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
5042 ShouldQueryImmediately = mDNSfalse;
5043 q->CurrentAnswers++;
5044 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
5045 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
5046 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5047 if (q->metrics.expiredAnswerState == ExpiredAnswer_Allowed) q->metrics.expiredAnswerState = IsExpired ? ExpiredAnswer_AnsweredWithExpired : ExpiredAnswer_AnsweredWithCache;
5048 #endif
5049 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5050 cr->LastCachedAnswerTime = m->timenow;
5051 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_hit);
5052 #endif
5053 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
5054 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5055 }
5056 else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(cr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
5057 ShouldQueryImmediately = mDNSfalse;
5058 }
5059 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5060 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5061 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
5062
5063 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5064 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_miss);
5065 #endif
5066 q->InitialCacheMiss = mDNStrue; // Initial cache check is done, so mark as a miss from now on
5067 if (q->allowExpired == AllowExpired_AllowExpiredAnswers)
5068 {
5069 q->allowExpired = AllowExpired_MakeAnswersImmortal; // After looking through the cache for an answer, demote to make immortal
5070 if (q->firstExpiredQname.c[0]) // If an original query name was saved on an expired answer, start it over in case it is updated
5071 {
5072 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5073 "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME " for allowExpiredAnswers question",
5074 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->firstExpiredQname));
5075 mDNS_StopQuery_internal(m, q); // Stop old query
5076 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5077 if (!SameDomainName(&q->qname, &q->firstExpiredQname))
5078 {
5079 Querier_PrepareQuestionForUnwindRestart(q);
5080 }
5081 #endif
5082 AssignDomainName(&q->qname, &q->firstExpiredQname); // Update qname
5083 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
5084 mDNS_StartQuery_internal(m, q); // start new query
5085 q->CNAMEReferrals = 0; // Reset referral count
5086 q->firstExpiredQname.c[0] = 0; // Erase the domain name
5087 }
5088 }
5089
5090 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5091 // Hence we don't execute the following block of code for those cases.
5092 if (ShouldQueryImmediately && ActiveQuestion(q))
5093 {
5094 debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->request_id, mDNSVal16(q->TargetQID), q->qname.c, DNSTypeName(q->qtype));
5095 q->ThisQInterval = InitialQuestionInterval;
5096 q->LastQTime = m->timenow - q->ThisQInterval;
5097 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
5098 {
5099 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5100 if (!m->RandomQueryDelay)
5101 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
5102 q->LastQTime += m->RandomQueryDelay;
5103 }
5104 }
5105
5106 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5107 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5108 // answers for this question until *after* its scheduled transmission time, in which case
5109 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5110 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5111 SetNextQueryTime(m,q);
5112
5113 exit:
5114 m->CurrentQuestion = mDNSNULL;
5115 m->lock_rrcache = 0;
5116 }
5117
5118 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5119 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
AnswerNewLocalOnlyQuestion(mDNS * const m)5120 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
5121 {
5122 AuthGroup *ag;
5123 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
5124 mDNSBool retEv = mDNSfalse;
5125 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
5126
5127 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5128
5129 if (m->CurrentQuestion)
5130 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5131 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5132 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
5133
5134 if (m->CurrentRecord)
5135 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5136
5137 // 1. First walk the LocalOnly records answering the LocalOnly question
5138 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5139 // walk the ResourceRecords list delivering the answers
5140 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5141 if (ag)
5142 {
5143 m->CurrentRecord = ag->members;
5144 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
5145 {
5146 AuthRecord *rr = m->CurrentRecord;
5147 m->CurrentRecord = rr->next;
5148 if (LocalOnlyRecordAnswersQuestion(rr, q))
5149 {
5150 retEv = mDNStrue;
5151 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
5152 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5153 }
5154 }
5155 }
5156
5157 if (m->CurrentQuestion == q)
5158 {
5159 m->CurrentRecord = m->ResourceRecords;
5160
5161 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
5162 {
5163 AuthRecord *ar = m->CurrentRecord;
5164 m->CurrentRecord = ar->next;
5165 if (AuthRecordAnswersQuestion(ar, q))
5166 {
5167 retEv = mDNStrue;
5168 AnswerLocalQuestionWithLocalAuthRecord(m, ar, QC_add);
5169 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5170 }
5171 }
5172 }
5173
5174 // The local host is the authoritative source for LocalOnly questions
5175 // so if no records exist and client requested intermediates, then generate a negative response
5176 if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed)
5177 GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse);
5178
5179 m->CurrentQuestion = mDNSNULL;
5180 m->CurrentRecord = mDNSNULL;
5181 }
5182
GetCacheEntity(mDNS * const m,const CacheGroup * const PreserveCG)5183 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
5184 {
5185 CacheEntity *e = mDNSNULL;
5186
5187 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
5188 m->lock_rrcache = 1;
5189
5190 // If we have no free records, ask the client layer to give us some more memory
5191 if (!m->rrcache_free && m->MainCallback)
5192 {
5193 if (m->rrcache_totalused != m->rrcache_size)
5194 {
5195 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5196 "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5197 m->rrcache_totalused, m->rrcache_size);
5198 }
5199
5200 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5201 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5202 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5203 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5204 // and recycle them, instead of allocating more memory.
5205 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
5206 {
5207 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
5208 "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5209 m->rrcache_size, m->rrcache_active);
5210 }
5211 else
5212 {
5213 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5214 m->MainCallback(m, mStatus_GrowCache);
5215 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5216 }
5217 }
5218
5219 // If we still have no free records, recycle all the records we can.
5220 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5221 if (!m->rrcache_free)
5222 {
5223 mDNSu32 oldtotalused = m->rrcache_totalused;
5224 mDNSu32 slot;
5225 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5226 {
5227 CacheGroup **cp = &m->rrcache_hash[slot];
5228 while (*cp)
5229 {
5230 CacheRecord **rp = &(*cp)->members;
5231 while (*rp)
5232 {
5233 // Records that answer still-active questions are not candidates for recycling
5234 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5235 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
5236 rp=&(*rp)->next;
5237 else
5238 {
5239 CacheRecord *rr = *rp;
5240 *rp = (*rp)->next; // Cut record from list
5241 ReleaseCacheRecord(m, rr);
5242 }
5243 }
5244 if ((*cp)->rrcache_tail != rp)
5245 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
5246 (*cp)->rrcache_tail = rp;
5247 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
5248 else ReleaseCacheGroup(m, cp);
5249 }
5250 }
5251 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5252 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
5253 }
5254
5255 if (m->rrcache_free) // If there are records in the free list, take one
5256 {
5257 e = m->rrcache_free;
5258 m->rrcache_free = e->next;
5259 if (++m->rrcache_totalused >= m->rrcache_report)
5260 {
5261 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "RR Cache now using %u objects", m->rrcache_totalused);
5262 if (m->rrcache_report < 100) m->rrcache_report += 10;
5263 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
5264 else m->rrcache_report += 1000;
5265 }
5266 mDNSPlatformMemZero(e, sizeof(*e));
5267 }
5268
5269 m->lock_rrcache = 0;
5270
5271 return(e);
5272 }
5273
GetCacheRecord(mDNS * const m,CacheGroup * cg,mDNSu16 RDLength)5274 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
5275 {
5276 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
5277 if (r)
5278 {
5279 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
5280 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
5281 {
5282 r->resrec.rdata = (RData*) mDNSPlatformMemAllocateClear(sizeofRDataHeader + RDLength);
5283 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
5284 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
5285 }
5286 }
5287 return(r);
5288 }
5289
GetCacheGroup(mDNS * const m,const mDNSu32 slot,const ResourceRecord * const rr)5290 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
5291 {
5292 mDNSu16 namelen = DomainNameLength(rr->name);
5293 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
5294 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
5295 cg->next = m->rrcache_hash[slot];
5296 cg->namehash = rr->namehash;
5297 cg->members = mDNSNULL;
5298 cg->rrcache_tail = &cg->members;
5299 if (namelen > sizeof(cg->namestorage))
5300 cg->name = (domainname *) mDNSPlatformMemAllocate(namelen);
5301 else
5302 cg->name = (domainname*)cg->namestorage;
5303 if (!cg->name)
5304 {
5305 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
5306 ReleaseCacheEntity(m, (CacheEntity*)cg);
5307 return(mDNSNULL);
5308 }
5309 AssignDomainName(cg->name, rr->name);
5310
5311 if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
5312 m->rrcache_hash[slot] = cg;
5313 if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
5314
5315 return(cg);
5316 }
5317
mDNS_PurgeCacheResourceRecord(mDNS * const m,CacheRecord * rr)5318 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
5319 {
5320 mDNS_CheckLock(m);
5321
5322 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5323 // a positive answer using an expired record (e.g. from an interface that has gone away).
5324 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5325 // summary deletion without giving the proper callback to any questions that are monitoring it.
5326 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5327 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
5328 rr->UnansweredQueries = MaxUnansweredQueries;
5329 rr->resrec.rroriginalttl = 0;
5330 SetNextCacheCheckTimeForRecord(m, rr);
5331 }
5332
mDNS_TimeNow(const mDNS * const m)5333 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
5334 {
5335 mDNSs32 time;
5336 mDNSPlatformLock(m);
5337 if (m->mDNS_busy)
5338 {
5339 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5340 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
5341 }
5342
5343 if (m->timenow) time = m->timenow;
5344 else time = mDNS_TimeNow_NoLock(m);
5345 mDNSPlatformUnlock(m);
5346 return(time);
5347 }
5348
5349 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5350 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5351 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5352 #define SetSPSProxyListChanged(X) do { \
5353 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5354 m->SPSProxyListChanged = (X); } while(0)
5355
5356 // Called from mDNS_Execute() to expire stale proxy records
CheckProxyRecords(mDNS * const m,AuthRecord * list)5357 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
5358 {
5359 m->CurrentRecord = list;
5360 while (m->CurrentRecord)
5361 {
5362 AuthRecord *rr = m->CurrentRecord;
5363 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
5364 {
5365 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5366 // so we need to cease proxying for *all* records we may have, expired or not.
5367 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
5368 {
5369 if (m->NextScheduledSPS - rr->TimeExpire > 0)
5370 m->NextScheduledSPS = rr->TimeExpire;
5371 }
5372 else // else proxy record expired, so remove it
5373 {
5374 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5375 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
5376 SetSPSProxyListChanged(rr->resrec.InterfaceID);
5377 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5378 // Don't touch rr after this -- memory may have been free'd
5379 }
5380 }
5381 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5382 // new records could have been added to the end of the list as a result of that call.
5383 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5384 m->CurrentRecord = rr->next;
5385 }
5386 }
5387
CheckRmvEventsForLocalRecords(mDNS * const m)5388 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5389 {
5390 while (m->CurrentRecord)
5391 {
5392 AuthRecord *rr = m->CurrentRecord;
5393 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5394 {
5395 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5396 rr->resrec.RecordType = kDNSRecordTypeShared;
5397 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv);
5398 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5399 {
5400 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5401 rr->AnsweredLocalQ = mDNSfalse;
5402 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5403 // For LocalOnly records, we don't do that and hence we need to do that here.
5404 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5405 }
5406 }
5407 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5408 m->CurrentRecord = rr->next;
5409 }
5410 }
5411
TimeoutQuestions_internal(mDNS * const m,DNSQuestion * questions,mDNSInterfaceID InterfaceID)5412 mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID)
5413 {
5414 if (m->CurrentQuestion)
5415 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5416 DNSTypeName(m->CurrentQuestion->qtype));
5417 m->CurrentQuestion = questions;
5418 while (m->CurrentQuestion)
5419 {
5420 DNSQuestion *const q = m->CurrentQuestion;
5421 if (q->StopTime)
5422 {
5423 if (!q->TimeoutQuestion)
5424 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5425
5426 if (m->timenow - q->StopTime >= 0)
5427 {
5428 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5429 q->LOAddressAnswers = 0; // unset since timing out the question
5430 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse);
5431 if (m->CurrentQuestion == q) q->StopTime = 0;
5432 }
5433 else
5434 {
5435 if (m->NextScheduledStopTime - q->StopTime > 0)
5436 m->NextScheduledStopTime = q->StopTime;
5437 }
5438 }
5439 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5440 // We can't do this at the start of the loop because GenerateNegativeResponse
5441 // depends on having m->CurrentQuestion point to the right question
5442 if (m->CurrentQuestion == q)
5443 m->CurrentQuestion = q->next;
5444 }
5445 m->CurrentQuestion = mDNSNULL;
5446 }
5447
TimeoutQuestions(mDNS * const m)5448 mDNSlocal void TimeoutQuestions(mDNS *const m)
5449 {
5450 m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future
5451 TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any);
5452 TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly);
5453 }
5454
mDNSCoreFreeProxyRR(mDNS * const m)5455 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5456 {
5457 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5458 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5459 while (rrPtr)
5460 {
5461 rrNext = rrPtr->next;
5462 mDNSPlatformMemFree(rrPtr);
5463 rrPtr = rrNext;
5464 }
5465 m->SPSRRSet = mDNSNULL;
5466 }
5467
mDNS_Execute(mDNS * const m)5468 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5469 {
5470 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
5471
5472 if (m->timenow - m->NextScheduledEvent >= 0)
5473 {
5474 int i;
5475 AuthRecord *head, *tail;
5476 mDNSu32 slot;
5477 AuthGroup *ag;
5478
5479 verbosedebugf("mDNS_Execute");
5480
5481 if (m->CurrentQuestion)
5482 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5483 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5484
5485 if (m->CurrentRecord)
5486 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5487
5488 // 1. If we're past the probe suppression time, we can clear it
5489 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5490
5491 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5492 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5493
5494 // 3. Purge our cache of stale old records
5495 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5496 {
5497 mDNSu32 numchecked = 0;
5498 m->NextCacheCheck = m->timenow + FutureTime;
5499 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5500 {
5501 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5502 {
5503 CacheGroup **cp = &m->rrcache_hash[slot];
5504 m->rrcache_nextcheck[slot] = m->timenow + FutureTime;
5505 while (*cp)
5506 {
5507 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5508 numchecked++;
5509 CheckCacheExpiration(m, slot, *cp);
5510 if ((*cp)->members) cp=&(*cp)->next;
5511 else ReleaseCacheGroup(m, cp);
5512 }
5513 }
5514 // Even if we didn't need to actually check this slot yet, still need to
5515 // factor its nextcheck time into our overall NextCacheCheck value
5516 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5517 m->NextCacheCheck = m->rrcache_nextcheck[slot];
5518 }
5519 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5520 }
5521
5522 if (m->timenow - m->NextScheduledSPS >= 0)
5523 {
5524 m->NextScheduledSPS = m->timenow + FutureTime;
5525 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
5526 CheckProxyRecords(m, m->ResourceRecords);
5527 }
5528
5529 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
5530
5531 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5532 // as records could have expired during that check
5533 if (m->timenow - m->NextScheduledKA >= 0)
5534 {
5535 m->NextScheduledKA = m->timenow + FutureTime;
5536 mDNS_SendKeepalives(m);
5537 }
5538
5539 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5540 if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0))
5541 {
5542 // Schedule immediate network change processing to leave the multicast group
5543 // since the delay time has expired since the previous active registration or query.
5544 m->NetworkChanged = m->timenow;
5545 m->NextBonjourDisableTime = 0;
5546 m->BonjourEnabled = 0;
5547
5548 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5549 }
5550 #endif
5551
5552 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5553 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5554 {
5555 m->AnnounceOwner = 0;
5556 }
5557
5558 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5559 {
5560 m->DelaySleep = 0;
5561 if (m->SleepState == SleepState_Transferring)
5562 {
5563 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5564 BeginSleepProcessing(m);
5565 }
5566 }
5567
5568 // 4. See if we can answer any of our new local questions from the cache
5569 for (i=0; m->NewQuestions && i<1000; i++)
5570 {
5571 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5572 AnswerNewQuestion(m);
5573 }
5574 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5575
5576 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5577 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5578 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5579 {
5580 m->LocalRemoveEvents = mDNSfalse;
5581 m->CurrentRecord = m->ResourceRecords;
5582 CheckRmvEventsForLocalRecords(m);
5583 // Walk the LocalOnly records and deliver the RMV events
5584 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5585 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5586 {
5587 m->CurrentRecord = ag->members;
5588 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5589 }
5590 }
5591
5592 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5593
5594 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5595 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5596
5597 head = tail = mDNSNULL;
5598 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5599 {
5600 AuthRecord *rr = m->NewLocalRecords;
5601 m->NewLocalRecords = m->NewLocalRecords->next;
5602 if (LocalRecordReady(rr))
5603 {
5604 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5605 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5606 }
5607 else if (!rr->next)
5608 {
5609 // If we have just one record that is not ready, we don't have to unlink and
5610 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5611 // terminate and set the NewLocalRecords to rr.
5612 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5613 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5614 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5615
5616 head = rr;
5617 }
5618 else
5619 {
5620 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
5621 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5622 // if this is the first record we are skipping, move to the end of the list.
5623 // if we have already skipped records before, append it at the end.
5624 while (*p && *p != rr) p=&(*p)->next;
5625 if (*p) *p = rr->next; // Cut this record from the list
5626 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5627 if (!head)
5628 {
5629 while (*p) p=&(*p)->next;
5630 *p = rr;
5631 head = tail = rr;
5632 }
5633 else
5634 {
5635 tail->next = rr;
5636 tail = rr;
5637 }
5638 rr->next = mDNSNULL;
5639 }
5640 }
5641 m->NewLocalRecords = head;
5642 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5643
5644 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5645
5646 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5647 // to our local questions
5648 if (m->NewLocalOnlyRecords)
5649 {
5650 m->NewLocalOnlyRecords = mDNSfalse;
5651 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5652 {
5653 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5654 {
5655 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5656 {
5657 AuthRecord *rr = ag->NewLocalOnlyRecords;
5658 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5659 // LocalOnly records should always be ready as they never probe
5660 if (LocalRecordReady(rr))
5661 {
5662 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5663 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5664 }
5665 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5666 }
5667 // We limit about 100 per AuthGroup that can be serviced at a time
5668 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5669 }
5670 }
5671 }
5672
5673 // 5. See what packets we need to send
5674 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5675 DiscardDeregistrations(m);
5676 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5677 {
5678 // If the platform code is ready, and we're not suppressing packet generation right now
5679 // then send our responses, probes, and questions.
5680 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5681 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5682 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5683 // Finally, we send responses, including the previously mentioned records that just completed probing.
5684 m->SuppressSending = 0;
5685
5686 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5687 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5688 if (m->timenow - m->NextScheduledQuery >= 0)
5689 {
5690 DNSQuestion *q;
5691 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5692 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5693 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5694 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5695 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5696 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5697 }
5698 if (m->timenow - m->NextScheduledProbe >= 0)
5699 {
5700 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5701 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5702 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5703 }
5704
5705 // 7. Send Response packets, including probing records just advanced to announcing state
5706 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5707 if (m->timenow - m->NextScheduledResponse >= 0)
5708 {
5709 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5710 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5711 }
5712 }
5713
5714 // Clear RandomDelay values, ready to pick a new different value next time
5715 m->RandomQueryDelay = 0;
5716 m->RandomReconfirmDelay = 0;
5717
5718 // See if any questions (or local-only questions) have timed out
5719 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5720 #ifndef UNICAST_DISABLED
5721 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5722 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5723 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5724 #endif
5725 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5726 extern void serviceBLE();
5727 if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE();
5728 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5729 }
5730
5731 // Note about multi-threaded systems:
5732 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5733 // performing mDNS API operations that change our next scheduled event time.
5734 //
5735 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5736 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5737 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5738 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5739 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5740 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5741 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5742 // without blocking. This avoids the race condition between the signal from the other thread arriving
5743 // just *before* or just *after* the main thread enters the blocking primitive.
5744 //
5745 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5746 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5747 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5748 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5749 // by the time it gets to the timer callback function).
5750
5751 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5752 return(m->NextScheduledEvent);
5753 }
5754
5755 #ifndef UNICAST_DISABLED
SuspendLLQs(mDNS * m)5756 mDNSlocal void SuspendLLQs(mDNS *m)
5757 {
5758 DNSQuestion *q;
5759 for (q = m->Questions; q; q = q->next)
5760 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5761 { q->ReqLease = 0; sendLLQRefresh(m, q); }
5762 }
5763 #endif // UNICAST_DISABLED
5764
QuestionHasLocalAnswers(mDNS * const m,DNSQuestion * q)5765 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5766 {
5767 AuthRecord *rr;
5768 AuthGroup *ag;
5769
5770 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5771 if (ag)
5772 {
5773 for (rr = ag->members; rr; rr=rr->next)
5774 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5775 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5776 {
5777 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5778 return mDNStrue;
5779 }
5780 }
5781 return mDNSfalse;
5782 }
5783
5784 // ActivateUnicastQuery() is called from three places:
5785 // 1. When a new question is created
5786 // 2. On wake from sleep
5787 // 3. When the DNS configuration changes
5788 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5789 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
ActivateUnicastQuery(mDNS * const m,DNSQuestion * const question,mDNSBool ScheduleImmediately)5790 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5791 {
5792 if (!question->DuplicateOf)
5793 {
5794 debugf("ActivateUnicastQuery: %##s %s%s",
5795 question->qname.c, DNSTypeName(question->qtype), ScheduleImmediately ? " ScheduleImmediately" : "");
5796 question->CNAMEReferrals = 0;
5797 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5798 if (question->LongLived)
5799 {
5800 question->state = LLQ_Init;
5801 question->id = zeroOpaque64;
5802 question->servPort = zeroIPPort;
5803 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5804 }
5805 // If the question has local answers, then we don't want answers from outside
5806 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5807 {
5808 question->ThisQInterval = InitialQuestionInterval;
5809 question->LastQTime = m->timenow - question->ThisQInterval;
5810 SetNextQueryTime(m, question);
5811 }
5812 }
5813 }
5814
5815 // Caller should hold the lock
mDNSCoreRestartAddressQueries(mDNS * const m,mDNSBool SearchDomainsChanged,FlushCache flushCacheRecords,CallbackBeforeStartQuery BeforeStartCallback,void * context)5816 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5817 CallbackBeforeStartQuery BeforeStartCallback, void *context)
5818 {
5819 DNSQuestion *q;
5820 DNSQuestion *restart = mDNSNULL;
5821
5822 mDNS_CheckLock(m);
5823
5824 // 1. Flush the cache records
5825 if (flushCacheRecords) flushCacheRecords(m);
5826
5827 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5828 // we are going to stop the question. Hence we need to deliver the RMV event before we
5829 // stop the question.
5830 //
5831 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5832 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5833 // *any* other question which could be the next one that we may process here. RestartQuestion
5834 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5835 // if the "next" question is stopped while the CurrentQuestion is stopped
5836
5837 if (m->RestartQuestion)
5838 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5839 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5840
5841 m->RestartQuestion = m->Questions;
5842 while (m->RestartQuestion)
5843 {
5844 q = m->RestartQuestion;
5845 m->RestartQuestion = q->next;
5846 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5847 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5848 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5849 // question followed by the original query that refers to this GetZoneData question, we will end up
5850 // freeing the GetZoneData question and then start the "freed" question at the end.
5851
5852 if (IsGetZoneDataQuestion(q))
5853 {
5854 DNSQuestion *refq = q->next;
5855 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5856 // debug stuff, we just try to find the referencing question and don't do much with it
5857 while (refq)
5858 {
5859 if (q == &refq->nta->question)
5860 {
5861 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5862 }
5863 refq = refq->next;
5864 }
5865 continue;
5866 }
5867
5868 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5869 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5870
5871 // If the search domains did not change, then we restart all the queries. Otherwise, only
5872 // for queries for which we "might" have appended search domains ("might" because we may
5873 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5874 if (!SearchDomainsChanged || q->AppendSearchDomains)
5875 {
5876 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5877 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5878 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5879 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5880 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5881 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5882 // for the original query using these cache entries as ADDs were never delivered using these cache
5883 // entries and hence this order is needed.
5884
5885 // If the query is suppressed, the RMV events won't be delivered
5886 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5887
5888 // Suppressed status does not affect questions that are answered using local records
5889 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5890
5891 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q,
5892 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains);
5893 mDNS_StopQuery_internal(m, q);
5894 if (q->ResetHandler) q->ResetHandler(q);
5895 q->next = restart;
5896 restart = q;
5897 }
5898 }
5899
5900 // 3. Callback before we start the query
5901 if (BeforeStartCallback) BeforeStartCallback(m, context);
5902
5903 // 4. Restart all the stopped queries
5904 while (restart)
5905 {
5906 q = restart;
5907 restart = restart->next;
5908 q->next = mDNSNULL;
5909 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5910 mDNS_StartQuery_internal(m, q);
5911 }
5912 }
5913
mDNSCoreRestartQueries(mDNS * const m)5914 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5915 {
5916 DNSQuestion *q;
5917
5918 #ifndef UNICAST_DISABLED
5919 // Retrigger all our uDNS questions
5920 if (m->CurrentQuestion)
5921 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5922 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5923 m->CurrentQuestion = m->Questions;
5924 while (m->CurrentQuestion)
5925 {
5926 q = m->CurrentQuestion;
5927 m->CurrentQuestion = m->CurrentQuestion->next;
5928 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5929 {
5930 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5931 mdns_querier_forget(&q->querier);
5932 #endif
5933 ActivateUnicastQuery(m, q, mDNStrue);
5934 }
5935 }
5936 #endif
5937
5938 // Retrigger all our mDNS questions
5939 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5940 mDNSCoreRestartQuestion(m, q);
5941 }
5942
5943 // restart question if it's multicast and currently active
mDNSCoreRestartQuestion(mDNS * const m,DNSQuestion * q)5944 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5945 {
5946 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5947 {
5948 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
5949 q->RequestUnicast = kDefaultRequestUnicastCount;
5950 q->LastQTime = m->timenow - q->ThisQInterval;
5951 q->RecentAnswerPkts = 0;
5952 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5953 m->NextScheduledQuery = m->timenow;
5954 }
5955 }
5956
5957 // restart the probe/announce cycle for multicast record
mDNSCoreRestartRegistration(mDNS * const m,AuthRecord * rr,int announceCount)5958 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5959 {
5960 if (!AuthRecord_uDNS(rr))
5961 {
5962 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5963 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5964
5965 if (mDNS_KeepaliveRecord(&rr->resrec))
5966 {
5967 rr->AnnounceCount = 0; // Do not announce keepalive records
5968 }
5969 else
5970 {
5971 // announceCount < 0 indicates default announce count should be used
5972 if (announceCount < 0)
5973 announceCount = InitialAnnounceCount;
5974 if (rr->AnnounceCount < (mDNSu8)announceCount)
5975 rr->AnnounceCount = (mDNSu8)announceCount;
5976 }
5977
5978 rr->SendNSECNow = mDNSNULL;
5979 InitializeLastAPTime(m, rr);
5980 }
5981 }
5982
5983 // ***************************************************************************
5984 #if COMPILER_LIKES_PRAGMA_MARK
5985 #pragma mark -
5986 #pragma mark - Power Management (Sleep/Wake)
5987 #endif
5988
mDNS_UpdateAllowSleep(mDNS * const m)5989 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
5990 {
5991 #ifndef IDLESLEEPCONTROL_DISABLED
5992 mDNSBool allowSleep = mDNStrue;
5993 char reason[128];
5994
5995 reason[0] = 0;
5996
5997 if (m->SystemSleepOnlyIfWakeOnLAN)
5998 {
5999 // Don't sleep if we are a proxy for any services
6000 if (m->ProxyRecords)
6001 {
6002 allowSleep = mDNSfalse;
6003 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
6004 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
6005 }
6006
6007 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
6008 {
6009 // Scan the list of active interfaces
6010 NetworkInterfaceInfo *intf;
6011 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6012 {
6013 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6014 {
6015 // Disallow sleep if this interface doesn't support NetWake
6016 if (!intf->NetWake)
6017 {
6018 allowSleep = mDNSfalse;
6019 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
6020 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
6021 break;
6022 }
6023
6024 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
6025 // that will be offloaded. If not, we should prevent sleep.
6026 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
6027 #if APPLE_OSX_mDNSResponder
6028 if (!SupportsInNICProxy(intf))
6029 #endif
6030 {
6031 // Disallow sleep if there is no sleep proxy server
6032 const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
6033 if ( cr == mDNSNULL)
6034 {
6035 allowSleep = mDNSfalse;
6036 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
6037 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
6038 break;
6039 }
6040 else if (m->SPSType != 0)
6041 {
6042 mDNSu32 mymetric = LocalSPSMetric(m);
6043 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
6044 if (metric >= mymetric)
6045 {
6046 allowSleep = mDNSfalse;
6047 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
6048 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
6049 break;
6050 }
6051 }
6052 }
6053 }
6054 }
6055 }
6056 }
6057
6058 // Call the platform code to enable/disable sleep
6059 mDNSPlatformSetAllowSleep(allowSleep, reason);
6060 #else
6061 (void) m;
6062 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6063 }
6064
mDNSUpdateOkToSend(mDNS * const m,AuthRecord * rr,NetworkInterfaceInfo * const intf,mDNSu32 scopeid)6065 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
6066 {
6067 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6068 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6069 // to send.
6070 if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
6071 m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
6072 {
6073 return mDNSfalse;
6074 }
6075
6076 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6077 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6078 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6079 // updateid and we should have returned from above.
6080 //
6081 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6082 // platform function to extract the value from "intf" every time.
6083
6084 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6085 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6086 return mDNStrue;
6087
6088 return mDNSfalse;
6089 }
6090
UpdateRMAC(mDNS * const m,void * context)6091 mDNSexport void UpdateRMAC(mDNS *const m, void *context)
6092 {
6093 IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
6094 m->CurrentRecord = m->ResourceRecords;
6095
6096 if (!addrmap)
6097 {
6098 LogMsg("UpdateRMAC: Address mapping is NULL");
6099 return;
6100 }
6101
6102 while (m->CurrentRecord)
6103 {
6104 AuthRecord *rr = m->CurrentRecord;
6105 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6106 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
6107 {
6108 mDNSAddr raddr;
6109 getKeepaliveRaddr(m, rr, &raddr);
6110 if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
6111 {
6112 // Update the MAC address only if it is not a zero MAC address
6113 mDNSEthAddr macAddr;
6114 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
6115 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
6116 {
6117 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
6118 }
6119 }
6120 }
6121 m->CurrentRecord = rr->next;
6122 }
6123
6124 if (addrmap)
6125 mDNSPlatformMemFree(addrmap);
6126
6127 }
6128
UpdateKeepaliveRData(mDNS * const m,AuthRecord * rr,NetworkInterfaceInfo * const intf,mDNSBool updateMac,char * ethAddr)6129 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
6130 {
6131 mDNSu16 newrdlength;
6132 mDNSAddr laddr = zeroAddr;
6133 mDNSAddr raddr = zeroAddr;
6134 mDNSEthAddr eth = zeroEthAddr;
6135 mDNSIPPort lport = zeroIPPort;
6136 mDNSIPPort rport = zeroIPPort;
6137 mDNSu32 timeout = 0;
6138 mDNSu32 seq = 0;
6139 mDNSu32 ack = 0;
6140 mDNSu16 win = 0;
6141 UTF8str255 txt;
6142 int rdsize;
6143 RData *newrd;
6144 mDNSTCPInfo mti;
6145 mStatus ret;
6146
6147 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6148 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6149 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win);
6150 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
6151 {
6152 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
6153 return mStatus_UnknownErr;
6154 }
6155
6156 if (updateMac)
6157 {
6158 if (laddr.type == mDNSAddrType_IPv4)
6159 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%s", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ethAddr);
6160 else
6161 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);
6162
6163 }
6164 else
6165 {
6166 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6167 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6168 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6169 mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
6170 ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti);
6171 if (ret != mStatus_NoError)
6172 {
6173 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
6174 return ret;
6175 }
6176 if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
6177 {
6178 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID);
6179 return mStatus_BadParamErr;
6180 }
6181
6182 if (laddr.type == mDNSAddrType_IPv4)
6183 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ð, mti.seq, mti.ack, mti.window);
6184 else
6185 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);
6186 }
6187
6188 // Did we insert a null byte at the end ?
6189 if (newrdlength == (sizeof(txt.c) - 1))
6190 {
6191 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
6192 return mStatus_NoMemoryErr;
6193 }
6194
6195 // Include the length for the null byte at the end
6196 txt.c[0] = newrdlength + 1;
6197 // Account for the first length byte and the null byte at the end
6198 newrdlength += 2;
6199
6200 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
6201 newrd = (RData *) mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
6202 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
6203
6204 newrd->MaxRDLength = (mDNSu16) rdsize;
6205 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
6206
6207 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6208 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6209 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6210 // free that memory here before copying in the new data.
6211 if ( rr->resrec.rdata != &rr->rdatastorage)
6212 {
6213 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
6214 mDNSPlatformMemFree(rr->resrec.rdata);
6215 }
6216 SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata
6217
6218 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
6219 return mStatus_NoError;
6220 }
6221
SendSPSRegistrationForOwner(mDNS * const m,NetworkInterfaceInfo * const intf,const mDNSOpaque16 id,const OwnerOptData * const owner)6222 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
6223 {
6224 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
6225 const int sps = intf->NextSPSAttempt / 3;
6226 AuthRecord *rr;
6227 mDNSOpaque16 msgid;
6228 mDNSu32 scopeid;
6229
6230 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6231 if (!intf->SPSAddr[sps].type)
6232 {
6233 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6234 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6235 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6236 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
6237 goto exit;
6238 }
6239
6240 // Mark our mDNS records (not unicast records) for transfer to SPS
6241 if (mDNSOpaque16IsZero(id))
6242 {
6243 // We may have to register this record over multiple interfaces and we don't want to
6244 // overwrite the id. We send the registration over interface X with id "IDX" and before
6245 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6246 // for "IDX". Hence, we want to use the same ID across all interfaces.
6247 //
6248 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6249 // option check below will set the same ID across the records from the same owner. Records
6250 // with different owner option gets different ID.
6251 msgid = mDNS_NewMessageID(m);
6252 for (rr = m->ResourceRecords; rr; rr=rr->next)
6253 {
6254 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
6255 {
6256 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6257 {
6258 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6259 {
6260 rr->SendRNow = mDNSInterfaceMark; // mark it now
6261 // When we are registering on the first interface, rr->updateid is zero in which case
6262 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6263 // At the end, all the updates sent across all the interfaces with the same ID.
6264 if (mDNSOpaque16IsZero(rr->updateid))
6265 rr->updateid = msgid;
6266 else
6267 msgid = rr->updateid;
6268 }
6269 }
6270 }
6271 }
6272 }
6273 else
6274 msgid = id;
6275
6276 while (1)
6277 {
6278 mDNSu8 *p = m->omsg.data;
6279 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6280 // For now we follow that same logic for SPS registrations too.
6281 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6282 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6283 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
6284
6285 for (rr = m->ResourceRecords; rr; rr=rr->next)
6286 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
6287 {
6288 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6289 {
6290 mDNSu8 *newptr;
6291 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
6292
6293 // If we can't update the keepalive record, don't send it
6294 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
6295 {
6296 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
6297 {
6298 bit_clr_opaque64(rr->updateIntID, scopeid);
6299 }
6300 rr->SendRNow = mDNSNULL;
6301 continue;
6302 }
6303
6304 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
6305 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6306 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
6307 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
6308 if (!newptr)
6309 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
6310 else
6311 {
6312 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));
6313 rr->SendRNow = mDNSNULL;
6314 rr->ThisAPInterval = mDNSPlatformOneSecond;
6315 rr->LastAPTime = m->timenow;
6316 // should be initialized above
6317 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
6318 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6319 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
6320 p = newptr;
6321 }
6322 }
6323 }
6324
6325 if (!m->omsg.h.mDNS_numUpdates) break;
6326 else
6327 {
6328 AuthRecord opt;
6329 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
6330 opt.resrec.rrclass = NormalMaxDNSMessageData;
6331 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
6332 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
6333 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
6334 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
6335 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
6336 if (!owner->HMAC.l[0]) // If no owner data,
6337 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
6338 else // otherwise, use the owner data we were given
6339 {
6340 opt.resrec.rdata->u.opt[1].u.owner = *owner;
6341 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
6342 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
6343 }
6344 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
6345 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6346 if (!p)
6347 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
6348 else
6349 {
6350 mStatus err;
6351
6352 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
6353 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
6354 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6355 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSfalse);
6356 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
6357 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
6358 {
6359 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
6360 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
6361 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
6362 return;
6363 }
6364 }
6365 }
6366 }
6367
6368 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
6369
6370 exit:
6371 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
6372 }
6373
RecordIsFirstOccurrenceOfOwner(mDNS * const m,const AuthRecord * const rr)6374 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
6375 {
6376 AuthRecord *ar;
6377 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
6378 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
6379 return mDNStrue;
6380 }
6381
mDNSCoreStoreProxyRR(mDNS * const m,const mDNSInterfaceID InterfaceID,AuthRecord * const rr)6382 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6383 {
6384 AuthRecord *newRR = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(*newRR));
6385 if (newRR == mDNSNULL)
6386 {
6387 LogSPS("%s : could not allocate memory for new resource record", __func__);
6388 return;
6389 }
6390
6391 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6392 rr->resrec.rroriginalttl, rr->resrec.RecordType,
6393 rr->ARType, mDNSNULL, mDNSNULL);
6394
6395 AssignDomainName(&newRR->namestorage, &rr->namestorage);
6396 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6397 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6398 newRR->resrec.rrclass = rr->resrec.rrclass;
6399
6400 if (rr->resrec.rrtype == kDNSType_A)
6401 {
6402 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4;
6403 }
6404 else if (rr->resrec.rrtype == kDNSType_AAAA)
6405 {
6406 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6407 }
6408 SetNewRData(&newRR->resrec, mDNSNULL, 0);
6409
6410 // Insert the new node at the head of the list.
6411 newRR->next = m->SPSRRSet;
6412 m->SPSRRSet = newRR;
6413 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6414 }
6415
6416 // Some records are interface specific and some are not. The ones that are supposed to be registered
6417 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6418 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6419 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6420 // registration on all the interfaces
SPSInitRecordsBeforeUpdate(mDNS * const m,mDNSOpaque64 updateIntID,mDNSBool * WakeOnlyService)6421 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6422 {
6423 AuthRecord *ar;
6424 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6425
6426 *WakeOnlyService = mDNSfalse;
6427
6428 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6429 // make sure that the old sleep proxy records are removed.
6430 mDNSCoreFreeProxyRR(m);
6431
6432 // For records that are registered only on a specific interface, mark only that bit as it will
6433 // never be registered on any other interface. For others, it should be sent on all interfaces.
6434 for (ar = m->ResourceRecords; ar; ar=ar->next)
6435 {
6436 ar->updateIntID = zeroOpaque64;
6437 ar->updateid = zeroID;
6438 if (AuthRecord_uDNS(ar))
6439 {
6440 continue;
6441 }
6442 if (ar->AuthFlags & AuthFlagsWakeOnly)
6443 {
6444 if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6445 {
6446 ar->ImmedAnswer = mDNSInterfaceMark;
6447 *WakeOnlyService = mDNStrue;
6448 continue;
6449 }
6450 }
6451 if (!ar->resrec.InterfaceID)
6452 {
6453 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6454 ar->updateIntID = updateIntID;
6455 }
6456 else
6457 {
6458 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6459 // exactly this.
6460 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6461 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6462 {
6463 bit_set_opaque64(ar->updateIntID, scopeid);
6464 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6465 ar->updateIntID.l[0], ARDisplayString(m, ar));
6466 }
6467 else
6468 {
6469 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6470 }
6471 }
6472 // Store the A and AAAA records that we registered with the sleep proxy.
6473 // We will use this to prevent spurious name conflicts that may occur when we wake up
6474 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6475 {
6476 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6477 }
6478 }
6479 }
6480
SendSPSRegistration(mDNS * const m,NetworkInterfaceInfo * const intf,const mDNSOpaque16 id)6481 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6482 {
6483 AuthRecord *ar;
6484 OwnerOptData owner = zeroOwner;
6485
6486 SendSPSRegistrationForOwner(m, intf, id, &owner);
6487
6488 for (ar = m->ResourceRecords; ar; ar=ar->next)
6489 {
6490 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6491 {
6492 owner = ar->WakeUp;
6493 SendSPSRegistrationForOwner(m, intf, id, &owner);
6494 }
6495 }
6496 }
6497
6498 // RetrySPSRegistrations is called from SendResponses, with the lock held
RetrySPSRegistrations(mDNS * const m)6499 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6500 {
6501 AuthRecord *rr;
6502 NetworkInterfaceInfo *intf;
6503
6504 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6505 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6506 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6507 intf->NextSPSAttemptTime++;
6508
6509 // Retry any record registrations that are due
6510 for (rr = m->ResourceRecords; rr; rr=rr->next)
6511 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6512 {
6513 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6514 {
6515 // If we still have registrations pending on this interface, send it now
6516 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6517 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6518 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6519 {
6520 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6521 SendSPSRegistration(m, intf, rr->updateid);
6522 }
6523 }
6524 }
6525
6526 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6527 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6528 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6529 intf->NextSPSAttempt++;
6530 }
6531
NetWakeResolve(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)6532 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6533 {
6534 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6535 int sps = (int)(question - intf->NetWakeResolve);
6536 (void)m; // Unused
6537 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6538
6539 if (!AddRecord) return; // Don't care about REMOVE events
6540 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
6541
6542 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6543
6544 if (answer->rrtype == kDNSType_SRV)
6545 {
6546 // 1. Got the SRV record; now look up the target host's IP address
6547 mDNS_StopQuery(m, question);
6548 intf->SPSPort[sps] = answer->rdata->u.srv.port;
6549 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6550 question->qtype = kDNSType_A;
6551 mDNS_StartQuery(m, question);
6552 }
6553 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6554 {
6555 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6556 mDNS_StopQuery(m, question);
6557 question->ThisQInterval = -1;
6558 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6559 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6560 mDNS_Lock(m);
6561 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6562 mDNS_Unlock(m);
6563 }
6564 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6565 {
6566 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6567 mDNS_StopQuery(m, question);
6568 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6569 question->qtype = kDNSType_AAAA;
6570 mDNS_StartQuery(m, question);
6571 }
6572 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6573 {
6574 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6575 mDNS_StopQuery(m, question);
6576 question->ThisQInterval = -1;
6577 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6578 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6579 mDNS_Lock(m);
6580 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6581 mDNS_Unlock(m);
6582 }
6583 }
6584
mDNSCoreHaveAdvertisedMulticastServices(mDNS * const m)6585 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6586 {
6587 AuthRecord *rr;
6588 for (rr = m->ResourceRecords; rr; rr=rr->next)
6589 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6590 return mDNStrue;
6591 return mDNSfalse;
6592 }
6593
6594 #define WAKE_ONLY_SERVICE 1
6595 #define AC_ONLY_SERVICE 2
6596
6597 #ifdef APPLE_OSX_mDNSResponder
SendGoodbyesForSelectServices(mDNS * const m,mDNSBool * servicePresent,mDNSu32 serviceType)6598 mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6599 {
6600 AuthRecord *rr;
6601 *servicePresent = mDNSfalse;
6602
6603 // Mark all the records we need to deregister and send them
6604 for (rr = m->ResourceRecords; rr; rr=rr->next)
6605 {
6606 // If the service type is wake only service and the auth flags match and requires a goodbye
6607 // OR if the service type is AC only and it is not a keepalive record,
6608 // mark the records we need to deregister and send them
6609 if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6610 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6611 (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6612 {
6613 rr->ImmedAnswer = mDNSInterfaceMark;
6614 *servicePresent = mDNStrue;
6615 }
6616 }
6617 }
6618 #endif
6619
6620 #ifdef APPLE_OSX_mDNSResponder
6621 // This function is used only in the case of local NIC proxy. For external
6622 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6623 // walk the resource records.
SendGoodbyesForWakeOnlyService(mDNS * const m,mDNSBool * WakeOnlyService)6624 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6625 {
6626 return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6627 }
6628 #endif // APPLE_OSX_mDNSResponder
6629
6630
SendSleepGoodbyes(mDNS * const m,mDNSBool AllInterfaces,mDNSBool unicast)6631 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6632 {
6633 AuthRecord *rr;
6634 m->SleepState = SleepState_Sleeping;
6635
6636 // If AllInterfaces is not set, the caller has already marked it appropriately
6637 // on which interfaces this should be sent.
6638 if (AllInterfaces)
6639 {
6640 NetworkInterfaceInfo *intf;
6641 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6642 {
6643 intf->SendGoodbyes = 1;
6644 }
6645 }
6646 if (unicast)
6647 {
6648 #ifndef UNICAST_DISABLED
6649 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
6650 #endif /* UNICAST_DISABLED */
6651 }
6652
6653 // Mark all the records we need to deregister and send them
6654 for (rr = m->ResourceRecords; rr; rr=rr->next)
6655 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6656 rr->ImmedAnswer = mDNSInterfaceMark;
6657 SendResponses(m);
6658 }
6659
6660 /*
6661 * This function attempts to detect if multiple interfaces are on the same subnet.
6662 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6663 * IPv6 link local addresses that are configured by default on all interfaces make
6664 * it hard to make this determination
6665 *
6666 * The 'real' fix for this would be to send out multicast packets over one interface
6667 * and conclude that multiple interfaces are on the same subnet only if these packets
6668 * are seen on other interfaces on the same system
6669 */
skipSameSubnetRegistration(mDNS * const m,mDNSInterfaceID * regID,mDNSu32 count,mDNSInterfaceID intfid)6670 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6671 {
6672 NetworkInterfaceInfo *intf;
6673 NetworkInterfaceInfo *newIntf;
6674 mDNSu32 i;
6675
6676 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6677 {
6678 if ((newIntf->InterfaceID != intfid) ||
6679 (newIntf->ip.type != mDNSAddrType_IPv4))
6680 {
6681 continue;
6682 }
6683 for ( i = 0; i < count; i++)
6684 {
6685 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6686 {
6687 if ((intf->InterfaceID != regID[i]) ||
6688 (intf->ip.type != mDNSAddrType_IPv4))
6689 {
6690 continue;
6691 }
6692 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6693 {
6694 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6695 return (mDNStrue);
6696 }
6697 }
6698 }
6699 }
6700 return (mDNSfalse);
6701 }
6702
DoKeepaliveCallbacks(mDNS * m)6703 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6704 {
6705 // Loop through the keepalive records and callback with an error
6706 m->CurrentRecord = m->ResourceRecords;
6707 while (m->CurrentRecord)
6708 {
6709 AuthRecord *const rr = m->CurrentRecord;
6710 if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6711 {
6712 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6713 if (rr->RecordCallback)
6714 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6715 }
6716 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6717 m->CurrentRecord = rr->next;
6718 }
6719 }
6720
6721 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
BeginSleepProcessing(mDNS * const m)6722 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6723 {
6724 mDNSBool SendGoodbyes = mDNStrue;
6725 mDNSBool WakeOnlyService = mDNSfalse;
6726 mDNSBool invokeKACallback = mDNStrue;
6727 const CacheRecord *sps[3] = { mDNSNULL };
6728 mDNSOpaque64 updateIntID = zeroOpaque64;
6729 mDNSInterfaceID registeredIntfIDS[128] = { 0 };
6730 mDNSu32 registeredCount = 0;
6731 int skippedRegistrations = 0;
6732
6733 m->NextScheduledSPRetry = m->timenow;
6734
6735 // Clear out the SCDynamic entry that stores the external SPS information
6736 mDNSPlatformClearSPSData();
6737
6738 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6739 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6740 else // If we have at least one advertised service
6741 {
6742 NetworkInterfaceInfo *intf;
6743 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6744 {
6745 mDNSBool skipFullSleepProxyRegistration = mDNSfalse;
6746 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6747 intf->SendGoodbyes = 0;
6748
6749 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6750 // servers.
6751 if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6752 {
6753 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6754 continue;
6755 }
6756
6757 // If we are not capable of WOMP, then don't register with sleep proxy.
6758 //
6759 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6760 // We might find sleep proxy servers in the cache and start a resolve on them.
6761 // But then if the interface goes away, we won't stop these questions because
6762 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6763 // to stop both the browse and resolve questions.
6764 if (!intf->NetWake)
6765 {
6766 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6767 intf->SendGoodbyes = 1;
6768 skippedRegistrations++;
6769 continue;
6770 }
6771
6772 // Check if we have already registered with a sleep proxy for this subnet.
6773 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6774 // to the interface.
6775 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6776 {
6777 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname);
6778 skipFullSleepProxyRegistration = mDNStrue;
6779 }
6780
6781 #if APPLE_OSX_mDNSResponder
6782 if (SupportsInNICProxy(intf))
6783 {
6784 mDNSBool keepaliveOnly = mDNSfalse;
6785 const mStatus err = ActivateLocalProxy(intf, skipFullSleepProxyRegistration, &keepaliveOnly);
6786 if (!skipFullSleepProxyRegistration && !err)
6787 {
6788 SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6789
6790 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6791 SendGoodbyes = (keepaliveOnly) ? mDNStrue: mDNSfalse;
6792 invokeKACallback = mDNSfalse;
6793 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6794 // This will leave m->SleepState set to SleepState_Transferring,
6795 // which is okay because with no outstanding resolves, or updates in flight,
6796 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6797
6798 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6799 registeredCount++;
6800 }
6801 continue;
6802 }
6803 #endif // APPLE_OSX_mDNSResponder
6804 if (!skipFullSleepProxyRegistration)
6805 {
6806 #if APPLE_OSX_mDNSResponder
6807 // If on battery, do not attempt to offload to external sleep proxies
6808 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6809 {
6810 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6811 return;
6812 }
6813 #endif // APPLE_OSX_mDNSResponder
6814 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6815 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6816 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6817 else
6818 {
6819 int i;
6820 mDNSu32 scopeid;
6821 SendGoodbyes = mDNSfalse;
6822 intf->NextSPSAttempt = 0;
6823 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6824
6825 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6826 // Now we know for sure that we have to wait for registration to complete on this interface.
6827 if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6828 bit_set_opaque64(updateIntID, scopeid);
6829
6830 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6831 for (i=0; i<3; i++)
6832 {
6833 #if ForceAlerts
6834 if (intf->SPSAddr[i].type)
6835 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6836 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6837 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6838 #endif
6839 intf->SPSAddr[i].type = mDNSAddrType_None;
6840 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6841 intf->NetWakeResolve[i].ThisQInterval = -1;
6842 if (sps[i])
6843 {
6844 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6845 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6846 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6847 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6848
6849 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6850 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6851 registeredCount++;
6852 }
6853 }
6854 }
6855 }
6856 }
6857 }
6858
6859 // If we have at least one interface on which we are registering with an external sleep proxy,
6860 // initialize all the records appropriately.
6861 if (!mDNSOpaque64IsZero(&updateIntID))
6862 SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6863
6864 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6865 // the records to a sleep proxy.
6866 if (invokeKACallback)
6867 {
6868 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6869 DoKeepaliveCallbacks(m);
6870 }
6871
6872 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6873 // interfaces and also deregister unicast registrations.
6874 //
6875 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6876 // for both multicast and unicast.
6877 //
6878 // - If we skipped registrations on some interfaces, then we have already marked
6879 // them appropriately above. We don't need to send goodbyes for unicast as
6880 // we have registered with at least one sleep proxy.
6881 //
6882 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6883 //
6884 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6885 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6886 // at WakeOnlyServices first.
6887 if (SendGoodbyes)
6888 {
6889 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6890 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6891 }
6892 else if (skippedRegistrations)
6893 {
6894 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6895 SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6896 }
6897 else if (WakeOnlyService)
6898 {
6899 // If we saw WakeOnly service above, send the goodbyes now.
6900 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6901 SendResponses(m);
6902 }
6903 }
6904
6905 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6906 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6907 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
mDNSCoreMachineSleep(mDNS * const m,mDNSBool sleep)6908 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6909 {
6910 AuthRecord *rr;
6911
6912 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_INFO,
6913 PUB_S " (old state %d) at %d", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6914
6915 if (sleep && !m->SleepState) // Going to sleep
6916 {
6917 mDNS_Lock(m);
6918 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6919 if (m->SPSSocket)
6920 {
6921 mDNSu8 oldstate = m->SPSState;
6922 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6923 m->SPSState = 2;
6924 #ifndef SPC_DISABLED
6925 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6926 #else
6927 (void)oldstate;
6928 #endif
6929 mDNS_ReclaimLockAfterCallback();
6930 }
6931 #ifdef _LEGACY_NAT_TRAVERSAL_
6932 if (m->SSDPSocket)
6933 {
6934 mDNSPlatformUDPClose(m->SSDPSocket);
6935 m->SSDPSocket = mDNSNULL;
6936 }
6937 #endif
6938 m->SleepState = SleepState_Transferring;
6939 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6940 {
6941 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6942 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
6943 "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6944 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6945 }
6946 else
6947 {
6948 m->DelaySleep = 0;
6949 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6950 m->mDNSStats.Sleeps++;
6951 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
6952 Querier_HandleSleep();
6953 #endif
6954 BeginSleepProcessing(m);
6955 }
6956
6957 #ifndef UNICAST_DISABLED
6958 SuspendLLQs(m);
6959 #endif
6960 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S ") seq %d",
6961 m->SleepState,
6962 m->SleepState == SleepState_Transferring ? "Transferring" :
6963 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
6964 mDNS_Unlock(m);
6965 }
6966 else if (!sleep) // Waking up
6967 {
6968 mDNSu32 slot;
6969 CacheGroup *cg;
6970 CacheRecord *cr;
6971 NetworkInterfaceInfo *intf;
6972 mDNSs32 currtime, diff;
6973
6974 mDNS_Lock(m);
6975 // Reset SleepLimit back to 0 now that we're awake again.
6976 m->SleepLimit = 0;
6977
6978 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6979 if (m->SleepState != SleepState_Awake)
6980 {
6981 m->SleepState = SleepState_Awake;
6982 m->SleepSeqNum++;
6983 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6984 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6985 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6986 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6987 m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep);
6988 }
6989
6990 if (m->SPSState == 3)
6991 {
6992 m->SPSState = 0;
6993 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
6994 }
6995 m->mDNSStats.Wakes++;
6996 // ... and the same for NextSPSAttempt
6997 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
6998
6999 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7000 Querier_HandleWake();
7001 #endif
7002 // Restart unicast and multicast queries
7003 mDNSCoreRestartQueries(m);
7004
7005 // and reactivtate service registrations
7006 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7007 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7008 "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
7009
7010 // 2. Re-validate our cache records
7011 currtime = mDNSPlatformUTC();
7012
7013 diff = currtime - m->TimeSlept;
7014 FORALL_CACHERECORDS(slot, cg, cr)
7015 {
7016 // Temporary fix: For unicast cache records, look at how much time we slept.
7017 // Adjust the RecvTime by the amount of time we slept so that we age the
7018 // cache record appropriately. If it is expired already, purge. If there
7019 // is a network change that happens after the wakeup, we might purge the
7020 // cache anyways and this helps only in the case where there are no network
7021 // changes across sleep/wakeup transition.
7022 //
7023 // Note: If there is a network/DNS server change that already happened and
7024 // these cache entries are already refreshed and we are getting a delayed
7025 // wake up notification, we might adjust the TimeRcvd based on the time slept
7026 // now which can cause the cache to purge pre-maturely. As this is not a very
7027 // common case, this should happen rarely.
7028 if (!cr->resrec.InterfaceID)
7029 {
7030 if (diff > 0)
7031 {
7032 mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
7033 const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
7034
7035 // -if we have slept longer than the remaining TTL, purge and start fresh.
7036 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
7037 // a sufficiently big value which could cause the value to go into the future
7038 // because of the signed comparison of time. For this to happen, we should have been
7039 // sleeping really long (~24 days). For now, we want to be conservative and flush even
7040 // if we have slept for more than two days.
7041
7042 if (diff >= remain || diff > (2 * 24 * 3600))
7043 {
7044 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7045 "mDNSCoreMachineSleep: " PRI_S ": Purging cache entry SleptTime %d, Remaining TTL %d",
7046 CRDisplayString(m, cr), diff, remain);
7047 mDNS_PurgeCacheResourceRecord(m, cr);
7048 continue;
7049 }
7050 cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
7051 if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
7052 {
7053 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7054 "mDNSCoreMachineSleep: " PRI_S ": Purging after adjusting the remaining TTL %d by %d seconds",
7055 CRDisplayString(m, cr), remain, diff);
7056 mDNS_PurgeCacheResourceRecord(m, cr);
7057 }
7058 else
7059 {
7060 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7061 "mDNSCoreMachineSleep: " PRI_S ": Adjusted the remain ttl %u by %d seconds",
7062 CRDisplayString(m, cr), remain, diff);
7063 }
7064 }
7065 }
7066 else
7067 {
7068 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
7069 }
7070 }
7071
7072 // 3. Retrigger probing and announcing for all our authoritative records
7073 for (rr = m->ResourceRecords; rr; rr=rr->next)
7074 {
7075 if (AuthRecord_uDNS(rr))
7076 {
7077 ActivateUnicastRegistration(m, rr);
7078 }
7079 else
7080 {
7081 mDNSCoreRestartRegistration(m, rr, -1);
7082 }
7083 }
7084
7085 // 4. Refresh NAT mappings
7086 // We don't want to have to assume that all hardware can necessarily keep accurate
7087 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7088 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7089 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7090 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7091 // than five seconds from now.
7092 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7093 RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
7094 mDNS_Unlock(m);
7095 }
7096 }
7097
mDNSCoreReadyForSleep(mDNS * m,mDNSs32 now)7098 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
7099 {
7100 DNSQuestion *q;
7101 AuthRecord *rr;
7102 NetworkInterfaceInfo *intf;
7103
7104 mDNS_Lock(m);
7105
7106 if (m->DelaySleep) goto notready;
7107
7108 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7109 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
7110
7111 m->NextScheduledSPRetry = now + 0x40000000UL;
7112
7113 // See if we might need to retransmit any lost Sleep Proxy Registrations
7114 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7115 if (intf->NextSPSAttempt >= 0)
7116 {
7117 if (now - intf->NextSPSAttemptTime >= 0)
7118 {
7119 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7120 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
7121 SendSPSRegistration(m, intf, zeroID);
7122 // Don't need to "goto notready" here, because if we do still have record registrations
7123 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7124 }
7125 else
7126 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
7127 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
7128 }
7129
7130 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7131 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7132 {
7133 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
7134 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
7135 {
7136 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7137 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
7138 goto spsnotready;
7139 }
7140 }
7141
7142 // Scan list of registered records
7143 for (rr = m->ResourceRecords; rr; rr = rr->next)
7144 if (!AuthRecord_uDNS(rr))
7145 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7146 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS updateIntID 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; }
7147
7148 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7149 for (q = m->Questions; q; q = q->next)
7150 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
7151 {
7152 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7153 goto notready;
7154 }
7155
7156 // Scan list of registered records
7157 for (rr = m->ResourceRecords; rr; rr = rr->next)
7158 if (AuthRecord_uDNS(rr))
7159 {
7160 if (rr->state == regState_Refresh && rr->tcp)
7161 { 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; }
7162 }
7163
7164 mDNS_Unlock(m);
7165 return mDNStrue;
7166
7167 spsnotready:
7168
7169 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7170 // and allow up to ten seconds more to complete wide-area deregistration instead
7171 if (now - m->SleepLimit >= 0)
7172 {
7173 LogMsg("Failed to register with SPS, now sending goodbyes");
7174
7175 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7176 if (intf->NetWakeBrowse.ThisQInterval >= 0)
7177 {
7178 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7179 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
7180 mDNS_DeactivateNetWake_internal(m, intf);
7181 }
7182
7183 for (rr = m->ResourceRecords; rr; rr = rr->next)
7184 if (!AuthRecord_uDNS(rr))
7185 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7186 {
7187 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));
7188 rr->updateIntID = zeroOpaque64;
7189 }
7190
7191 // We'd really like to allow up to ten seconds more here,
7192 // but if we don't respond to the sleep notification within 30 seconds
7193 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7194 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7195 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7196 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7197 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
7198
7199 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
7200 }
7201
7202 notready:
7203 mDNS_Unlock(m);
7204 return mDNSfalse;
7205 }
7206
mDNSCoreIntervalToNextWake(mDNS * const m,mDNSs32 now,mDNSNextWakeReason * outReason)7207 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now, mDNSNextWakeReason *outReason)
7208 {
7209 AuthRecord *ar;
7210
7211 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7212 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7213 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7214 // and if that happens we don't want to just give up and go back to sleep and never try again.
7215 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
7216 mDNSNextWakeReason reason = mDNSNextWakeReason_UpkeepWake;
7217
7218 NATTraversalInfo *nat;
7219 for (nat = m->NATTraversals; nat; nat=nat->next)
7220 {
7221 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
7222 {
7223 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
7224 if ((e - t) > 0)
7225 {
7226 e = t;
7227 reason = mDNSNextWakeReason_NATPortMappingRenewal;
7228 }
7229 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7230 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
7231 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
7232 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
7233 nat->retryInterval / mDNSPlatformOneSecond,
7234 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
7235 (t - now) / mDNSPlatformOneSecond);
7236 }
7237 }
7238 // This loop checks both the time we need to renew wide-area registrations,
7239 // and the time we need to renew Sleep Proxy registrations
7240 for (ar = m->ResourceRecords; ar; ar = ar->next)
7241 {
7242 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
7243 {
7244 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
7245 if ((e - t) > 0)
7246 {
7247 e = t;
7248 reason = mDNSNextWakeReason_RecordRegistrationRenewal;
7249 }
7250 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7251 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
7252 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
7253 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
7254 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
7255 }
7256 }
7257 if (outReason)
7258 {
7259 *outReason = reason;
7260 }
7261 return(e - now);
7262 }
7263
7264 // ***************************************************************************
7265 #if COMPILER_LIKES_PRAGMA_MARK
7266 #pragma mark -
7267 #pragma mark - Packet Reception Functions
7268 #endif
7269
7270 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7271
GenerateUnicastResponse(const DNSMessage * const query,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID,mDNSBool LegacyQuery,DNSMessage * const response,AuthRecord * ResponseRecords)7272 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
7273 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
7274 {
7275 mDNSu8 *responseptr = response->data;
7276 const mDNSu8 *const limit = response->data + sizeof(response->data);
7277 const mDNSu8 *ptr = query->data;
7278 AuthRecord *rr;
7279 mDNSu32 maxttl = (!InterfaceID) ? mDNSMaximumUnicastTTLSeconds : mDNSMaximumMulticastTTLSeconds;
7280 int i;
7281
7282 // Initialize the response fields so we can answer the questions
7283 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
7284
7285 // ***
7286 // *** 1. Write out the list of questions we are actually going to answer with this packet
7287 // ***
7288 if (LegacyQuery)
7289 {
7290 maxttl = kStaticCacheTTL;
7291 for (i=0; i<query->h.numQuestions; i++) // For each question...
7292 {
7293 DNSQuestion q;
7294 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
7295 if (!ptr) return(mDNSNULL);
7296
7297 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
7298 {
7299 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
7300 { // then put the question in the question section
7301 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
7302 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
7303 break; // break out of the ResponseRecords loop, and go on to the next question
7304 }
7305 }
7306 }
7307
7308 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
7309 }
7310
7311 // ***
7312 // *** 2. Write Answers
7313 // ***
7314 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7315 if (rr->NR_AnswerTo)
7316 {
7317 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
7318 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7319 if (p) responseptr = p;
7320 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
7321 }
7322
7323 // ***
7324 // *** 3. Write Additionals
7325 // ***
7326 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7327 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
7328 {
7329 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
7330 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7331 if (p) responseptr = p;
7332 else debugf("GenerateUnicastResponse: No more space for additionals");
7333 }
7334
7335 return(responseptr);
7336 }
7337
7338 // AuthRecord *our is our Resource Record
7339 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7340 // Returns 0 if there is no conflict
7341 // Returns +1 if there was a conflict and we won
7342 // Returns -1 if there was a conflict and we lost and have to rename
CompareRData(const AuthRecord * const our,const CacheRecord * const pkt)7343 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
7344 {
7345 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
7346 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
7347 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7348 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7349
7350 #if defined(__clang_analyzer__)
7351 // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7352 // There are no clear indications from the analyzer of the cause of the supposed problem.
7353 mDNSPlatformMemZero(ourdata, 1);
7354 mDNSPlatformMemZero(pktdata, 1);
7355 #endif
7356 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
7357 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
7358 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
7359 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
7360
7361 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
7362 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
7363 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
7364 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
7365
7366 LogMsg("CompareRData ERROR: Invalid state");
7367 return(-1);
7368 }
7369
PacketRecordMatches(const AuthRecord * const rr,const CacheRecord * const pktrr,const AuthRecord * const master)7370 mDNSlocal mDNSBool PacketRecordMatches(const AuthRecord *const rr, const CacheRecord *const pktrr, const AuthRecord *const master)
7371 {
7372 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7373 {
7374 const AuthRecord *r2 = rr;
7375 while (r2->DependentOn) r2 = r2->DependentOn;
7376 if (r2 == master) return(mDNStrue);
7377 }
7378 return(mDNSfalse);
7379 }
7380
7381 // See if we have an authoritative record that's identical to this packet record,
7382 // whose canonical DependentOn record is the specified master record.
7383 // The DependentOn pointer is typically used for the TXT record of service registrations
7384 // It indicates that there is no inherent conflict detection for the TXT record
7385 // -- it depends on the SRV record to resolve name conflicts
7386 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7387 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7388 // If the record has no DependentOn, then just return that record's pointer
7389 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
MatchDependentOn(const mDNS * const m,const CacheRecord * const pktrr,const AuthRecord * const master)7390 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
7391 {
7392 const AuthRecord *r1;
7393 for (r1 = m->ResourceRecords; r1; r1=r1->next)
7394 {
7395 if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7396 }
7397 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
7398 {
7399 if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7400 }
7401 return(mDNSfalse);
7402 }
7403
7404 // Find the canonical RRSet pointer for this RR received in a packet.
7405 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7406 // pointers (if any) to make sure we return the canonical member of this name/type/class
7407 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
FindRRSet(const mDNS * const m,const CacheRecord * const pktrr)7408 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
7409 {
7410 const AuthRecord *rr;
7411 for (rr = m->ResourceRecords; rr; rr=rr->next)
7412 {
7413 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7414 {
7415 return(rr->RRSet ? rr->RRSet : rr);
7416 }
7417 }
7418 return(mDNSNULL);
7419 }
7420
7421 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7422 // as one of our records (our) but different rdata.
7423 // 1. If our record is not a type that's supposed to be unique, we don't care.
7424 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7425 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7426 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7427 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7428 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7429 // are members of the same RRSet, then this is not a conflict.
PacketRRConflict(const mDNS * const m,const AuthRecord * const our,const CacheRecord * const pktrr)7430 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7431 {
7432 // If not supposed to be unique, not a conflict
7433 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7434
7435 // If a dependent record, not a conflict
7436 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7437 else
7438 {
7439 // If the pktrr matches a member of ourset, not a conflict
7440 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7441 const AuthRecord *pktset = FindRRSet(m, pktrr);
7442 if (pktset == ourset) return(mDNSfalse);
7443
7444 // For records we're proxying, where we don't know the full
7445 // relationship between the records, having any matching record
7446 // in our AuthRecords list is sufficient evidence of non-conflict
7447 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7448 }
7449
7450 // Okay, this is a conflict
7451 return(mDNStrue);
7452 }
7453
7454 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7455 // the record list and/or question list.
7456 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
ResolveSimultaneousProbe(mDNS * const m,const DNSMessage * const query,const mDNSu8 * const end,DNSQuestion * q,AuthRecord * our)7457 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7458 DNSQuestion *q, AuthRecord *our)
7459 {
7460 int i;
7461 const mDNSu8 *ptr = LocateAuthorities(query, end);
7462 mDNSBool FoundUpdate = mDNSfalse;
7463
7464 for (i = 0; i < query->h.numAuthorities; i++)
7465 {
7466 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7467 if (!ptr) break;
7468 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && CacheRecordAnswersQuestion(&m->rec.r, q))
7469 {
7470 FoundUpdate = mDNStrue;
7471 if (PacketRRConflict(m, our, &m->rec.r))
7472 {
7473 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7474 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
7475 if (!result) result = CompareRData(our, &m->rec.r);
7476 if (result)
7477 {
7478 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7479 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7480 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7481 }
7482 // 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.
7483 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7484 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7485 if (result < 0)
7486 {
7487 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7488 our->ProbeCount = DefaultProbeCountForTypeUnique;
7489 our->AnnounceCount = InitialAnnounceCount;
7490 InitializeLastAPTime(m, our);
7491 goto exit;
7492 }
7493 }
7494 #if 0
7495 else
7496 {
7497 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7498 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7499 }
7500 #endif
7501 }
7502 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7503 }
7504 if (!FoundUpdate)
7505 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7506 exit:
7507 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7508 }
7509
FindIdenticalRecordInCache(const mDNS * const m,const ResourceRecord * const pktrr)7510 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7511 {
7512 CacheGroup *cg = CacheGroupForRecord(m, pktrr);
7513 CacheRecord *rr;
7514 mDNSBool match;
7515 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7516 {
7517 if (!pktrr->InterfaceID)
7518 {
7519 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7520 match = (pktrr->dnsservice == rr->resrec.dnsservice) ? mDNStrue : mDNSfalse;
7521 #else
7522 const mDNSu32 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7523 const mDNSu32 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7524 match = (id1 == id2);
7525 #endif
7526 }
7527 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7528
7529 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7530 }
7531 return(rr);
7532 }
DeregisterProxyRecord(mDNS * const m,AuthRecord * const rr)7533 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7534 {
7535 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7536 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
7537 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7538 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7539 }
7540
ClearKeepaliveProxyRecords(mDNS * const m,const OwnerOptData * const owner,AuthRecord * const thelist,const mDNSInterfaceID InterfaceID)7541 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7542 {
7543 if (m->CurrentRecord)
7544 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7545 m->CurrentRecord = thelist;
7546
7547 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7548 // clean up the keepalive record.
7549 while (m->CurrentRecord)
7550 {
7551 AuthRecord *const rr = m->CurrentRecord;
7552 if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7553 {
7554 if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7555 {
7556 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7557 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7558 DeregisterProxyRecord(m, rr);
7559 }
7560 }
7561 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7562 // new records could have been added to the end of the list as a result of that call.
7563 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7564 m->CurrentRecord = rr->next;
7565 }
7566 }
7567
7568 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7569 // to check our lists and discard any stale duplicates of this record we already have
ClearIdenticalProxyRecords(mDNS * const m,const OwnerOptData * const owner,AuthRecord * const thelist)7570 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7571 {
7572 if (m->CurrentRecord)
7573 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7574 m->CurrentRecord = thelist;
7575 while (m->CurrentRecord)
7576 {
7577 AuthRecord *const rr = m->CurrentRecord;
7578 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7579 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7580 {
7581 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7582 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7583 DeregisterProxyRecord(m, rr);
7584 }
7585 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7586 // new records could have been added to the end of the list as a result of that call.
7587 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7588 m->CurrentRecord = rr->next;
7589 }
7590 }
7591
7592 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
ClearProxyRecords(mDNS * const m,const OwnerOptData * const owner,AuthRecord * const thelist)7593 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7594 {
7595 if (m->CurrentRecord)
7596 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7597 m->CurrentRecord = thelist;
7598 while (m->CurrentRecord)
7599 {
7600 AuthRecord *const rr = m->CurrentRecord;
7601 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7602 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7603 {
7604 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7605 {
7606 // We don't do this here because we know that the host is waking up at this point, so we don't send
7607 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7608 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7609 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7610 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7611 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7612 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7613 #endif
7614 }
7615 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7616 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7617 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7618 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7619 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7620 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7621 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7622 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7623 }
7624 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7625 // new records could have been added to the end of the list as a result of that call.
7626 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7627 m->CurrentRecord = rr->next;
7628 }
7629 }
7630
7631 // ProcessQuery examines a received query to see if we have any answers to give
ProcessQuery(mDNS * const m,const DNSMessage * const query,const mDNSu8 * const end,const mDNSAddr * srcaddr,const mDNSInterfaceID InterfaceID,mDNSBool LegacyQuery,mDNSBool QueryWasMulticast,mDNSBool QueryWasLocalUnicast,DNSMessage * const response)7632 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7633 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7634 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7635 {
7636 const mDNSBool FromLocalSubnet = mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7637 AuthRecord *ResponseRecords = mDNSNULL;
7638 AuthRecord **nrp = &ResponseRecords;
7639
7640 #if POOF_ENABLED
7641 mDNSBool notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID); // We don't run the POOF algorithm on D2D interfaces.
7642 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
7643 CacheRecord **eap = &ExpectedAnswers;
7644 #endif // POOF_ENABLED
7645
7646 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
7647 DNSQuestion **dqp = &DupQuestions;
7648 mDNSs32 delayresponse = 0;
7649 mDNSBool SendLegacyResponse = mDNSfalse;
7650 const mDNSu8 *ptr;
7651 mDNSu8 *responseptr = mDNSNULL;
7652 AuthRecord *rr;
7653 int i;
7654
7655 // ***
7656 // *** 1. Look in Additional Section for an OPT record
7657 // ***
7658 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7659 if (ptr)
7660 {
7661 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7662 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7663 {
7664 const rdataOPT *opt;
7665 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7666 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7667 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7668 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7669 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7670 {
7671 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7672 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7673 }
7674 }
7675 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7676 }
7677
7678 // ***
7679 // *** 2. Parse Question Section and mark potential answers
7680 // ***
7681 ptr = query->data;
7682 for (i=0; i<query->h.numQuestions; i++) // For each question...
7683 {
7684 mDNSBool QuestionNeedsMulticastResponse;
7685 int NumAnswersForThisQuestion = 0;
7686 AuthRecord *NSECAnswer = mDNSNULL;
7687 DNSQuestion pktq, *q;
7688 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7689 if (!ptr) goto exit;
7690
7691 // The only queries that *need* a multicast response are:
7692 // * Queries sent via multicast
7693 // * from port 5353
7694 // * that don't have the kDNSQClass_UnicastResponse bit set
7695 // These queries need multicast responses because other clients will:
7696 // * suppress their own identical questions when they see these questions, and
7697 // * expire their cache records if they don't see the expected responses
7698 // For other queries, we may still choose to send the occasional multicast response anyway,
7699 // to keep our neighbours caches warm, and for ongoing conflict detection.
7700 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7701
7702 if (pktq.qclass & kDNSQClass_UnicastResponse)
7703 m->mDNSStats.UnicastBitInQueries++;
7704 else
7705 m->mDNSStats.NormalQueries++;
7706
7707 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7708 pktq.qclass &= ~kDNSQClass_UnicastResponse;
7709
7710 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7711 // can result in user callbacks which may change the record list and/or question list.
7712 // Also note: we just mark potential answer records here, without trying to build the
7713 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7714 // from that list while we're in the middle of trying to build it.
7715 if (m->CurrentRecord)
7716 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7717 m->CurrentRecord = m->ResourceRecords;
7718 while (m->CurrentRecord)
7719 {
7720 rr = m->CurrentRecord;
7721 m->CurrentRecord = rr->next;
7722 if (AnyTypeRecordAnswersQuestion(rr, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7723 {
7724 m->mDNSStats.MatchingAnswersForQueries++;
7725 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7726 {
7727 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7728 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7729 else if (ResourceRecordIsValidAnswer(rr))
7730 {
7731 NumAnswersForThisQuestion++;
7732
7733 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7734 // unicast answer back to the source, because timeliness in answering probes is important.
7735
7736 // Notes:
7737 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7738 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7739 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7740 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7741 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7742 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7743 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7744 {
7745 // We only mark this question for sending if it is at least one second since the last time we multicast it
7746 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7747 // This is to guard against the case where someone blasts us with queries as fast as they can.
7748 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond ||
7749 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7750 rr->NR_AnswerTo = NR_AnswerMulticast;
7751 }
7752 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7753 }
7754 }
7755 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7756 {
7757 // If we don't have any answers for this question, but we do own another record with the same name,
7758 // then we'll want to mark it to generate an NSEC record on this interface
7759 if (!NSECAnswer) NSECAnswer = rr;
7760 }
7761 }
7762 }
7763
7764 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7765 {
7766 NumAnswersForThisQuestion++;
7767 NSECAnswer->SendNSECNow = InterfaceID;
7768 m->NextScheduledResponse = m->timenow;
7769 }
7770
7771 // If we couldn't answer this question, someone else might be able to,
7772 // so use random delay on response to reduce collisions
7773 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7774
7775 if (query->h.flags.b[0] & kDNSFlag0_TC)
7776 m->mDNSStats.KnownAnswerMultiplePkts++;
7777 // We only do the following accelerated cache expiration and duplicate question suppression processing
7778 // for non-truncated multicast queries with multicast responses.
7779 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7780 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7781 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7782 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7783 {
7784 #if POOF_ENABLED
7785 if (notD2D)
7786 {
7787 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname);
7788 CacheRecord *cr;
7789
7790 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7791 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7792 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7793 {
7794 if (SameNameCacheRecordAnswersQuestion(cr, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7795 {
7796 if (!cr->NextInKAList && eap != &cr->NextInKAList)
7797 {
7798 *eap = cr;
7799 eap = &cr->NextInKAList;
7800 }
7801 }
7802 }
7803 }
7804 #endif // POOF_ENABLED
7805
7806 // Check if this question is the same as any of mine.
7807 // We only do this for non-truncated queries. Right now it would be too complicated to try
7808 // to keep track of duplicate suppression state between multiple packets, especially when we
7809 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7810 for (q = m->Questions; q; q=q->next)
7811 {
7812 if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7813 {
7814 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7815 {
7816 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7817 {
7818 if (q->qtype == pktq.qtype &&
7819 q->qclass == pktq.qclass &&
7820 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7821 { *dqp = q; dqp = &q->NextInDQList; }
7822 }
7823 }
7824 }
7825 }
7826 }
7827 }
7828
7829 // ***
7830 // *** 3. Now we can safely build the list of marked answers
7831 // ***
7832 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
7833 if (rr->NR_AnswerTo) // If we marked the record...
7834 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
7835
7836 // ***
7837 // *** 4. Add additional records
7838 // ***
7839 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7840
7841 // ***
7842 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7843 // ***
7844 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
7845 {
7846 // Get the record...
7847 CacheRecord *ourcacherr;
7848 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7849 if (!ptr) goto exit;
7850 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7851 {
7852 // See if this Known-Answer suppresses any of our currently planned answers
7853 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7854 {
7855 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7856 {
7857 m->mDNSStats.KnownAnswerSuppressions++;
7858 rr->NR_AnswerTo = mDNSNULL;
7859 rr->NR_AdditionalTo = mDNSNULL;
7860 }
7861 }
7862
7863 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7864 for (rr=m->ResourceRecords; rr; rr=rr->next)
7865 {
7866 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7867 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7868 {
7869 if (srcaddr->type == mDNSAddrType_IPv4)
7870 {
7871 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7872 }
7873 else if (srcaddr->type == mDNSAddrType_IPv6)
7874 {
7875 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7876 }
7877 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7878 {
7879 m->mDNSStats.KnownAnswerSuppressions++;
7880 rr->ImmedAnswer = mDNSNULL;
7881 rr->ImmedUnicast = mDNSfalse;
7882 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7883 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7884 #endif
7885 }
7886 }
7887 }
7888
7889 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7890
7891 #if POOF_ENABLED
7892 if (notD2D)
7893 {
7894 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7895 // any records that are suppressed by the Known Answer list in this packet.
7896 eap = &ExpectedAnswers;
7897 while (*eap)
7898 {
7899 CacheRecord *cr = *eap;
7900 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7901 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7902 else eap = &cr->NextInKAList;
7903 }
7904 }
7905 #endif // POOF_ENABLED
7906
7907 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7908 if (!ourcacherr)
7909 {
7910 dqp = &DupQuestions;
7911 while (*dqp)
7912 {
7913 DNSQuestion *q = *dqp;
7914 if (CacheRecordAnswersQuestion(&m->rec.r, q))
7915 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7916 else dqp = &q->NextInDQList;
7917 }
7918 }
7919 }
7920 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7921 }
7922
7923 // ***
7924 // *** 6. Cancel any additionals that were added because of now-deleted records
7925 // ***
7926 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7927 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7928 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7929
7930 // ***
7931 // *** 7. Mark the send flags on the records we plan to send
7932 // ***
7933 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7934 {
7935 if (rr->NR_AnswerTo)
7936 {
7937 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
7938 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
7939
7940 // If it's been one TTL/4 since we multicast this, then send a multicast response
7941 // for conflict detection, etc.
7942 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4)
7943 {
7944 SendMulticastResponse = mDNStrue;
7945 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7946 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7947 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7948 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7949 {
7950 m->mDNSStats.UnicastDemotedToMulticast++;
7951 rr->NR_AnswerTo = NR_AnswerMulticast;
7952 }
7953 }
7954
7955 // If the client insists on a multicast response, then we'd better send one
7956 if (rr->NR_AnswerTo == NR_AnswerMulticast)
7957 {
7958 m->mDNSStats.MulticastResponses++;
7959 SendMulticastResponse = mDNStrue;
7960 }
7961 else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7962 {
7963 m->mDNSStats.UnicastResponses++;
7964 SendUnicastResponse = mDNStrue;
7965 }
7966 else if (rr->NR_AnswerTo)
7967 {
7968 SendLegacyResponse = mDNStrue;
7969 }
7970
7971 if (SendMulticastResponse || SendUnicastResponse)
7972 {
7973 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7974 rr->ImmedAnswerMarkTime = m->timenow;
7975 #endif
7976 m->NextScheduledResponse = m->timenow;
7977 // If we're already planning to send this on another interface, just send it on all interfaces
7978 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7979 rr->ImmedAnswer = mDNSInterfaceMark;
7980 else
7981 {
7982 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
7983 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7984 if (srcaddr->type == mDNSAddrType_IPv4)
7985 {
7986 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7987 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
7988 }
7989 else if (srcaddr->type == mDNSAddrType_IPv6)
7990 {
7991 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
7992 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
7993 }
7994 }
7995 }
7996 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7997 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7998 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7999 // else, for a simple unique record reply, we can reply immediately; no need for delay
8000 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
8001 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
8002 }
8003 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
8004 {
8005 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
8006 // If two clients on different interfaces do queries that invoke the same optional additional answer,
8007 // then the earlier client is out of luck
8008 rr->ImmedAdditional = InterfaceID;
8009 // No need to set m->NextScheduledResponse here
8010 // We'll send these additional records when we send them, or not, as the case may be
8011 }
8012 }
8013
8014 // ***
8015 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
8016 // ***
8017 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
8018 {
8019 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8020 mDNSs32 oldss = m->SuppressSending;
8021 if (oldss && delayresponse)
8022 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
8023 #endif
8024 // Pick a random delay:
8025 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
8026 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
8027 // This is an integer value, with resolution determined by the platform clock rate.
8028 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
8029 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
8030 // The +49 before dividing is to ensure we round up, not down, to ensure that even
8031 // on platforms where the native clock rate is less than fifty ticks per second,
8032 // we still guarantee that the final calculated delay is at least one platform tick.
8033 // We want to make sure we don't ever allow the delay to be zero ticks,
8034 // because if that happens we'll fail the Bonjour Conformance Test.
8035 // Our final computed delay is 20-120ms for normal delayed replies,
8036 // or 400-500ms in the case of multi-packet known-answer lists.
8037 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
8038 if (m->SuppressSending == 0) m->SuppressSending = 1;
8039 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8040 if (oldss && delayresponse)
8041 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
8042 #endif
8043 }
8044
8045 // ***
8046 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
8047 // ***
8048 if (SendLegacyResponse)
8049 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
8050
8051 exit:
8052 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8053
8054 // ***
8055 // *** 10. Finally, clear our link chains ready for use next time
8056 // ***
8057 while (ResponseRecords)
8058 {
8059 rr = ResponseRecords;
8060 ResponseRecords = rr->NextResponse;
8061 rr->NextResponse = mDNSNULL;
8062 rr->NR_AnswerTo = mDNSNULL;
8063 rr->NR_AdditionalTo = mDNSNULL;
8064 }
8065
8066 #if POOF_ENABLED
8067 while (ExpectedAnswers && notD2D)
8068 {
8069 CacheRecord *cr = ExpectedAnswers;
8070 ExpectedAnswers = cr->NextInKAList;
8071 cr->NextInKAList = mDNSNULL;
8072
8073 // For non-truncated queries, we can definitively say that we should expect
8074 // to be seeing a response for any records still left in the ExpectedAnswers list
8075 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
8076 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4)
8077 {
8078 cr->UnansweredQueries++;
8079 cr->LastUnansweredTime = m->timenow;
8080 if (cr->UnansweredQueries > 1)
8081 debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr));
8082 SetNextCacheCheckTimeForRecord(m, cr);
8083 }
8084
8085 // If we've seen multiple unanswered queries for this record,
8086 // then mark it to expire in five seconds if we don't get a response by then.
8087 if (cr->UnansweredQueries >= MaxUnansweredQueries)
8088 {
8089 // Only show debugging message if this record was not about to expire anyway
8090 if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond)
8091 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8092 cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr));
8093
8094 m->mDNSStats.PoofCacheDeletions++;
8095 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8096 }
8097 }
8098 #endif // POOF_ENABLED
8099
8100 while (DupQuestions)
8101 {
8102 DNSQuestion *q = DupQuestions;
8103 DupQuestions = q->NextInDQList;
8104 q->NextInDQList = mDNSNULL;
8105 RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
8106 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
8107 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
8108 }
8109 return(responseptr);
8110 }
8111
mDNSCoreReceiveQuery(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * const end,const mDNSAddr * srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,mDNSIPPort dstport,const mDNSInterfaceID InterfaceID)8112 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
8113 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8114 const mDNSInterfaceID InterfaceID)
8115 {
8116 mDNSu8 *responseend = mDNSNULL;
8117 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
8118 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8119
8120 if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr)))
8121 {
8122 const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID";
8123 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8124 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8125 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8126 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8127 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8128 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8129 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data, reason);
8130 return;
8131 }
8132
8133 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8134 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8135 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8136 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8137 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8138 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8139 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
8140
8141 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
8142 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
8143
8144 if (responseend) // If responseend is non-null, that means we built a unicast response packet
8145 {
8146 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8147 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
8148 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
8149 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
8150 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
8151 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSfalse);
8152 }
8153 }
8154
8155 #if 0
8156 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
8157 {
8158 DNSServer *s;
8159 (void)m; // Unused
8160 (void)srcaddr; // Unused
8161 for (s = m->DNSServers; s; s = s->next)
8162 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
8163 return(mDNSfalse);
8164 }
8165 #endif
8166
8167 struct UDPSocket_struct
8168 {
8169 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8170 };
8171
ExpectingUnicastResponseForQuestion(const mDNS * const m,const mDNSIPPort port,const mDNSOpaque16 id,const DNSQuestion * const question,mDNSBool tcp)8172 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port,
8173 const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
8174 {
8175 DNSQuestion *q;
8176 for (q = m->Questions; q; q=q->next)
8177 {
8178 if (!tcp && !q->LocalSocket) continue;
8179 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
8180 q->qtype == question->qtype &&
8181 q->qclass == question->qclass &&
8182 q->qnamehash == question->qnamehash &&
8183 SameDomainName(&q->qname, &question->qname))
8184 {
8185 if (mDNSSameOpaque16(q->TargetQID, id)) return(q);
8186 else
8187 {
8188 return(mDNSNULL);
8189 }
8190 }
8191 }
8192 return(mDNSNULL);
8193 }
8194
8195 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8196 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
ExpectingUnicastResponseForRecord(mDNS * const m,const mDNSAddr * const srcaddr,const mDNSBool SrcLocal,const mDNSIPPort port,const mDNSOpaque16 id,const CacheRecord * const rr,mDNSBool tcp)8197 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
8198 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
8199 {
8200 DNSQuestion *q;
8201 (void)id;
8202
8203 for (q = m->Questions; q; q=q->next)
8204 {
8205 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
8206 {
8207 if (!mDNSOpaque16IsZero(q->TargetQID))
8208 {
8209 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
8210
8211 if (mDNSSameOpaque16(q->TargetQID, id))
8212 {
8213 mDNSIPPort srcp;
8214 if (!tcp)
8215 {
8216 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
8217 }
8218 else
8219 {
8220 srcp = q->tcpSrcPort;
8221 }
8222 if (mDNSSameIPPort(srcp, port)) return(q);
8223
8224 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8225 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8226 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8227 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8228 q->qname.c, DNSTypeName(q->qtype), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
8229 return(mDNSNULL);
8230 }
8231 }
8232 else
8233 {
8234 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
8235 return(q);
8236 }
8237 }
8238 }
8239 return(mDNSNULL);
8240 }
8241
8242 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8243 // Currently this applies only to rdata types containing more than one domainname,
8244 // or types where the domainname is not the last item in the structure.
GetRDLengthMem(const ResourceRecord * const rr)8245 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
8246 {
8247 switch (rr->rrtype)
8248 {
8249 case kDNSType_SOA: return sizeof(rdataSOA);
8250 case kDNSType_RP: return sizeof(rdataRP);
8251 case kDNSType_PX: return sizeof(rdataPX);
8252 default: return rr->rdlength;
8253 }
8254 }
8255
CreateNewCacheEntry(mDNS * const m,const mDNSu32 slot,CacheGroup * cg,mDNSs32 delay,mDNSBool Add,const mDNSAddr * sourceAddress)8256 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
8257 {
8258 CacheRecord *rr = mDNSNULL;
8259 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
8260
8261 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
8262
8263 //if (RDLength > InlineCacheRDSize)
8264 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8265
8266 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
8267 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
8268 if (!rr) NoCacheAnswer(m, &m->rec.r);
8269 else
8270 {
8271 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
8272 *rr = m->rec.r; // Block copy the CacheRecord object
8273 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8274 mdns_retain_null_safe(rr->resrec.dnsservice);
8275 #endif
8276 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
8277 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
8278 rr->resrec.mortality = Mortality_Mortal;
8279 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8280 rr->resrec.dnssec_result = dnssec_indeterminate; // Set the DNSSEC validation result of a record as "indeterminate" by default.
8281 #endif
8282
8283 rr->DelayDelivery = delay;
8284
8285 // If this is an oversized record with external storage allocated, copy rdata to external storage
8286 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
8287 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8288 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
8289 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8290 if (RDLength > InlineCacheRDSize)
8291 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
8292
8293 rr->next = mDNSNULL; // Clear 'next' pointer
8294 rr->soa = mDNSNULL;
8295
8296 if (sourceAddress)
8297 rr->sourceAddress = *sourceAddress;
8298
8299 if (!rr->resrec.InterfaceID)
8300 {
8301 m->rrcache_totalused_unicast += rr->resrec.rdlength;
8302 }
8303
8304 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8305 if (rr != mDNSNULL)
8306 {
8307 rr->denial_of_existence_records = mDNSNULL;
8308 }
8309 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8310
8311 if (Add)
8312 {
8313 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
8314 cg->rrcache_tail = &(rr->next); // Advance tail pointer
8315 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8316 }
8317 else
8318 {
8319 // Can't use the "cg->name" if we are not adding to the cache as the
8320 // CacheGroup may be released anytime if it is empty
8321 domainname *name = (domainname *) mDNSPlatformMemAllocate(DomainNameLength(cg->name));
8322 if (name)
8323 {
8324 AssignDomainName(name, cg->name);
8325 rr->resrec.name = name;
8326 }
8327 else
8328 {
8329 ReleaseCacheRecord(m, rr);
8330 NoCacheAnswer(m, &m->rec.r);
8331 rr = mDNSNULL;
8332 }
8333 }
8334 }
8335 return(rr);
8336 }
8337
RefreshCacheRecordCacheGroupOrder(CacheGroup * cg,CacheRecord * cr)8338 mDNSlocal void RefreshCacheRecordCacheGroupOrder(CacheGroup *cg, CacheRecord *cr)
8339 { // Move the cache record to the tail of the cache group to maintain a fresh ordering
8340 if (cg->rrcache_tail != &cr->next) // If not already at the tail
8341 {
8342 CacheRecord **rp;
8343 for (rp = &cg->members; *rp; rp = &(*rp)->next)
8344 {
8345 if (*rp == cr) // This item points to this record
8346 {
8347 *rp = cr->next; // Remove this record
8348 break;
8349 }
8350 }
8351 cr->next = mDNSNULL; // This record is now last
8352 *(cg->rrcache_tail) = cr; // Append this record to tail of cache group
8353 cg->rrcache_tail = &(cr->next); // Advance tail pointer
8354 }
8355 }
8356
RefreshCacheRecord(mDNS * const m,CacheRecord * rr,mDNSu32 ttl)8357 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8358 {
8359 rr->TimeRcvd = m->timenow;
8360 rr->resrec.rroriginalttl = ttl;
8361 rr->UnansweredQueries = 0;
8362 if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal;
8363 SetNextCacheCheckTimeForRecord(m, rr);
8364 }
8365
GrantCacheExtensions(mDNS * const m,DNSQuestion * q,mDNSu32 lease)8366 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8367 {
8368 CacheRecord *rr;
8369 CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname);
8370 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8371 if (rr->CRActiveQuestion == q)
8372 {
8373 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8374 RefreshCacheRecord(m, rr, lease);
8375 }
8376 }
8377
GetEffectiveTTL(const uDNS_LLQType LLQType,mDNSu32 ttl)8378 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
8379 {
8380 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8381 else if (LLQType == uDNS_LLQ_Events)
8382 {
8383 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8384 if (ttl == 0xFFFFFFFF) ttl = 0;
8385 else ttl = kLLQ_DefLease;
8386 }
8387 else // else not LLQ (standard uDNS response)
8388 {
8389 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8390 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8391 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8392
8393 ttl = RRAdjustTTL(ttl);
8394
8395 // For mDNS, TTL zero means "delete this record"
8396 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8397 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8398 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8399 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8400 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8401 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8402 // (with the current code) result in the server having even less than three seconds to respond
8403 // before we deleted the record and reported a "remove" event to any active questions.
8404 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8405 // then things really break (e.g. we end up making a negative cache entry).
8406 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8407 if (ttl < 15) ttl = 15;
8408 }
8409
8410 return ttl;
8411 }
8412
8413 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8414 // in m->rec.
IsResponseAcceptable(mDNS * const m,const CacheRecord * crlist)8415 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist)
8416 {
8417 CacheRecord *const newcr = &m->rec.r;
8418 ResourceRecord *rr = &newcr->resrec;
8419 const CacheRecord *cr;
8420
8421 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8422 {
8423 domainname *target = GetRRDomainNameTarget(&cr->resrec);
8424 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8425 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8426 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8427 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8428 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8429
8430 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8431 {
8432 LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8433 return (mDNStrue);
8434 }
8435 }
8436 return mDNSfalse;
8437 }
8438
mDNSCoreReceiveNoUnicastAnswers(mDNS * const m,const DNSMessage * const response,const mDNSu8 * end,const mDNSAddr * dstaddr,const mDNSIPPort dstport,const mDNSInterfaceID InterfaceID,const mdns_querier_t querier,const mdns_dns_service_t uDNSService,denial_of_existence_records_t ** denial_of_existence_records_ptr,const uDNS_LLQType LLQType)8439 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8440 const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID,
8441 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8442 const mdns_querier_t querier, const mdns_dns_service_t uDNSService,
8443 #endif
8444 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8445 denial_of_existence_records_t **denial_of_existence_records_ptr,
8446 #endif
8447 const uDNS_LLQType LLQType)
8448 {
8449 int i;
8450 const mDNSu8 *ptr = response->data;
8451 CacheRecord *SOARecord = mDNSNULL;
8452
8453 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8454 {
8455 DNSQuestion q;
8456 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8457 if (ptr)
8458 {
8459 DNSQuestion *qptr;
8460 CacheRecord *cr, *neg = mDNSNULL;
8461 CacheGroup *cg;
8462 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8463 if (querier)
8464 {
8465 qptr = Querier_GetDNSQuestion(querier);
8466 }
8467 else
8468 #endif
8469 {
8470 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr);
8471 if (!qptr)
8472 {
8473 continue;
8474 }
8475 }
8476 cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8477 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8478 {
8479 mDNSBool isAnswer;
8480 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8481 if (querier)
8482 {
8483 isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier);
8484 }
8485 else
8486 #endif
8487 {
8488 isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr);
8489 }
8490 if (isAnswer)
8491 {
8492 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8493 if (RRExpireTime(cr) - m->timenow > 0) break;
8494 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8495 if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = cr;
8496 else if (cr->resrec.mortality == Mortality_Ghost)
8497 {
8498 // 3. If the existing entry is expired, mark it to be purged
8499 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8500 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Removing expired record" PRI_S,
8501 q.request_id, mDNSVal16(q.TargetQID), CRDisplayString(m, cr));
8502 mDNS_PurgeCacheResourceRecord(m, cr);
8503 }
8504 }
8505 }
8506 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8507 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8508 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8509 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8510 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8511 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8512 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8513 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8514 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8515 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8516 //
8517 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8518 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8519 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8520 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8521 // do the appropriate thing. This negative response is also needed for appending new search domains.
8522 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8523 {
8524 if (!cr)
8525 {
8526 if (qptr)
8527 {
8528 const mDNSBool noData = ((response->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr) ? mDNStrue : mDNSfalse;
8529 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8530 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME " (" PUB_S ")",
8531 q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
8532 m->CurrentQuestion = qptr;
8533 // We are not creating a cache record in this case, we need to pass back
8534 // the error we got so that the proxy code can return the right one to
8535 // the application
8536 if (qptr->ProxyQuestion)
8537 qptr->responseFlags = response->h.flags;
8538 GenerateNegativeResponseEx(m, mDNSInterface_Any, QC_forceresponse, noData);
8539 m->CurrentQuestion = mDNSNULL;
8540 }
8541 }
8542 else
8543 {
8544 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8545 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME " (" PUB_S ")",
8546 q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
8547 }
8548 }
8549 else
8550 {
8551 if (!cr)
8552 {
8553 // We start off assuming a negative caching TTL of 60 seconds
8554 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8555 mDNSu32 negttl = 60;
8556 int repeat = 0;
8557 const domainname *name = &q.qname;
8558 mDNSu32 hash = q.qnamehash;
8559
8560 // Special case for our special Microsoft Active Directory "local SOA" check.
8561 // Some cheap home gateways don't include an SOA record in the authority section when
8562 // they send negative responses, so we don't know how long to cache the negative result.
8563 // Because we don't want to keep hitting the root name servers with our query to find
8564 // if we're on a network using Microsoft Active Directory using "local" as a private
8565 // internal top-level domain, we make sure to cache the negative result for at least one day.
8566 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8567
8568 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8569 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8570 {
8571 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8572 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8573 {
8574 CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec);
8575 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8576 mDNSu32 ttl_s = soa->min;
8577 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8578 // for the SOA record for ".", where the record is reported as non-cacheable
8579 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8580 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8581 ttl_s = m->rec.r.resrec.rroriginalttl;
8582 if (negttl < ttl_s) negttl = ttl_s;
8583
8584 // Create the SOA record as we may have to return this to the questions
8585 // that we are acting as a proxy for currently or in the future.
8586 SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL);
8587
8588 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8589 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8590 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8591 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8592 //
8593 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8594 // along with the negative cache record. For simplicity, we don't create the additional records.
8595 if ((!qptr || !qptr->ProxyQuestion) && (q.qtype == kDNSType_SOA))
8596 {
8597 int qcount = CountLabels(&q.qname);
8598 int scount = CountLabels(m->rec.r.resrec.name);
8599 if (qcount - 1 > scount)
8600 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8601 repeat = qcount - 1 - scount;
8602 }
8603 }
8604 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8605 }
8606
8607 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8608 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8609 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8610 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8611 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8612 // so that we back off our polling rate and don't keep hitting the server continually.
8613 if (neg)
8614 {
8615 if (negttl < neg->resrec.rroriginalttl * 2)
8616 negttl = neg->resrec.rroriginalttl * 2;
8617 if (negttl > 3600)
8618 negttl = 3600;
8619 }
8620
8621 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
8622
8623 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8624 if (neg)
8625 {
8626 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8627 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S,
8628 q.request_id, mDNSVal16(q.TargetQID), neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8629 RefreshCacheRecord(m, neg, negttl);
8630 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8631 // replace the old records with the new ones
8632 // If qptr is NULL, it means the question is no longer active, and we do not process the record
8633 // for DNSSEC.
8634 if ((qptr != mDNSNULL) && qptr->DNSSECStatus.enable_dnssec)
8635 {
8636 update_denial_records_in_cache_record(neg, denial_of_existence_records_ptr);
8637 }
8638 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8639 // When we created the cache for the first time and answered the question, the question's
8640 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8641 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8642 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8643 // we should reset its question interval here to MaxQuestionInterval.
8644 if (qptr)
8645 {
8646 ResetQuestionState(m, qptr);
8647 }
8648 if (SOARecord)
8649 {
8650 if (neg->soa)
8651 ReleaseCacheRecord(m, neg->soa);
8652 neg->soa = SOARecord;
8653 SOARecord = mDNSNULL;
8654 }
8655 }
8656 else while (1)
8657 {
8658 CacheRecord *negcr;
8659 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8660 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8661 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, uDNSService);
8662 #else
8663 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8664 #endif
8665 m->rec.r.responseFlags = response->h.flags;
8666 // We create SOA records above which might create new cache groups. Earlier
8667 // in the function we looked up the cache group for the name and it could have
8668 // been NULL. If we pass NULL cg to new cache entries that we create below,
8669 // it will create additional cache groups for the same name. To avoid that,
8670 // look up the cache group again to re-initialize cg again.
8671 cg = CacheGroupForName(m, hash, name);
8672 // Need to add with a delay so that we can tag the SOA record
8673 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8674
8675 if (negcr)
8676 {
8677 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8678 // If qptr is NULL, it means the question is no longer active, and we do not process the
8679 // record for DNSSEC.
8680 if (qptr != mDNSNULL && qptr->DNSSECStatus.enable_dnssec)
8681 {
8682 update_denial_records_in_cache_record(negcr, denial_of_existence_records_ptr);
8683 }
8684 #endif
8685 negcr->DelayDelivery = 0;
8686
8687 if (SOARecord)
8688 {
8689 if (negcr->soa)
8690 ReleaseCacheRecord(m, negcr->soa);
8691 negcr->soa = SOARecord;
8692 SOARecord = mDNSNULL;
8693 }
8694 CacheRecordDeferredAdd(m, negcr);
8695 }
8696 m->rec.r.responseFlags = zeroID;
8697 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8698 if (!repeat) break;
8699 repeat--;
8700 name = (const domainname *)(name->c + 1 + name->c[0]);
8701 hash = DomainNameHashValue(name);
8702 }
8703 }
8704 }
8705 }
8706 }
8707 if (SOARecord)
8708 {
8709 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8710 ReleaseCacheRecord(m, SOARecord);
8711 }
8712 }
8713
mDNSCorePrintStoredProxyRecords(mDNS * const m)8714 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8715 {
8716 AuthRecord *rrPtr = mDNSNULL;
8717 if (!m->SPSRRSet) return;
8718 LogSPS("Stored Proxy records :");
8719 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8720 {
8721 LogSPS("%s", ARDisplayString(m, rrPtr));
8722 }
8723 }
8724
mDNSCoreRegisteredProxyRecord(mDNS * const m,AuthRecord * rr)8725 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8726 {
8727 AuthRecord *rrPtr = mDNSNULL;
8728
8729 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8730 {
8731 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8732 {
8733 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8734 return mDNStrue;
8735 }
8736 }
8737 mDNSCorePrintStoredProxyRecords(m);
8738 return mDNSfalse;
8739 }
8740
mDNSCoreReceiveCacheCheck(mDNS * const m,const DNSMessage * const response,uDNS_LLQType LLQType,const mDNSu32 slot,CacheGroup * cg,CacheRecord *** cfp,mDNSInterfaceID InterfaceID)8741 mDNSexport CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8742 const mDNSu32 slot, CacheGroup *cg, CacheRecord ***cfp, mDNSInterfaceID InterfaceID)
8743 {
8744 CacheRecord *cr;
8745 CacheRecord **cflocal = *cfp;
8746
8747 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8748 {
8749 mDNSBool match;
8750 // Resource record received via unicast, the resGroupID should match ?
8751 if (!InterfaceID)
8752 {
8753 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8754 match = (cr->resrec.dnsservice == m->rec.r.resrec.dnsservice) ? mDNStrue : mDNSfalse;
8755 #else
8756 const mDNSu32 id1 = (cr->resrec.rDNSServer ? cr->resrec.rDNSServer->resGroupID : 0);
8757 const mDNSu32 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8758 match = (id1 == id2);
8759 #endif
8760 }
8761 else
8762 match = (cr->resrec.InterfaceID == InterfaceID);
8763 // If we found this exact resource record, refresh its TTL
8764 if (match)
8765 {
8766 if (IdenticalSameNameRecord(&m->rec.r.resrec, &cr->resrec))
8767 {
8768 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8769 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8770 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8771
8772 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8773 {
8774 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8775 if (cr->NextInCFList == mDNSNULL && *cfp != &cr->NextInCFList && LLQType != uDNS_LLQ_Events)
8776 {
8777 *cflocal = cr;
8778 cflocal = &cr->NextInCFList;
8779 *cflocal = (CacheRecord*)1;
8780 *cfp = &cr->NextInCFList;
8781 }
8782
8783 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8784 if (!(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8785 {
8786 DNSQuestion *q;
8787 for (q = m->Questions; q; q=q->next)
8788 {
8789 if (CacheRecordAnswersQuestion(cr, q))
8790 q->UniqueAnswers++;
8791 }
8792 cr->resrec.RecordType = m->rec.r.resrec.RecordType;
8793 }
8794 }
8795
8796 if (!SameRDataBody(&m->rec.r.resrec, &cr->resrec.rdata->u, SameDomainNameCS))
8797 {
8798 // If the rdata of the packet record differs in name capitalization from the record in our cache
8799 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8800 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8801 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8802 cr->resrec.rroriginalttl = 0;
8803 cr->TimeRcvd = m->timenow;
8804 cr->UnansweredQueries = MaxUnansweredQueries;
8805 SetNextCacheCheckTimeForRecord(m, cr);
8806 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S, CRDisplayString(m, cr));
8807 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S, CRDisplayString(m, &m->rec.r));
8808 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8809 NextCacheCheckEvent(cr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8810 // DO NOT break out here -- we want to continue as if we never found it
8811 }
8812 else if (m->rec.r.resrec.rroriginalttl > 0)
8813 {
8814 DNSQuestion *q;
8815
8816 m->mDNSStats.CacheRefreshed++;
8817
8818 if ((cr->resrec.mortality == Mortality_Ghost) && !cr->DelayDelivery)
8819 {
8820 cr->DelayDelivery = NonZeroTime(m->timenow);
8821 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(cr), CRDisplayString(m, cr));
8822 }
8823
8824 if (cr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, cr));
8825 RefreshCacheRecord(m, cr, m->rec.r.resrec.rroriginalttl);
8826 // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop.
8827 // 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.
8828 RefreshCacheRecordCacheGroupOrder(cg, cr);
8829 cr->responseFlags = response->h.flags;
8830
8831 // If we may have NSEC records returned with the answer (which we don't know yet as it
8832 // has not been processed), we need to cache them along with the first cache
8833 // record in the list that answers the question so that it can be used for validation
8834 // later. The "type" check below is to make sure that we cache on the cache record
8835 // that would answer the question. It is possible that we might cache additional things
8836 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8837 // the record that answers the question.
8838 if (!InterfaceID)
8839 {
8840 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S, CRDisplayString(m, cr));
8841 }
8842 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8843 // polling the network once we get a valid response back. For the first time when a new
8844 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8845 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8846 // configuration changed, without flushing the cache, we reset the question interval here.
8847 // Currently, we do this for for both multicast and unicast questions as long as the record
8848 // type is unique. For unicast, resource record is always unique and for multicast it is
8849 // true for records like A etc. but not for PTR.
8850 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8851 {
8852 for (q = m->Questions; q; q=q->next)
8853 {
8854 if (!q->DuplicateOf && !q->LongLived &&
8855 ActiveQuestion(q) && CacheRecordAnswersQuestion(cr, q))
8856 {
8857 ResetQuestionState(m, q);
8858 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8859 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8860 }
8861 }
8862 }
8863 break; // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above)
8864 }
8865 else
8866 {
8867 // If the packet TTL is zero, that means we're deleting this record.
8868 // To give other hosts on the network a chance to protest, we push the deletion
8869 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8870 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8871 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8872 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8873 // If the record is already going to expire in less than one second anyway, we leave it alone --
8874 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8875 debugf("DE for %s", CRDisplayString(m, cr));
8876 if (RRExpireTime(cr) - m->timenow > mDNSPlatformOneSecond)
8877 {
8878 cr->resrec.rroriginalttl = 1;
8879 cr->TimeRcvd = m->timenow;
8880 cr->UnansweredQueries = MaxUnansweredQueries;
8881 SetNextCacheCheckTimeForRecord(m, cr);
8882 }
8883 break;
8884 }
8885 }
8886 else if (cr->resrec.rroriginalttl != 0 && // Not already marked for discarding
8887 m->rec.r.resrec.rrclass == cr->resrec.rrclass &&
8888 (m->rec.r.resrec.rrtype != cr->resrec.rrtype &&
8889 (m->rec.r.resrec.rrtype == kDNSType_CNAME || cr->resrec.rrtype == kDNSType_CNAME)))
8890 {
8891 // If the cache record rrtype doesn't match and one is a CNAME, then flush this record
8892 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding (%s) " PRI_S " rrtype change from (%s) to (%s)",
8893 MortalityDisplayString(cr->resrec.mortality), CRDisplayString(m, cr), DNSTypeName(cr->resrec.rrtype), DNSTypeName(m->rec.r.resrec.rrtype));
8894 mDNS_PurgeCacheResourceRecord(m, cr);
8895 // DO NOT break out here -- we want to continue iterating the cache entries
8896 }
8897 }
8898 }
8899 return cr;
8900 }
8901
mDNSCoreResetRecord(mDNS * const m)8902 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8903 {
8904 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8905 }
8906
8907 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8908 // the record list and/or question list.
8909 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8910 // InterfaceID non-NULL tells us the interface this multicast response was received on
8911 // InterfaceID NULL tells us this was a unicast response
8912 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
mDNSCoreReceiveResponse(mDNS * const m,const DNSMessage * const response,const mDNSu8 * end,const mDNSAddr * srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,mDNSIPPort dstport,mdns_querier_t querier,mdns_dns_service_t uDNSService,const mDNSInterfaceID InterfaceID)8913 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8914 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8915 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8916 mdns_querier_t querier, mdns_dns_service_t uDNSService,
8917 #endif
8918 const mDNSInterfaceID InterfaceID)
8919 {
8920 int i;
8921 const mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8922 const mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8923 DNSQuestion *llqMatch = mDNSNULL;
8924 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8925
8926 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8927 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8928 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8929 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8930 CacheRecord **cfp = &CacheFlushRecords;
8931 NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8932 mDNSBool recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8933
8934 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8935 // to guard against spoof responses, then the only credible protection against that is cryptographic
8936 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8937 int firstauthority = response->h.numAnswers;
8938 int firstadditional = firstauthority + response->h.numAuthorities;
8939 int totalrecords = firstadditional + response->h.numAdditionals;
8940 const mDNSu8 *ptr = response->data;
8941 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8942 DNSServer *uDNSServer = mDNSNULL;
8943 #endif
8944 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8945 denial_of_existence_records_t *denial_of_existence_records = mDNSNULL;
8946 mDNSBool not_answer_but_required_for_dnssec = mDNSfalse;
8947 #endif
8948 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8949 // Determine whether the response is mDNS, as opposed to DNS.
8950 // Thus far, the code has assumed that responses with IDs set to zero are mDNS responses. However, this condition
8951 // isn't sufficient because queriers, which are used exclusively for DNS queries, may set the IDs of their queries
8952 // to zero. And consequently, their responses may have their IDs set to zero. Specifically, zero-valued IDs are used
8953 // for DNS over HTTPs, as specified by <https://tools.ietf.org/html/rfc8484#section-4.1>.
8954 const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id) && !querier;
8955 #else
8956 const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id);
8957 #endif
8958
8959 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8960 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8961 srcaddr, dstaddr, InterfaceID,
8962 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
8963 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
8964 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
8965 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
8966
8967 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8968 if (mDNSSameIPPort(srcport, UnicastDNSPort))
8969 {
8970 MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response));
8971 }
8972 #endif
8973
8974 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8975 // When a DNS client receives a reply with TC
8976 // set, it should ignore that response, and query again, using a
8977 // mechanism, such as a TCP connection, that will permit larger replies.
8978 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8979 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8980 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8981 // <rdar://problem/6690034> Can't bind to Active Directory
8982 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8983 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8984 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
8985 // and not even do the TCP query.
8986 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
8987 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
8988 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
8989 // section, and the answer section is therefore assumed to be complete.
8990 //
8991 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
8992 // When a response is so long that truncation is required, the truncation
8993 // should start at the end of the response and work forward in the
8994 // datagram. Thus if there is any data for the authority section, the
8995 // answer section is guaranteed to be unique.
8996 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8997 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && !querier &&
8998 #else
8999 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) &&
9000 #endif
9001 ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return;
9002
9003 if (LLQType == uDNS_LLQ_Ignore) return;
9004
9005 // 1. We ignore questions (if any) in mDNS response packets
9006 // 2. If this is an LLQ response, we handle it much the same
9007 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9008 if (ResponseMCast || LLQType == uDNS_LLQ_Events)
9009 ptr = LocateAnswers(response, end);
9010 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9011 // in this response packet are immediately deemed to be invalid.
9012 else
9013 {
9014 mDNSBool failure, returnEarly;
9015 const int rcode = response->h.flags.b[1] & kDNSFlag1_RC_Mask;
9016 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
9017 returnEarly = mDNSfalse;
9018 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9019 // When the QUERIER functionality is enabled, DNS transport is handled exclusively by querier objects. If this
9020 // response was provided by a querier, but the RCODE is considered a failure, then set failure to false so that
9021 // we don't return early. The logic of returning early was so that uDNS_CheckCurrentQuestion() could handle
9022 // resending the query and generate a negative cache record if all servers were tried. If the querier provides a
9023 // response, then it's the best response that it could provide. If the RCODE is considered a failure,
9024 // mDNSCoreReceiveResponse() needs to create negative cache entries for the unanwered question, so totalrecords
9025 // is set to 0 to ignore any records that the response may contain.
9026 if (querier && failure)
9027 {
9028 totalrecords = 0;
9029 failure = mDNSfalse;
9030 }
9031 #endif
9032 // We could possibly combine this with the similar loop at the end of this function --
9033 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9034 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9035 // which it was received (or refreshed), and then at the end if we find any cache records which
9036 // answer questions in this packet's question section, but which aren't tagged with this packet's
9037 // packet number, then we deduce they are old and delete them
9038 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
9039 {
9040 DNSQuestion q;
9041 DNSQuestion *qptr;
9042 mDNSBool expectingResponse;
9043 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
9044 if (!ptr)
9045 {
9046 continue;
9047 }
9048 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9049 if (querier)
9050 {
9051 expectingResponse = mDNStrue;
9052 qptr = mDNSNULL;
9053 }
9054 else
9055 #endif
9056 {
9057 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr);
9058 expectingResponse = qptr ? mDNStrue : mDNSfalse;
9059 }
9060 if (!expectingResponse)
9061 {
9062 continue;
9063 }
9064 if (!failure)
9065 {
9066 CacheRecord *cr;
9067 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
9068 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
9069 {
9070 mDNSBool isAnswer;
9071 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9072 if (querier)
9073 {
9074 isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier);
9075 }
9076 else
9077 #endif
9078 {
9079 isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr);
9080 }
9081 if (isAnswer)
9082 {
9083 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
9084 cr->resrec.InterfaceID, CRDisplayString(m, cr));
9085 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9086 cr->TimeRcvd = m->timenow - TicksTTL(cr) - 1;
9087 cr->UnansweredQueries = MaxUnansweredQueries;
9088 }
9089 }
9090 }
9091 else
9092 {
9093 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9094 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9095 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME " (" PUB_S ")",
9096 qptr->request_id, mDNSVal16(qptr->TargetQID), qptr->qDNSServer, rcode,
9097 DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
9098 PenalizeDNSServer(m, qptr, response->h.flags);
9099 #endif
9100 returnEarly = mDNStrue;
9101 }
9102 }
9103 if (returnEarly)
9104 {
9105 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9106 "[Q%d] Ignoring %2d Answer" PUB_S " %2d Authorit" PUB_S " %2d Additional" PUB_S,
9107 mDNSVal16(response->h.id),
9108 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
9109 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
9110 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
9111 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9112 // generate negative cache entries (we want to query the next server)
9113 return;
9114 }
9115 }
9116
9117 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
9118 {
9119 // All responses sent via LL multicast are acceptable for caching
9120 // All responses received over our outbound TCP connections are acceptable for caching
9121 // We accept all records in a unicast response to a multicast query once we find one that
9122 // answers an active question.
9123 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9124 mDNSBool AcceptableResponse = ResponseMCast || (!querier && !dstaddr) || LLQType || recordAcceptedInResponse;
9125 #else
9126 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse;
9127 #endif
9128 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9129 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9130
9131 const mDNSu8 RecordType =
9132 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
9133 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
9134 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
9135 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9136
9137 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
9138 {
9139 mDNSCoreResetRecord(m);
9140 continue;
9141 }
9142
9143 // Don't want to cache OPT or TSIG pseudo-RRs
9144 if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
9145 {
9146 mDNSCoreResetRecord(m);
9147 continue;
9148 }
9149 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
9150 {
9151 const rdataOPT *opt;
9152 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9153 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9154 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9155 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
9156 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
9157 {
9158 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
9159 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
9160 }
9161 mDNSCoreResetRecord(m);
9162 continue;
9163 }
9164 // if a CNAME record points to itself, then don't add it to the cache
9165 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
9166 {
9167 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
9168 mDNSCoreResetRecord(m);
9169 continue;
9170 }
9171
9172 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9173 // In the case of active LLQs, we'll get remove events when the records actually do go away
9174 // In the case of polling LLQs, we assume the record remains valid until the next poll
9175 if (!ResponseIsMDNS)
9176 {
9177 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
9178 }
9179
9180 // If response was not sent via LL multicast,
9181 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9182 if (!ResponseMCast)
9183 {
9184 if (LLQType)
9185 {
9186 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9187 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9188 // queries to get ADD/RMV events. To lookup the question, we can't use
9189 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9190 // has already matched the question using the 64 bit Id in the packet and we use that here.
9191
9192 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9193 if (querier)
9194 {
9195 mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService);
9196 }
9197 #else
9198 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
9199 #endif
9200 }
9201 else if (!AcceptableResponse || !dstaddr)
9202 {
9203 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9204 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9205 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9206 // we create.
9207 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9208 if (querier)
9209 {
9210 ResourceRecord *const rr = &m->rec.r.resrec;
9211 if (Querier_ResourceRecordIsAnswer(rr, querier))
9212 {
9213 const mdns_resolver_type_t resolver_type = mdns_querier_get_resolver_type(querier);
9214 if ((resolver_type == mdns_resolver_type_normal) &&
9215 (mdns_querier_get_over_tcp_reason(querier) != mdns_query_over_tcp_reason_null))
9216 {
9217 rr->protocol = mdns_resolver_type_tcp;
9218 }
9219 else
9220 {
9221 rr->protocol = resolver_type;
9222 }
9223 mdns_replace(&rr->dnsservice, uDNSService);
9224 AcceptableResponse = mDNStrue;
9225 }
9226 }
9227 else
9228 #endif
9229 {
9230 const DNSQuestion *q;
9231 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9232 // this record.
9233 //
9234 // We could potentially lookup the DNS server based on the source address, but that may not work always
9235 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9236 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9237 // on the "id" and "source port", then this response answers the question and assume the response
9238 // came from the same DNS server that we sent the query to.
9239 q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
9240 if (q != mDNSNULL)
9241 {
9242 AcceptableResponse = mDNStrue;
9243 if (!InterfaceID)
9244 {
9245 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9246 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9247 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9248 #endif
9249 }
9250 else
9251 {
9252 // Accept all remaining records in this unicast response to an mDNS query.
9253 recordAcceptedInResponse = mDNStrue;
9254 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9255 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME " (" PUB_S ")",
9256 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
9257 }
9258 }
9259 else
9260 {
9261 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9262 // the question. The code below does that. So, make this record unacceptable for now
9263 if (!InterfaceID)
9264 {
9265 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9266 AcceptableResponse = mDNSfalse;
9267 }
9268 }
9269 }
9270 }
9271 }
9272 else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9273 {
9274 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9275 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9276 // To work with these broken routers, client devices need to blacklist these broken
9277 // routers and ignore their bogus ARP responses. Some devices implement a technique
9278 // such as the one described in US Patent 7436783, which lets clients detect and
9279 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9280
9281 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9282 // approach of just detecting these broken routers and completely disabling IPv4
9283 // link-local communication on interfaces where a broken router is detected.
9284 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9285 // that are deemed “safe” for IPv4 link-local communication;
9286 // the flag is cleared on interfaces where a broken router is detected.
9287
9288 // OS X and iOS will not even try to communicate with an IPv4
9289 // link-local destination on an interface without the IFEF_ARPLL flag set.
9290 // This can cause some badly written applications to freeze for a long time if they
9291 // attempt to connect to an IPv4 link-local destination address and then wait for
9292 // that connection attempt to time out before trying other candidate addresses.
9293
9294 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9295 // records on interfaces where we know the OS will be unwilling even to attempt
9296 // communication with those IPv4 link-local destination addresses.
9297 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9298
9299 const CacheRecord *const rr = &m->rec.r;
9300 const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9301 if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9302 {
9303 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9304 mDNSCoreResetRecord(m);
9305 continue;
9306 }
9307 }
9308
9309 // 1. Check that this packet resource record does not conflict with any of ours
9310 if (ResponseIsMDNS && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9311 {
9312 if (m->CurrentRecord)
9313 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9314 m->CurrentRecord = m->ResourceRecords;
9315 while (m->CurrentRecord)
9316 {
9317 AuthRecord *rr = m->CurrentRecord;
9318 m->CurrentRecord = rr->next;
9319 // We accept all multicast responses, and unicast responses resulting from queries we issued
9320 // For other unicast responses, this code accepts them only for responses with an
9321 // (apparently) local source address that pertain to a record of our own that's in probing state
9322 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9323
9324 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
9325 {
9326 // ... check to see if type and rdata are identical
9327 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9328 {
9329 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9330 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9331 {
9332 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9333 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9334 }
9335 else
9336 {
9337 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
9338 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9339 }
9340 }
9341 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9342 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9343 {
9344 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9345 m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r), IIDPrintable(InterfaceID));
9346 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9347
9348 // If this record is marked DependentOn another record for conflict detection purposes,
9349 // then *that* record has to be bumped back to probing state to resolve the conflict
9350 if (rr->DependentOn)
9351 {
9352 while (rr->DependentOn) rr = rr->DependentOn;
9353 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9354 }
9355
9356 // If we've just whacked this record's ProbeCount, don't need to do it again
9357 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9358 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9359 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9360 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9361 else
9362 {
9363 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9364 // If we'd previously verified this record, put it back to probing state and try again
9365 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9366 {
9367 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9368 rr->resrec.RecordType = kDNSRecordTypeUnique;
9369 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9370 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9371 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9372 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9373 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9374 rr->AnnounceCount = InitialAnnounceCount;
9375 InitializeLastAPTime(m, rr);
9376 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9377 }
9378 // If we're probing for this record, we just failed
9379 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9380 {
9381 // At this point in the code, we're probing for uniqueness.
9382 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9383 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9384 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9385 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9386 {
9387 if ((rr->ProbingConflictCount == 0) || (m->MPktNum != rr->LastConflictPktNum))
9388 {
9389 const NetworkInterfaceInfo *const intf = FirstInterfaceForID(m, InterfaceID);
9390 rr->ProbingConflictCount++;
9391 rr->LastConflictPktNum = m->MPktNum;
9392 if (ResponseMCast && (!intf || intf->SupportsUnicastMDNSResponse) &&
9393 (rr->ProbingConflictCount <= kMaxAllowedMCastProbingConflicts))
9394 {
9395 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9396 "spurious multicast conflict (%d/%d) via interface %d for %s",
9397 rr->ProbeCount, kProbingConflictPauseDuration, rr->ProbingConflictCount,
9398 kMaxAllowedMCastProbingConflicts, IIDPrintable(InterfaceID), ARDisplayString(m, rr));
9399 rr->ProbeCount = DefaultProbeCountForTypeUnique;
9400 rr->LastAPTime = m->timenow + kProbingConflictPauseDuration - rr->ThisAPInterval;
9401 SetNextAnnounceProbeTime(m, rr);
9402 }
9403 else
9404 {
9405 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9406 rr->ProbeCount, ARDisplayString(m, rr), ResponseMCast ? "multi" : "uni", IIDPrintable(InterfaceID));
9407 m->mDNSStats.NameConflicts++;
9408 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9409 // See if this record was also registered with any D2D plugins.
9410 D2D_stop_advertising_record(rr);
9411 #endif
9412 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9413 }
9414 }
9415 }
9416 }
9417 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9418 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9419 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9420 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9421 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9422 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9423 {
9424 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9425 m->mDNSStats.KnownUniqueNameConflicts++;
9426 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9427 D2D_stop_advertising_record(rr);
9428 #endif
9429 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9430 }
9431 else
9432 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9433 }
9434 }
9435 // Else, matching signature, different type or rdata, but not a considered a conflict.
9436 // If the packet record has the cache-flush bit set, then we check to see if we
9437 // have any record(s) of the same type that we should re-assert to rescue them
9438 // (see note about "multi-homing and bridged networks" at the end of this function).
9439 else if ((m->rec.r.resrec.rrtype == rr->resrec.rrtype) &&
9440 (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) &&
9441 ((mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2) &&
9442 ResourceRecordIsValidAnswer(rr))
9443 {
9444 rr->ImmedAnswer = mDNSInterfaceMark;
9445 m->NextScheduledResponse = m->timenow;
9446 }
9447 }
9448 }
9449 }
9450
9451 if (!AcceptableResponse)
9452 {
9453 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9454 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9455 not_answer_but_required_for_dnssec = adds_denial_records_in_cache_record(&m->rec.r.resrec,
9456 querier != mDNSNULL && mdns_querier_get_dnssec_ok(querier), &denial_of_existence_records);
9457 #else
9458 not_answer_but_required_for_dnssec = mDNSfalse;
9459 #endif
9460 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9461 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords);
9462
9463 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9464 if (AcceptableResponse) mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService);
9465 #else
9466 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9467 #endif
9468 }
9469
9470 // 2. See if we want to add this packet resource record to our cache
9471 // We only try to cache answers if we have a cache to put them in
9472 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9473 if (!AcceptableResponse) {
9474 const char* savedString = "";
9475 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9476 savedString = (not_answer_but_required_for_dnssec ? "Saved for DNSSEC" : "");
9477 #endif
9478 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S " %s",
9479 mDNSVal16(response->h.id), CRDisplayString(m, &m->rec.r), savedString);
9480 }
9481
9482 if (m->rrcache_size && AcceptableResponse)
9483 {
9484 const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash);
9485 CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec);
9486 CacheRecord *rr = mDNSNULL;
9487
9488 // 2a. Check if this packet resource record is already in our cache.
9489 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, &cfp, InterfaceID);
9490
9491 // If packet resource record not in our cache, add it now
9492 // (unless it is just a deletion of a record we never had, in which case we don't care)
9493 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9494 {
9495 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9496 mDNSs32 delay;
9497
9498 if (AddToCFList)
9499 delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9500 else
9501 delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash);
9502
9503 // If unique, assume we may have to delay delivery of this 'add' event.
9504 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9505 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9506 // to schedule an mDNS_Execute task at the appropriate time.
9507 rr = CreateNewCacheEntry(m, slot, cg, delay, mDNStrue, srcaddr);
9508 if (rr)
9509 {
9510 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9511 set_denial_records_in_cache_record(rr, &denial_of_existence_records);
9512 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9513
9514 rr->responseFlags = response->h.flags;
9515
9516 if (AddToCFList)
9517 {
9518 *cfp = rr;
9519 cfp = &rr->NextInCFList;
9520 *cfp = (CacheRecord*)1;
9521 }
9522 else if (rr->DelayDelivery)
9523 {
9524 ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9525 }
9526 }
9527 }
9528 }
9529 mDNSCoreResetRecord(m);
9530 }
9531
9532 exit:
9533 mDNSCoreResetRecord(m);
9534
9535 // If we've just received one or more records with their cache flush bits set,
9536 // then scan that cache slot to see if there are any old stale records we need to flush
9537 while (CacheFlushRecords != (CacheRecord*)1)
9538 {
9539 CacheRecord *r1 = CacheFlushRecords, *r2;
9540 const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash);
9541 const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec);
9542 mDNSBool purgedRecords = mDNSfalse;
9543 CacheFlushRecords = CacheFlushRecords->NextInCFList;
9544 r1->NextInCFList = mDNSNULL;
9545
9546 // Look for records in the cache with the same signature as this new one with the cache flush
9547 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9548 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9549 // We make these TTL adjustments *only* for records that still have *more* than one second
9550 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9551 // (and now has half a second remaining) could inadvertently get its life extended, by either
9552 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9553 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9554 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9555 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9556 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9557 // To avoid this, we need to ensure that the cache flushing operation will only act to
9558 // *decrease* a record's remaining lifetime, never *increase* it.
9559 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9560 {
9561 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9562 mDNSBool match;
9563 #else
9564 mDNSu32 id1;
9565 mDNSu32 id2;
9566 #endif
9567 if (!r1->resrec.InterfaceID)
9568 {
9569 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9570 match = (r1->resrec.dnsservice == r2->resrec.dnsservice) ? mDNStrue : mDNSfalse;
9571 #else
9572 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9573 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9574 #endif
9575 }
9576 else
9577 {
9578 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9579 match = mDNStrue;
9580 #else
9581 id1 = id2 = 0;
9582 #endif
9583 }
9584 // For Unicast (null InterfaceID) the resolver IDs should also match
9585 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9586 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9587 (r1->resrec.InterfaceID || match) &&
9588 #else
9589 (r1->resrec.InterfaceID || (id1 == id2)) &&
9590 #endif
9591 r1->resrec.rrtype == r2->resrec.rrtype &&
9592 r1->resrec.rrclass == r2->resrec.rrclass
9593 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9594 // 2 RRSIGs need to cover the same DNS type to be identified as one RRSET, and have the same TTL
9595 && are_records_in_the_same_cache_set_for_dnssec(&r1->resrec, &r2->resrec)
9596 #endif
9597 )
9598 {
9599 if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal)
9600 {
9601 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2);
9602 r1->resrec.mortality = Mortality_Immortal; // Immortalize the replacement record
9603 }
9604
9605 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9606 // else, if record is old, mark it to be flushed
9607 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9608 {
9609 // If we find mismatched TTLs in an RRSet, correct them.
9610 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9611 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9612 // which we treat as a goodbye followed by an addition) and in that case it would be
9613 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9614
9615 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9616 // because certain early Bonjour devices are known to have this specific mismatch, and
9617 // there's no point filling syslog with messages about something we already know about.
9618 // We also don't log this for uDNS responses, since a caching name server is obliged
9619 // to give us an aged TTL to correct for how long it has held the record,
9620 // so our received TTLs are expected to vary in that case
9621
9622 // We also suppress log message in the case of SRV records that are received
9623 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9624 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9625 // GM builds.
9626 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9627 {
9628 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9629 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9630 ResponseIsMDNS)
9631 LogInfo("Correcting TTL from %4d to %4d for %s",
9632 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9633 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9634 }
9635 r2->TimeRcvd = m->timenow;
9636 SetNextCacheCheckTimeForRecord(m, r2);
9637 }
9638 else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed
9639 {
9640 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9641 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9642 // We set stale records to expire in one second.
9643 // This gives the owner a chance to rescue it if necessary.
9644 // This is important in the case of multi-homing and bridged networks:
9645 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9646 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9647 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9648 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9649 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9650 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9651
9652 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9653 // final expiration queries for this record.
9654
9655 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9656 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9657 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9658 // <rdar://problem/5636422> Updating TXT records is too slow
9659 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9660 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9661 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9662 {
9663 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9664 r2->resrec.rroriginalttl = 0;
9665 }
9666 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9667 {
9668 // We only set a record to expire in one second if it currently has *more* than a second to live
9669 // If it's already due to expire in a second or less, we just leave it alone
9670 r2->resrec.rroriginalttl = 1;
9671 r2->UnansweredQueries = MaxUnansweredQueries;
9672 r2->TimeRcvd = m->timenow - 1;
9673 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9674 // that we marked for deletion via an explicit DE record
9675 }
9676 SetNextCacheCheckTimeForRecord(m, r2);
9677 }
9678 else
9679 {
9680 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9681 if (r2->resrec.mortality == Mortality_Ghost)
9682 {
9683 DNSQuestion * q;
9684 for (q = m->Questions; q; q=q->next)
9685 {
9686 if (!q->LongLived && ActiveQuestion(q) &&
9687 CacheRecordAnswersQuestion(r2, q) &&
9688 q->metrics.expiredAnswerState == ExpiredAnswer_AnsweredWithExpired)
9689 {
9690 q->metrics.expiredAnswerState = ExpiredAnswer_ExpiredAnswerChanged;
9691 }
9692 }
9693 }
9694 #endif
9695 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9696 mDNS_PurgeCacheResourceRecord(m, r2);
9697 purgedRecords = mDNStrue;
9698 }
9699 }
9700 }
9701
9702 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
9703 {
9704 if (r1->resrec.InterfaceID)
9705 {
9706 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash);
9707 }
9708 else
9709 {
9710 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9711 // them to be deleted before any ADD events for this record.
9712 r1->DelayDelivery = purgedRecords ? NonZeroTime(m->timenow) : 0;
9713 }
9714 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9715 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9716 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9717 }
9718 }
9719
9720 // See if we need to generate negative cache entries for unanswered unicast questions
9721 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID,
9722 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9723 querier, uDNSService,
9724 #endif
9725 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9726 &denial_of_existence_records,
9727 #endif
9728 LLQType);
9729
9730 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9731 destroy_denial_of_existence_records_t_if_nonnull(denial_of_existence_records);
9732 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9733 }
9734
9735 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9736 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9737 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9738 // that warrants waking the sleeping host.
9739 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9740
ScheduleWakeupForList(mDNS * const m,mDNSInterfaceID InterfaceID,mDNSEthAddr * e,AuthRecord * const thelist)9741 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9742 {
9743 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9744 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9745 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9746 // simple, we use the same mechanism for both lists.
9747 if (!e->l[0])
9748 {
9749 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9750 return;
9751 }
9752 m->CurrentRecord = thelist;
9753 while (m->CurrentRecord)
9754 {
9755 AuthRecord *const rr = m->CurrentRecord;
9756 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9757 {
9758 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9759 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9760 }
9761 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9762 m->CurrentRecord = rr->next;
9763 }
9764 }
9765
ScheduleWakeup(mDNS * const m,mDNSInterfaceID InterfaceID,mDNSEthAddr * e)9766 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9767 {
9768 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9769 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9770 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9771 }
9772
SPSRecordCallback(mDNS * const m,AuthRecord * const ar,mStatus result)9773 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9774 {
9775 if (result && result != mStatus_MemFree)
9776 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9777
9778 if (result == mStatus_NameConflict)
9779 {
9780 mDNS_Lock(m);
9781 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9782 if (ar->WakeUp.HMAC.l[0])
9783 {
9784 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse); // Send one wakeup magic packet
9785 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
9786 }
9787 mDNS_Unlock(m);
9788 }
9789
9790 if (result == mStatus_NameConflict || result == mStatus_MemFree)
9791 {
9792 m->ProxyRecords--;
9793 mDNSPlatformMemFree(ar);
9794 mDNS_UpdateAllowSleep(m);
9795 }
9796 }
9797
GetValueForMACAddr(mDNSu8 * ptr,mDNSu8 * limit,mDNSEthAddr * eth)9798 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9799 {
9800 int i;
9801 mDNSs8 hval = 0;
9802 int colons = 0;
9803 mDNSu8 val = 0;
9804
9805 for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9806 {
9807 hval = HexVal(*ptr);
9808 if (hval != -1)
9809 {
9810 val <<= 4;
9811 val |= hval;
9812 }
9813 else if (*ptr == ':')
9814 {
9815 if (colons >=5)
9816 {
9817 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9818 return mDNSNULL;
9819 }
9820 eth->b[colons] = val;
9821 colons++;
9822 val = 0;
9823 }
9824 }
9825 if (colons != 5)
9826 {
9827 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9828 return mDNSNULL;
9829 }
9830 eth->b[colons] = val;
9831 return ptr;
9832 }
9833
GetValueForIPv6Addr(mDNSu8 * ptr,mDNSu8 * limit,mDNSv6Addr * v6)9834 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9835 {
9836 int hval;
9837 int value;
9838 int numBytes;
9839 int digitsProcessed;
9840 int zeroFillStart;
9841 int numColons;
9842 mDNSu8 v6addr[16];
9843
9844 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9845 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9846 //
9847 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9848 // the result in "v6"
9849
9850 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9851 while (ptr < limit && *ptr != ' ')
9852 {
9853 hval = HexVal(*ptr);
9854 if (hval != -1)
9855 {
9856 value <<= 4;
9857 value |= hval;
9858 digitsProcessed = 1;
9859 }
9860 else if (*ptr == ':')
9861 {
9862 if (!digitsProcessed)
9863 {
9864 // If we have already seen a "::", we should not see one more. Handle the special
9865 // case of "::"
9866 if (numColons)
9867 {
9868 // if we never filled any bytes and the next character is space (we have reached the end)
9869 // we are done
9870 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9871 {
9872 mDNSPlatformMemZero(v6->b, 16);
9873 return ptr + 1;
9874 }
9875 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9876 return mDNSNULL;
9877 }
9878
9879 // We processed "::". We need to fill zeroes later. For now, mark the
9880 // point where we will start filling zeroes from.
9881 zeroFillStart = numBytes;
9882 numColons++;
9883 }
9884 else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9885 {
9886 // We have a trailing ":" i.e., no more characters after ":"
9887 LogMsg("GetValueForIPv6Addr: Trailing colon");
9888 return mDNSNULL;
9889 }
9890 else
9891 {
9892 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9893 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9894 // filled here is 12 and 13.
9895 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9896
9897 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9898 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9899 digitsProcessed = value = 0;
9900
9901 // Make sure that we did not fill the 13th and 14th byte above
9902 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9903 }
9904 }
9905 ptr++;
9906 }
9907
9908 // We should be processing the last set of bytes following the last ":" here
9909 if (!digitsProcessed)
9910 {
9911 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9912 return mDNSNULL;
9913 }
9914
9915 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9916 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9917 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9918
9919 if (zeroFillStart)
9920 {
9921 int i, j, n;
9922 for (i = 0; i < zeroFillStart; i++)
9923 v6->b[i] = v6addr[i];
9924 for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9925 v6->b[j] = 0;
9926 for (; j < 16; i++, j++)
9927 v6->b[j] = v6addr[i];
9928 }
9929 else if (numBytes == 16)
9930 mDNSPlatformMemCopy(v6->b, v6addr, 16);
9931 else
9932 {
9933 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9934 return mDNSNULL;
9935 }
9936 return ptr;
9937 }
9938
GetValueForIPv4Addr(mDNSu8 * ptr,mDNSu8 * limit,mDNSv4Addr * v4)9939 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9940 {
9941 mDNSu32 val;
9942 int dots = 0;
9943 val = 0;
9944
9945 for ( ; ptr < limit && *ptr != ' '; ptr++)
9946 {
9947 if (*ptr >= '0' && *ptr <= '9')
9948 val = val * 10 + *ptr - '0';
9949 else if (*ptr == '.')
9950 {
9951 if (val > 255 || dots >= 3)
9952 {
9953 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
9954 return mDNSNULL;
9955 }
9956 v4->b[dots++] = val;
9957 val = 0;
9958 }
9959 else
9960 {
9961 // We have a zero at the end and if we reached that, then we are done.
9962 if (*ptr == 0 && ptr == limit - 1 && dots == 3)
9963 {
9964 v4->b[dots] = val;
9965 return ptr + 1;
9966 }
9967 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
9968 }
9969 }
9970 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
9971 v4->b[dots] = val;
9972 return ptr;
9973 }
9974
GetValueForKeepalive(mDNSu8 * ptr,mDNSu8 * limit,mDNSu32 * value)9975 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
9976 {
9977 mDNSu32 val;
9978
9979 val = 0;
9980 for ( ; ptr < limit && *ptr != ' '; ptr++)
9981 {
9982 if (*ptr < '0' || *ptr > '9')
9983 {
9984 // We have a zero at the end and if we reached that, then we are done.
9985 if (*ptr == 0 && ptr == limit - 1)
9986 {
9987 *value = val;
9988 return ptr + 1;
9989 }
9990 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
9991 }
9992 val = val * 10 + *ptr - '0';
9993 }
9994 *value = val;
9995 return ptr;
9996 }
9997
mDNSValidKeepAliveRecord(AuthRecord * rr)9998 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
9999 {
10000 mDNSAddr laddr, raddr;
10001 mDNSEthAddr eth;
10002 mDNSIPPort lport, rport;
10003 mDNSu32 timeout, seq, ack;
10004 mDNSu16 win;
10005
10006 if (!mDNS_KeepaliveRecord(&rr->resrec))
10007 {
10008 return mDNSfalse;
10009 }
10010
10011 timeout = seq = ack = 0;
10012 win = 0;
10013 laddr = raddr = zeroAddr;
10014 lport = rport = zeroIPPort;
10015 eth = zeroEthAddr;
10016
10017 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win);
10018
10019 if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
10020 mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
10021 mDNSEthAddressIsZero(eth))
10022 {
10023 return mDNSfalse;
10024 }
10025
10026 return mDNStrue;
10027 }
10028
10029
mDNS_ExtractKeepaliveInfo(AuthRecord * ar,mDNSu32 * timeout,mDNSAddr * laddr,mDNSAddr * raddr,mDNSEthAddr * eth,mDNSu32 * seq,mDNSu32 * ack,mDNSIPPort * lport,mDNSIPPort * rport,mDNSu16 * win)10030 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
10031 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
10032 {
10033 if (ar->resrec.rrtype != kDNSType_NULL)
10034 return;
10035
10036 if (mDNS_KeepaliveRecord(&ar->resrec))
10037 {
10038 int len = ar->resrec.rdlength;
10039 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
10040 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
10041 mDNSu32 value = 0;
10042
10043 while (ptr < limit)
10044 {
10045 mDNSu8 param = *ptr;
10046 ptr += 2; // Skip the letter and the "="
10047 if (param == 'h')
10048 {
10049 laddr->type = mDNSAddrType_IPv4;
10050 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
10051 }
10052 else if (param == 'd')
10053 {
10054 raddr->type = mDNSAddrType_IPv4;
10055 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
10056 }
10057 else if (param == 'H')
10058 {
10059 laddr->type = mDNSAddrType_IPv6;
10060 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
10061 }
10062 else if (param == 'D')
10063 {
10064 raddr->type = mDNSAddrType_IPv6;
10065 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
10066 }
10067 else if (param == 'm')
10068 {
10069 ptr = GetValueForMACAddr(ptr, limit, eth);
10070 }
10071 else
10072 {
10073 ptr = GetValueForKeepalive(ptr, limit, &value);
10074 }
10075 if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10076
10077 // Extract everything in network order so that it is easy for sending a keepalive and also
10078 // for matching incoming TCP packets
10079 switch (param)
10080 {
10081 case 't':
10082 *timeout = value;
10083 //if (*timeout < 120) *timeout = 120;
10084 break;
10085 case 'h':
10086 case 'H':
10087 case 'd':
10088 case 'D':
10089 case 'm':
10090 case 'i':
10091 case 'c':
10092 break;
10093 case 'l':
10094 lport->NotAnInteger = swap16((mDNSu16)value);
10095 break;
10096 case 'r':
10097 rport->NotAnInteger = swap16((mDNSu16)value);
10098 break;
10099 case 's':
10100 *seq = swap32(value);
10101 break;
10102 case 'a':
10103 *ack = swap32(value);
10104 break;
10105 case 'w':
10106 *win = swap16((mDNSu16)value);
10107 break;
10108 default:
10109 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
10110 ptr = limit;
10111 break;
10112 }
10113 ptr++; // skip the space
10114 }
10115 }
10116 }
10117
10118 // 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
10119 // the clients need not retrieve this information from the auth record again.
mDNS_MatchKeepaliveInfo(mDNS * const m,const mDNSAddr * pladdr,const mDNSAddr * praddr,const mDNSIPPort plport,const mDNSIPPort prport,mDNSu32 * rseq,mDNSu32 * rack)10120 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
10121 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
10122 {
10123 AuthRecord *ar;
10124 mDNSAddr laddr, raddr;
10125 mDNSEthAddr eth;
10126 mDNSIPPort lport, rport;
10127 mDNSu32 timeout, seq, ack;
10128 mDNSu16 win;
10129
10130 for (ar = m->ResourceRecords; ar; ar=ar->next)
10131 {
10132 timeout = seq = ack = 0;
10133 win = 0;
10134 laddr = raddr = zeroAddr;
10135 lport = rport = zeroIPPort;
10136
10137 if (!ar->WakeUp.HMAC.l[0]) continue;
10138
10139 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win);
10140
10141 // Did we parse correctly ?
10142 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10143 {
10144 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
10145 continue;
10146 }
10147
10148 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10149 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
10150
10151 // Does it match the incoming TCP packet ?
10152 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
10153 {
10154 // returning in network order
10155 *rseq = seq;
10156 *rack = ack;
10157 return ar;
10158 }
10159 }
10160 return mDNSNULL;
10161 }
10162
mDNS_SendKeepalives(mDNS * const m)10163 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
10164 {
10165 AuthRecord *ar;
10166
10167 for (ar = m->ResourceRecords; ar; ar=ar->next)
10168 {
10169 mDNSu32 timeout, seq, ack;
10170 mDNSu16 win;
10171 mDNSAddr laddr, raddr;
10172 mDNSEthAddr eth;
10173 mDNSIPPort lport, rport;
10174
10175 timeout = seq = ack = 0;
10176 win = 0;
10177
10178 laddr = raddr = zeroAddr;
10179 lport = rport = zeroIPPort;
10180
10181 if (!ar->WakeUp.HMAC.l[0]) continue;
10182
10183 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win);
10184
10185 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10186 {
10187 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
10188 continue;
10189 }
10190 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10191
10192 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10193 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10194 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
10195 {
10196 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10197 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
10198 }
10199 if (m->NextScheduledKA - ar->KATimeExpire > 0)
10200 m->NextScheduledKA = ar->KATimeExpire;
10201 }
10202 }
10203
mDNS_SendKeepaliveACK(mDNS * const m,AuthRecord * ar)10204 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
10205 {
10206 mDNSu32 timeout, seq, ack, seqInc;
10207 mDNSu16 win;
10208 mDNSAddr laddr, raddr;
10209 mDNSEthAddr eth;
10210 mDNSIPPort lport, rport;
10211 mDNSu8 *ptr;
10212
10213 if (ar == mDNSNULL)
10214 {
10215 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10216 return;
10217 }
10218
10219 timeout = seq = ack = 0;
10220 win = 0;
10221
10222 laddr = raddr = zeroAddr;
10223 lport = rport = zeroIPPort;
10224
10225 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win);
10226
10227 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10228 {
10229 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
10230 return;
10231 }
10232
10233 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10234 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10235 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10236 // it's converted to host byte order before incrementing it by one.
10237 ptr = (mDNSu8 *)&seq;
10238 seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
10239 ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
10240 ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
10241 ptr[2] = (mDNSu8)((seqInc >> 8) & 0xFF);
10242 ptr[3] = (mDNSu8)((seqInc ) & 0xFF);
10243 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10244 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10245 }
10246
mDNSCoreReceiveUpdate(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * end,const mDNSAddr * srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,mDNSIPPort dstport,const mDNSInterfaceID InterfaceID)10247 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
10248 const DNSMessage *const msg, const mDNSu8 *end,
10249 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
10250 const mDNSInterfaceID InterfaceID)
10251 {
10252 int i;
10253 AuthRecord opt;
10254 mDNSu8 *p = m->omsg.data;
10255 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10256 mDNSu32 updatelease = 0;
10257 const mDNSu8 *ptr;
10258
10259 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10260 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10261 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
10262 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
10263 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
10264 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
10265 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
10266
10267 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
10268
10269 if (mDNS_PacketLoggingEnabled)
10270 DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10271
10272 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
10273 if (ptr)
10274 {
10275 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10276 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10277 {
10278 const rdataOPT *o;
10279 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10280 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10281 {
10282 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10283 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
10284 }
10285 }
10286 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10287 }
10288
10289 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10290
10291 if (!updatelease || !owner.HMAC.l[0])
10292 {
10293 static int msgs = 0;
10294 if (msgs < 100)
10295 {
10296 msgs++;
10297 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10298 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10299 }
10300 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10301 }
10302 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10303 {
10304 static int msgs = 0;
10305 if (msgs < 100)
10306 {
10307 msgs++;
10308 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10309 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10310 }
10311 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10312 }
10313 else
10314 {
10315 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10316
10317 if (updatelease > 24 * 60 * 60)
10318 updatelease = 24 * 60 * 60;
10319
10320 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10321 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10322
10323 ptr = LocateAuthorities(msg, end);
10324
10325 // Clear any stale TCP keepalive records that may exist
10326 ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10327 ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10328
10329 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10330 {
10331 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10332 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10333 {
10334 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10335 AuthRecord *ar = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10336 if (!ar)
10337 {
10338 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10339 break;
10340 }
10341 else
10342 {
10343 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10344 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10345 // All stale keepalive records have been flushed prior to this loop.
10346 if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10347 {
10348 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10349 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10350 }
10351 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10352 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10353 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10354 ar->resrec.rdata->MaxRDLength = RDLengthMem;
10355 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10356 ar->ForceMCast = mDNStrue;
10357 ar->WakeUp = owner;
10358 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10359 {
10360 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10361 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10362 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10363 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10364 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10365 }
10366 ar->TimeRcvd = m->timenow;
10367 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10368 if (m->NextScheduledSPS - ar->TimeExpire > 0)
10369 m->NextScheduledSPS = ar->TimeExpire;
10370 ar->KATimeExpire = 0;
10371 mDNS_Register_internal(m, ar);
10372
10373 m->ProxyRecords++;
10374 mDNS_UpdateAllowSleep(m);
10375 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10376 }
10377 }
10378 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10379 }
10380
10381 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10382 {
10383 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10384 ClearProxyRecords(m, &owner, m->DuplicateRecords);
10385 ClearProxyRecords(m, &owner, m->ResourceRecords);
10386 }
10387 else
10388 {
10389 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10390 opt.resrec.rrclass = NormalMaxDNSMessageData;
10391 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
10392 opt.resrec.rdestimate = sizeof(rdataOPT);
10393 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
10394 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10395 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10396 }
10397 }
10398
10399 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, mDNSNULL, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSfalse);
10400 mDNS_SendKeepalives(m);
10401 }
10402
mDNSGenerateOwnerOptForInterface(mDNS * const m,const mDNSInterfaceID InterfaceID,DNSMessage * msg)10403 mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg)
10404 {
10405 mDNSu8 *ptr = msg->data;
10406 mDNSu8 *end = mDNSNULL;
10407 mDNSu32 length = 0;
10408 AuthRecord opt;
10409 NetworkInterfaceInfo *intf;
10410
10411 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10412 opt.resrec.rrclass = NormalMaxDNSMessageData;
10413 opt.resrec.rdlength = sizeof(rdataOPT);
10414 opt.resrec.rdestimate = sizeof(rdataOPT);
10415
10416 intf = FirstInterfaceForID(m, InterfaceID);
10417 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
10418
10419 LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt));
10420 end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec);
10421 if (end != mDNSNULL)
10422 {
10423 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10424 SwapDNSHeaderBytes(msg);
10425 length = (mDNSu32)(end - msg->data);
10426 }
10427 else
10428 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10429
10430 return length;
10431 }
10432
10433 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10434 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10435 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10436 // Really, both should be unified and handled in one place.
mDNSCoreReceiveUpdateR(mDNS * const m,const DNSMessage * const msg,const mDNSu8 * end,const mDNSAddr * srcaddr,const mDNSInterfaceID InterfaceID)10437 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10438 {
10439 if (InterfaceID)
10440 {
10441 mDNSu32 pktlease = 0, spsupdates = 0;
10442 const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease);
10443 const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour
10444 if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10445
10446 if (m->CurrentRecord)
10447 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10448 m->CurrentRecord = m->ResourceRecords;
10449 while (m->CurrentRecord)
10450 {
10451 AuthRecord *const rr = m->CurrentRecord;
10452 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10453 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10454 {
10455 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10456 // Clear the updateid when we are done sending on all interfaces.
10457 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10458 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10459 bit_clr_opaque64(rr->updateIntID, scopeid);
10460 if (mDNSOpaque64IsZero(&rr->updateIntID))
10461 rr->updateid = zeroID;
10462 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10463 spsupdates++;
10464 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));
10465 if (rr->WakeUp.HMAC.l[0])
10466 {
10467 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10468 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10469 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10470 }
10471 }
10472 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10473 // new records could have been added to the end of the list as a result of that call.
10474 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10475 m->CurrentRecord = rr->next;
10476 }
10477 if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10478 {
10479 char *ifname;
10480 mDNSAddr spsaddr;
10481 DNSMessage optMsg;
10482 int length;
10483 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10484 ifname = InterfaceNameForID(m, InterfaceID);
10485 mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10486 mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10487
10488 // Store the Owner OPT record for this interface.
10489 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10490 InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags);
10491 length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg);
10492 if (length != 0)
10493 {
10494 length += sizeof(DNSMessageHeader);
10495 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length);
10496 }
10497 }
10498 }
10499 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10500 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10501 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10502 }
10503
MakeNegativeCacheRecord(mDNS * const m,CacheRecord * const cr,const domainname * const name,const mDNSu32 namehash,const mDNSu16 rrtype,const mDNSu16 rrclass,mDNSu32 ttl_seconds,mDNSInterfaceID InterfaceID,mdns_dns_service_t service)10504 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr, const domainname *const name,
10505 const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID,
10506 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10507 mdns_dns_service_t service)
10508 #else
10509 DNSServer *dnsserver)
10510 #endif
10511 {
10512 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10513 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10514
10515 // Create empty resource record
10516 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
10517 cr->resrec.InterfaceID = InterfaceID;
10518 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10519 mdns_replace(&cr->resrec.dnsservice, service);
10520 #else
10521 cr->resrec.rDNSServer = dnsserver;
10522 #endif
10523 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10524 cr->resrec.rrtype = rrtype;
10525 cr->resrec.rrclass = rrclass;
10526 cr->resrec.rroriginalttl = ttl_seconds;
10527 cr->resrec.rdlength = 0;
10528 cr->resrec.rdestimate = 0;
10529 cr->resrec.namehash = namehash;
10530 cr->resrec.rdatahash = 0;
10531 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10532 cr->resrec.rdata->MaxRDLength = 0;
10533
10534 cr->NextInKAList = mDNSNULL;
10535 cr->TimeRcvd = m->timenow;
10536 cr->DelayDelivery = 0;
10537 cr->NextRequiredQuery = m->timenow;
10538 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
10539 cr->LastCachedAnswerTime= 0;
10540 #endif
10541 cr->CRActiveQuestion = mDNSNULL;
10542 cr->UnansweredQueries = 0;
10543 cr->LastUnansweredTime = 0;
10544 cr->NextInCFList = mDNSNULL;
10545 cr->soa = mDNSNULL;
10546 // Initialize to the basic one and the caller can set it to more
10547 // specific based on the response if any
10548 cr->responseFlags = ResponseFlags;
10549 }
10550
10551 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
mDNSCoreReceiveForQuerier(mDNS * const m,DNSMessage * const msg,const mDNSu8 * const end,mdns_querier_t querier,mdns_dns_service_t dnsservice)10552 mDNSexport void mDNSCoreReceiveForQuerier(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10553 mdns_querier_t querier, mdns_dns_service_t dnsservice)
10554 {
10555 SwapDNSHeaderBytes(msg);
10556 mDNS_Lock(m);
10557 mDNSCoreReceiveResponse(m, msg, end, mDNSNULL, zeroIPPort, mDNSNULL, zeroIPPort, querier, dnsservice, mDNSNULL);
10558 mDNS_Unlock(m);
10559 }
10560 #endif
10561
mDNSCoreReceive(mDNS * const m,DNSMessage * const msg,const mDNSu8 * const end,const mDNSAddr * const srcaddr,const mDNSIPPort srcport,const mDNSAddr * dstaddr,const mDNSIPPort dstport,const mDNSInterfaceID InterfaceID)10562 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10563 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10564 const mDNSInterfaceID InterfaceID)
10565 {
10566 mDNSInterfaceID ifid = InterfaceID;
10567 const mDNSu8 *const pkt = (mDNSu8 *)msg;
10568 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
10569 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10570 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
10571 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10572 mDNSu8 QR_OP;
10573 mDNSu8 *ptr = mDNSNULL;
10574 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10575 if (TLS) dstaddr = mDNSNULL;
10576
10577 #ifndef UNICAST_DISABLED
10578 if (mDNSSameAddress(srcaddr, &m->Router))
10579 {
10580 #ifdef _LEGACY_NAT_TRAVERSAL_
10581 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10582 {
10583 mDNS_Lock(m);
10584 LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10585 mDNS_Unlock(m);
10586 return;
10587 }
10588 #endif
10589 if (mDNSSameIPPort(srcport, NATPMPPort))
10590 {
10591 mDNS_Lock(m);
10592 uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10593 mDNS_Unlock(m);
10594 return;
10595 }
10596 }
10597 #ifdef _LEGACY_NAT_TRAVERSAL_
10598 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10599 #endif
10600
10601 #endif
10602 if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader))
10603 {
10604 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt));
10605 return;
10606 }
10607 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10608 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10609 ptr = (mDNSu8 *)&msg->h.numQuestions;
10610 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10611 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10612 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10613 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10614
10615 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10616
10617 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10618 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10619 if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10620
10621 mDNS_Lock(m);
10622 m->PktNum++;
10623 if (mDNSOpaque16IsZero(msg->h.id))
10624 {
10625 m->MPktNum++;
10626 #if APPLE_OSX_mDNSResponder
10627 // Track the number of multicast packets received from a source outside our subnet.
10628 // Check the destination address to avoid accounting for spurious packets that
10629 // comes in with message id zero.
10630 if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr &&
10631 mDNSAddressIsAllDNSLinkGroup(dstaddr))
10632 {
10633 m->RemoteSubnet++;
10634 }
10635 #endif // #if APPLE_OSX_mDNSResponder
10636 }
10637
10638 #ifndef UNICAST_DISABLED
10639 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10640 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10641 {
10642 ifid = mDNSInterface_Any;
10643 if (mDNS_PacketLoggingEnabled)
10644 DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10645 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10646 // Note: mDNSCore also needs to get access to received unicast responses
10647 }
10648 #endif
10649 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10650 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10651 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, mDNSNULL, mDNSNULL, ifid);
10652 #else
10653 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10654 #endif
10655 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10656 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID);
10657 else
10658 {
10659 if (mDNS_LoggingEnabled)
10660 {
10661 static int msgCount = 0;
10662 if (msgCount < 1000) {
10663 int i = 0;
10664 msgCount++;
10665 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10666 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID);
10667 while (i < (int)(end - pkt))
10668 {
10669 char buffer[128];
10670 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10671 do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15);
10672 LogInfo("%s", buffer);
10673 }
10674 }
10675 }
10676 }
10677 // Packet reception often causes a change to the task list:
10678 // 1. Inbound queries can cause us to need to send responses
10679 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10680 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10681 // 4. Response packets that answer questions may cause our client to issue new questions
10682 mDNS_Unlock(m);
10683 }
10684
10685 // ***************************************************************************
10686 #if COMPILER_LIKES_PRAGMA_MARK
10687 #pragma mark -
10688 #pragma mark - Searcher Functions
10689 #endif
10690
10691 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10692 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10693 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10694 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10695 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10696 //
10697 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10698 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10699 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10700 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10701 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10702 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10703 // breaks this design principle.
10704 //
10705
10706 // If IsLLQ(Q) is true, it means the question is both:
10707 // (a) long-lived and
10708 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10709 // for multicast questions, we don't want to treat LongLived as anything special
10710 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10711 #define AWDLIsIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10712 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10713
FindDuplicateQuestion(const mDNS * const m,const DNSQuestion * const question)10714 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10715 {
10716 DNSQuestion *q;
10717 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10718 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10719 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10720 // further in the list.
10721 for (q = m->Questions; q && (q != question); q = q->next)
10722 {
10723 if (!SameQuestionKind(q, question)) continue;
10724 if (q->qnamehash != question->qnamehash) continue;
10725 if (q->InterfaceID != question->InterfaceID) continue;
10726 if (q->qtype != question->qtype) continue;
10727 if (q->qclass != question->qclass) continue;
10728 if (IsLLQ(q) != IsLLQ(question)) continue;
10729 if (q->AuthInfo && !question->AuthInfo) continue;
10730 if (!q->Suppressed != !question->Suppressed) continue;
10731 if (q->BrowseThreshold != question->BrowseThreshold) continue;
10732 if (AWDLIsIncluded(q) != AWDLIsIncluded(question)) continue;
10733 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10734 if (q->dnsservice != question->dnsservice) continue;
10735 #endif
10736 if (!SameDomainName(&q->qname, &question->qname)) continue;
10737 return(q);
10738 }
10739 return(mDNSNULL);
10740 }
10741
10742 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
UpdateQuestionDuplicates(mDNS * const m,DNSQuestion * const question)10743 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10744 {
10745 DNSQuestion *q;
10746 DNSQuestion *first = mDNSNULL;
10747
10748 // This is referring to some other question as duplicate. No other question can refer to this
10749 // question as a duplicate.
10750 if (question->DuplicateOf)
10751 {
10752 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10753 "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME " (" PUB_S ") duplicate of %p " PRI_DM_NAME " (" PUB_S ")",
10754 question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID),
10755 question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), question->DuplicateOf,
10756 DM_NAME_PARAM(&question->DuplicateOf->qname), DNSTypeName(question->DuplicateOf->qtype));
10757 return;
10758 }
10759
10760 for (q = m->Questions; q; q=q->next) // Scan our list of questions
10761 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
10762 {
10763 q->DuplicateOf = first;
10764 if (!first)
10765 {
10766 first = q;
10767 // If q used to be a duplicate, but now is not,
10768 // then inherit the state from the question that's going away
10769 q->LastQTime = question->LastQTime;
10770 q->ThisQInterval = question->ThisQInterval;
10771 q->ExpectUnicastResp = question->ExpectUnicastResp;
10772 q->LastAnswerPktNum = question->LastAnswerPktNum;
10773 q->RecentAnswerPkts = question->RecentAnswerPkts;
10774 q->RequestUnicast = question->RequestUnicast;
10775 q->LastQTxTime = question->LastQTxTime;
10776 q->CNAMEReferrals = question->CNAMEReferrals;
10777 q->nta = question->nta;
10778 q->servAddr = question->servAddr;
10779 q->servPort = question->servPort;
10780 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10781 mdns_replace(&q->dnsservice, question->dnsservice);
10782 mdns_forget(&question->dnsservice);
10783 mdns_querier_forget(&q->querier);
10784 mdns_replace(&q->querier, question->querier);
10785 mdns_forget(&question->querier);
10786 #else
10787 q->qDNSServer = question->qDNSServer;
10788 q->validDNSServers = question->validDNSServers;
10789 q->unansweredQueries = question->unansweredQueries;
10790 q->noServerResponse = question->noServerResponse;
10791 q->triedAllServersOnce = question->triedAllServersOnce;
10792 #endif
10793
10794 q->TargetQID = question->TargetQID;
10795 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10796 q->LocalSocket = question->LocalSocket;
10797 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10798 #endif
10799
10800 q->state = question->state;
10801 // q->tcp = question->tcp;
10802 q->ReqLease = question->ReqLease;
10803 q->expire = question->expire;
10804 q->ntries = question->ntries;
10805 q->id = question->id;
10806
10807 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10808 question->LocalSocket = mDNSNULL;
10809 #endif
10810 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
10811 // question->tcp = mDNSNULL;
10812
10813 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10814 if (q->LocalSocket)
10815 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10816 #endif
10817 if (q->nta)
10818 {
10819 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10820 q->nta->ZoneDataContext = q;
10821 }
10822
10823 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10824 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10825
10826 if (question->state == LLQ_Established)
10827 {
10828 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10829 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10830 }
10831
10832 SetNextQueryTime(m,q);
10833 }
10834 }
10835 }
10836
mDNS_AddMcastResolver(mDNS * const m,const domainname * d,const mDNSInterfaceID interface,mDNSu32 timeout)10837 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10838 {
10839 McastResolver **p = &m->McastResolvers;
10840 McastResolver *tmp = mDNSNULL;
10841
10842 if (!d) d = (const domainname *)"";
10843
10844 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10845 "mDNS_AddMcastResolver: Adding " PUB_DM_NAME ", InterfaceID %p, timeout %u", DM_NAME_PARAM(d), interface, timeout);
10846
10847 mDNS_CheckLock(m);
10848
10849 while (*p) // Check if we already have this {interface, domain} tuple registered
10850 {
10851 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10852 {
10853 if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10854 (*p)->flags &= ~McastResolver_FlagDelete;
10855 tmp = *p;
10856 *p = tmp->next;
10857 tmp->next = mDNSNULL;
10858 }
10859 else
10860 p=&(*p)->next;
10861 }
10862
10863 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10864 else
10865 {
10866 // allocate, add to list
10867 *p = (McastResolver *) mDNSPlatformMemAllocateClear(sizeof(**p));
10868 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10869 else
10870 {
10871 (*p)->interface = interface;
10872 (*p)->flags = McastResolver_FlagNew;
10873 (*p)->timeout = timeout;
10874 AssignDomainName(&(*p)->domain, d);
10875 (*p)->next = mDNSNULL;
10876 }
10877 }
10878 return(*p);
10879 }
10880
10881 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
PenaltyTimeForServer(mDNS * m,DNSServer * server)10882 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10883 {
10884 mDNSs32 ptime = 0;
10885 if (server->penaltyTime != 0)
10886 {
10887 ptime = server->penaltyTime - m->timenow;
10888 if (ptime < 0)
10889 {
10890 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10891 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10892 // here
10893 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10894 ptime, server->penaltyTime, m->timenow);
10895 server->penaltyTime = 0;
10896 ptime = 0;
10897 }
10898 }
10899 return ptime;
10900 }
10901 #endif
10902
10903 //Checks to see whether the newname is a better match for the name, given the best one we have
10904 //seen so far (given in bestcount).
10905 //Returns -1 if the newname is not a better match
10906 //Returns 0 if the newname is the same as the old match
10907 //Returns 1 if the newname is a better match
BetterMatchForName(const domainname * name,int namecount,const domainname * newname,int newcount,int bestcount)10908 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10909 int bestcount)
10910 {
10911 // If the name contains fewer labels than the new server's domain or the new name
10912 // contains fewer labels than the current best, then it can't possibly be a better match
10913 if (namecount < newcount || newcount < bestcount) return -1;
10914
10915 // If there is no match, return -1 and the caller will skip this newname for
10916 // selection
10917 //
10918 // If we find a match and the number of labels is the same as bestcount, then
10919 // we return 0 so that the caller can do additional logic to pick one of
10920 // the best based on some other factors e.g., penaltyTime
10921 //
10922 // If we find a match and the number of labels is more than bestcount, then we
10923 // return 1 so that the caller can pick this over the old one.
10924 //
10925 // Note: newcount can either be equal or greater than bestcount beause of the
10926 // check above.
10927
10928 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10929 return bestcount == newcount ? 0 : 1;
10930 else
10931 return -1;
10932 }
10933
10934 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10935 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10936 // names. In that case, we give a default timeout of 5 seconds
10937 #define DEFAULT_MCAST_TIMEOUT 5
GetTimeoutForMcastQuestion(mDNS * m,DNSQuestion * question)10938 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10939 {
10940 McastResolver *curmatch = mDNSNULL;
10941 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10942 McastResolver *curr;
10943 int bettermatch, currcount;
10944 for (curr = m->McastResolvers; curr; curr = curr->next)
10945 {
10946 currcount = CountLabels(&curr->domain);
10947 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10948 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10949 // the timeout value from the first one
10950 if (bettermatch == 1)
10951 {
10952 curmatch = curr;
10953 bestmatchlen = currcount;
10954 }
10955 }
10956 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10957 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10958 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10959 }
10960
10961 // Returns true if it is a Domain Enumeration Query
DomainEnumQuery(const domainname * qname)10962 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10963 {
10964 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10965 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10966 const domainname *d = qname;
10967 const mDNSu8 *label;
10968 int i = 0;
10969
10970 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10971 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10972
10973 label = (const mDNSu8 *)d;
10974 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10975 {
10976 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10977 i++;
10978 }
10979 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
10980 {
10981 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
10982 return mDNSfalse;
10983 }
10984 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
10985
10986 // CountLabels already verified the number of labels
10987 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
10988 label = (const mDNSu8 *)d;
10989 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
10990 {
10991 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
10992 return(mDNSfalse);
10993 }
10994 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
10995
10996 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
10997 label = (const mDNSu8 *)d;
10998 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
10999 {
11000 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
11001 return(mDNSfalse);
11002 }
11003 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
11004
11005 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
11006
11007 return mDNStrue;
11008 }
11009
11010 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11011 // Note: InterfaceID is the InterfaceID of the question
DNSServerMatch(DNSServer * d,mDNSInterfaceID InterfaceID,mDNSs32 ServiceID)11012 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11013 {
11014 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11015 // with scopeType set to kScopeNone)
11016 //
11017 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11018 // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11019 //
11020 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11021 // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11022 //
11023 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11024 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11025 //
11026 // If the first condition fails, following are the possible cases (the notes below are using
11027 // InterfaceID for discussion and the same holds good for ServiceID):
11028 //
11029 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11030 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11031 //
11032 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11033 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11034 // would fail in this case.
11035 //
11036 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11037 // should match (Refer to (2) above).
11038
11039 if (((d->scopeType == kScopeNone) && (!InterfaceID && ServiceID == -1)) ||
11040 ((d->scopeType == kScopeInterfaceID) && d->interface == InterfaceID) ||
11041 ((d->scopeType == kScopeServiceID) && d->serviceID == ServiceID))
11042 {
11043 return mDNStrue;
11044 }
11045 return mDNSfalse;
11046 }
11047
11048 // Sets all the Valid DNS servers for a question
SetValidDNSServers(mDNS * m,DNSQuestion * question)11049 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
11050 {
11051 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
11052 DNSServer *curr;
11053 int bettermatch, currcount;
11054 int index = 0;
11055 mDNSu32 timeout = 0;
11056 mDNSBool DEQuery;
11057
11058 question->validDNSServers = zeroOpaque128;
11059 DEQuery = DomainEnumQuery(&question->qname);
11060 for (curr = m->DNSServers; curr; curr = curr->next)
11061 {
11062 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scopeType);
11063 // skip servers that will soon be deleted
11064 if (curr->flags & DNSServerFlag_Delete)
11065 {
11066 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11067 continue;
11068 }
11069
11070 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11071 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11072 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11073 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11074 // match the scoped entries by mistake.
11075 //
11076 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11077
11078 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11079 if (((curr->scopeType == kScopeInterfaceID) && (curr->interface == mDNSInterface_Any)) ||
11080 ((curr->scopeType == kScopeServiceID) && (curr->serviceID <= 0)))
11081 {
11082 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11083 (int)curr->scopeType, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
11084 continue;
11085 }
11086
11087 currcount = CountLabels(&curr->domain);
11088 if ((!DEQuery || !curr->isCell) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
11089 {
11090 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11091
11092 // If we found a better match (bettermatch == 1) then clear all the bits
11093 // corresponding to the old DNSServers that we have may set before and start fresh.
11094 // If we find an equal match, then include that DNSServer also by setting the corresponding
11095 // bit
11096 if ((bettermatch == 1) || (bettermatch == 0))
11097 {
11098 bestmatchlen = currcount;
11099 if (bettermatch)
11100 {
11101 debugf("SetValidDNSServers: Resetting all the bits");
11102 question->validDNSServers = zeroOpaque128;
11103 timeout = 0;
11104 }
11105 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11106 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scopeType, index, curr->timeout,
11107 curr->interface);
11108 timeout += curr->timeout;
11109 if (DEQuery)
11110 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->isCell);
11111 bit_set_opaque128(question->validDNSServers, index);
11112 }
11113 }
11114 index++;
11115 }
11116 question->noServerResponse = 0;
11117
11118 debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11119 question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
11120 // If there are no matching resolvers, then use the default timeout value.
11121 return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
11122 }
11123
11124 // Get the Best server that matches a name. If you find penalized servers, look for the one
11125 // that will come out of the penalty box soon
GetBestServer(mDNS * m,const domainname * name,mDNSInterfaceID InterfaceID,mDNSs32 ServiceID,mDNSOpaque128 validBits,int * selected,mDNSBool nameMatch)11126 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits,
11127 int *selected, mDNSBool nameMatch)
11128 {
11129 DNSServer *curmatch = mDNSNULL;
11130 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
11131 DNSServer *curr;
11132 mDNSs32 bestPenaltyTime, currPenaltyTime;
11133 int bettermatch, currcount;
11134 int index = 0;
11135 int currindex = -1;
11136
11137 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
11138 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
11139 for (curr = m->DNSServers; curr; curr = curr->next)
11140 {
11141 // skip servers that will soon be deleted
11142 if (curr->flags & DNSServerFlag_Delete)
11143 {
11144 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11145 continue;
11146 }
11147
11148 // Check if this is a valid DNSServer
11149 if (!bit_get_opaque64(validBits, index))
11150 {
11151 debugf("GetBestServer: continuing for index %d", index);
11152 index++;
11153 continue;
11154 }
11155
11156 currcount = CountLabels(&curr->domain);
11157 currPenaltyTime = PenaltyTimeForServer(m, curr);
11158
11159 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11160 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
11161
11162 // If there are multiple best servers for a given question, we will pick the first one
11163 // if none of them are penalized. If some of them are penalized in that list, we pick
11164 // the least penalized one. BetterMatchForName walks through all best matches and
11165 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11166 // in the list when there are no penalized servers and least one among them
11167 // when there are some penalized servers.
11168
11169 if (DNSServerMatch(curr, InterfaceID, ServiceID))
11170 {
11171
11172 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11173 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11174 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11175 // part and still do some redundant steps e.g., InterfaceID match
11176
11177 if (nameMatch)
11178 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
11179 else
11180 bettermatch = 0;
11181
11182 // If we found a better match (bettermatch == 1) then we don't need to
11183 // compare penalty times. But if we found an equal match, then we compare
11184 // the penalty times to pick a better match
11185
11186 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
11187 {
11188 currindex = index;
11189 curmatch = curr;
11190 bestmatchlen = currcount;
11191 bestPenaltyTime = currPenaltyTime;
11192 }
11193 }
11194 index++;
11195 }
11196 if (selected) *selected = currindex;
11197 return curmatch;
11198 }
11199
11200 // Look up a DNS Server, matching by name and InterfaceID
GetServerForName(mDNS * m,const domainname * name,mDNSInterfaceID InterfaceID,mDNSs32 ServiceID)11201 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11202 {
11203 DNSServer *curmatch = mDNSNULL;
11204 char *ifname = mDNSNULL; // for logging purposes only
11205 mDNSOpaque128 allValid;
11206
11207 if (InterfaceID == mDNSInterface_LocalOnly)
11208 InterfaceID = mDNSNULL;
11209
11210 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
11211
11212 // By passing in all ones, we make sure that every DNS server is considered
11213 allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF;
11214
11215 curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
11216
11217 if (curmatch != mDNSNULL)
11218 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr,
11219 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11220 InterfaceID, name);
11221 else
11222 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name);
11223
11224 return(curmatch);
11225 }
11226
11227 // Look up a DNS Server for a question within its valid DNSServer bits
GetServerForQuestion(mDNS * m,DNSQuestion * question)11228 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
11229 {
11230 DNSServer *curmatch = mDNSNULL;
11231 char *ifname = mDNSNULL; // for logging purposes only
11232 mDNSInterfaceID InterfaceID = question->InterfaceID;
11233 const domainname *name = &question->qname;
11234 int currindex;
11235
11236 if (InterfaceID == mDNSInterface_LocalOnly)
11237 InterfaceID = mDNSNULL;
11238
11239 if (InterfaceID)
11240 ifname = InterfaceNameForID(m, InterfaceID);
11241
11242 if (!mDNSOpaque128IsZero(&question->validDNSServers))
11243 {
11244 curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
11245 if (currindex != -1)
11246 bit_clr_opaque128(question->validDNSServers, currindex);
11247 }
11248
11249 if (curmatch != mDNSNULL)
11250 {
11251 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11252 "[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 ")",
11253 question->request_id, mDNSVal16(question->TargetQID), question, curmatch, &curmatch->addr,
11254 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0),
11255 ifname ? ifname : "None", InterfaceID, question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11256 }
11257 else
11258 {
11259 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11260 "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11261 question->request_id, mDNSVal16(question->TargetQID), question, ifname ? ifname : "None", InterfaceID,
11262 question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11263 }
11264
11265 return(curmatch);
11266 }
11267 #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11268
11269 // Called in normal client context (lock not held)
LLQNATCallback(mDNS * m,NATTraversalInfo * n)11270 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
11271 {
11272 DNSQuestion *q;
11273 mDNS_Lock(m);
11274 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
11275 n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
11276 for (q = m->Questions; q; q=q->next)
11277 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
11278 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
11279 mDNS_Unlock(m);
11280 }
11281
11282 // This function takes the DNSServer as a separate argument because sometimes the
11283 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11284 // status before switching to it.
11285 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
ShouldSuppressUnicastQuery(const DNSQuestion * const q,const mdns_dns_service_t dnsservice)11286 mDNSexport mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const mdns_dns_service_t dnsservice)
11287 #else
11288 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const DNSServer *const server)
11289 #endif
11290 {
11291 mDNSBool suppress = mDNSfalse;
11292 const char *reason = mDNSNULL;
11293
11294 if (q->BlockedByPolicy)
11295 {
11296 suppress = mDNStrue;
11297 reason = " (blocked by policy)";
11298 }
11299 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11300 else if (!dnsservice)
11301 {
11302 if (!q->IsUnicastDotLocal)
11303 {
11304 suppress = mDNStrue;
11305 reason = " (no DNS service)";
11306 }
11307 }
11308 #else
11309 else if (!server)
11310 {
11311 if (!q->IsUnicastDotLocal)
11312 {
11313 suppress = mDNStrue;
11314 reason = " (no DNS server)";
11315 }
11316 }
11317 #endif
11318 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11319 else if ((q->flags & kDNSServiceFlagsDenyCellular) && mdns_dns_service_interface_is_cellular(dnsservice))
11320 #else
11321 else if ((q->flags & kDNSServiceFlagsDenyCellular) && server->isCell)
11322 #endif
11323 {
11324 suppress = mDNStrue;
11325 reason = " (interface is cellular)";
11326 }
11327 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11328 else if ((q->flags & kDNSServiceFlagsDenyExpensive) && mdns_dns_service_interface_is_expensive(dnsservice))
11329 #else
11330 else if ((q->flags & kDNSServiceFlagsDenyExpensive) && server->isExpensive)
11331 #endif
11332 {
11333 suppress = mDNStrue;
11334 reason = " (interface is expensive)";
11335 }
11336 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11337 else if ((q->flags & kDNSServiceFlagsDenyConstrained) && mdns_dns_service_interface_is_constrained(dnsservice))
11338 #else
11339 else if ((q->flags & kDNSServiceFlagsDenyConstrained) && server->isConstrained)
11340 #endif
11341 {
11342 suppress = mDNStrue;
11343 reason = " (interface is constrained)";
11344 }
11345 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11346 else if (q->SuppressUnusable && !DNS64IsQueryingARecord(q->dns64.state))
11347 #else
11348 else if (q->SuppressUnusable)
11349 #endif
11350 {
11351 if (q->qtype == kDNSType_A)
11352 {
11353 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11354 if (!mdns_dns_service_a_queries_advised(dnsservice))
11355 #else
11356 if (!server->usableA)
11357 #endif
11358 {
11359 suppress = mDNStrue;
11360 reason = " (A records are unusable)";
11361 }
11362 // If the server's configuration allows A record queries, suppress this query if
11363 // 1. the interface associated with the server is CLAT46; and
11364 // 2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11365 // See <rdar://problem/42672030> for more info.
11366 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11367 else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && mdns_dns_service_interface_is_clat46(dnsservice))
11368 #else
11369 else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && server->isCLAT46)
11370 #endif
11371 {
11372 suppress = mDNStrue;
11373 reason = " (CLAT46 A records are unusable)";
11374 }
11375 }
11376 else if (q->qtype == kDNSType_AAAA)
11377 {
11378 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11379 if (!mdns_dns_service_aaaa_queries_advised(dnsservice))
11380 #else
11381 if (!server->usableAAAA)
11382 #endif
11383 {
11384 suppress = mDNStrue;
11385 reason = " (AAAA records are unusable)";
11386 }
11387 }
11388 }
11389 if (suppress)
11390 {
11391 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11392 "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME " " PUB_S PUB_S,
11393 mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), reason ? reason : "");
11394 }
11395 return suppress;
11396 }
11397
ShouldSuppressQuery(DNSQuestion * q)11398 mDNSlocal mDNSBool ShouldSuppressQuery(DNSQuestion *q)
11399 {
11400 // Multicast queries are never suppressed.
11401 if (mDNSOpaque16IsZero(q->TargetQID))
11402 {
11403 return mDNSfalse;
11404 }
11405 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11406 return (ShouldSuppressUnicastQuery(q, q->dnsservice));
11407 #else
11408 return (ShouldSuppressUnicastQuery(q, q->qDNSServer));
11409 #endif
11410 }
11411
CacheRecordRmvEventsForCurrentQuestion(mDNS * const m,DNSQuestion * q)11412 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11413 {
11414 CacheRecord *cr;
11415 CacheGroup *cg;
11416
11417 cg = CacheGroupForName(m, q->qnamehash, &q->qname);
11418 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
11419 {
11420 // Don't deliver RMV events for negative records
11421 if (cr->resrec.RecordType == kDNSRecordTypePacketNegative)
11422 {
11423 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11424 "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S " Suppressing RMV events for question %p " PRI_DM_NAME " (" PUB_S "), CRActiveQuestion %p, CurrentAnswers %d",
11425 q->request_id, mDNSVal16(q->TargetQID), CRDisplayString(m, cr), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), cr->CRActiveQuestion, q->CurrentAnswers);
11426 continue;
11427 }
11428
11429 if (SameNameCacheRecordAnswersQuestion(cr, q))
11430 {
11431 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11432 q->qname.c, CRDisplayString(m, cr), q->LOAddressAnswers);
11433
11434 q->CurrentAnswers--;
11435 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11436 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11437 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
11438 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
11439 }
11440 }
11441 }
11442
IsQuestionNew(mDNS * const m,DNSQuestion * question)11443 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11444 {
11445 DNSQuestion *q;
11446 for (q = m->NewQuestions; q; q = q->next)
11447 if (q == question) return mDNStrue;
11448 return mDNSfalse;
11449 }
11450
11451 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
LocalRecordRmvEventsForQuestion(mDNS * const m,DNSQuestion * q)11452 mDNSexport mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11453 #else
11454 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11455 #endif
11456 {
11457 AuthRecord *rr;
11458 AuthGroup *ag;
11459
11460 if (m->CurrentQuestion)
11461 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11462 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11463
11464 if (IsQuestionNew(m, q))
11465 {
11466 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11467 return mDNStrue;
11468 }
11469 m->CurrentQuestion = q;
11470 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
11471 if (ag)
11472 {
11473 for (rr = ag->members; rr; rr=rr->next)
11474 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11475 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11476 {
11477 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11478 ARDisplayString(m, rr));
11479 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11480 {
11481 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11482 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11483 q->CurrentAnswers, q->LOAddressAnswers);
11484 continue;
11485 }
11486 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
11487 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11488 }
11489 }
11490 m->CurrentQuestion = mDNSNULL;
11491 return mDNStrue;
11492 }
11493
11494 // Returns false if the question got deleted while delivering the RMV events
11495 // The caller should handle the case
CacheRecordRmvEventsForQuestion(mDNS * const m,DNSQuestion * q)11496 mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11497 {
11498 if (m->CurrentQuestion)
11499 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11500 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11501
11502 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11503 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11504 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11505 {
11506 m->CurrentQuestion = q;
11507 CacheRecordRmvEventsForCurrentQuestion(m, q);
11508 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11509 m->CurrentQuestion = mDNSNULL;
11510 }
11511 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11512 return mDNStrue;
11513 }
11514
SuppressStatusChanged(mDNS * const m,DNSQuestion * q,DNSQuestion ** restart)11515 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11516 {
11517 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11518 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11519 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11520 if (q->Suppressed)
11521 {
11522 q->Suppressed = mDNSfalse;
11523 if (!CacheRecordRmvEventsForQuestion(m, q))
11524 {
11525 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11526 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11527 q->request_id, mDNSVal16(q->TargetQID));
11528 return;
11529 }
11530 q->Suppressed = mDNStrue;
11531 }
11532
11533 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11534 // and Suppressed status does not mean anything for these questions. As we are going to stop the
11535 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11536 // the restart will not be a duplicate ADD
11537 if (!LocalRecordRmvEventsForQuestion(m, q))
11538 {
11539 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11540 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11541 q->request_id, mDNSVal16(q->TargetQID));
11542 return;
11543 }
11544
11545 // There are two cases here.
11546 //
11547 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11548 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11549 // because when we get the response, if we had entries in the cache already, it will not answer
11550 // this question if the cache entry did not change. Hence, we need to restart
11551 // the query so that it can be answered from the cache.
11552 //
11553 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11554 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11555 // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11556 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11557 // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11558 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11559 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11560 // This affects both efficiency and also the current design where there is only one active question
11561 // pointed to from a cache entry.
11562 //
11563 // We restart queries in a two step process by first calling stop and build a temporary list which we
11564 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11565 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11566 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11567 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11568 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11569 //
11570 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11571
11572 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11573 "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME " (" PUB_S ")",
11574 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
11575 mDNS_StopQuery_internal(m, q);
11576 q->next = *restart;
11577 *restart = q;
11578 }
11579
11580 // The caller should hold the lock
CheckSuppressUnusableQuestions(mDNS * const m)11581 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11582 {
11583 DNSQuestion *q;
11584 DNSQuestion *restart = mDNSNULL;
11585
11586 // We look through all questions including new questions. During network change events,
11587 // we potentially restart questions here in this function that ends up as new questions,
11588 // which may be suppressed at this instance. Before it is handled we get another network
11589 // event that changes the status e.g., address becomes available. If we did not process
11590 // new questions, we would never change its Suppressed status.
11591 //
11592 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11593 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11594 // *any* other question which could be the next one that we may process here. RestartQuestion
11595 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11596 // if the "next" question is stopped while the CurrentQuestion is stopped
11597 if (m->RestartQuestion)
11598 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11599 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11600 m->RestartQuestion = m->Questions;
11601 while (m->RestartQuestion)
11602 {
11603 q = m->RestartQuestion;
11604 m->RestartQuestion = q->next;
11605 if (q->SuppressUnusable)
11606 {
11607 const mDNSBool old = q->Suppressed;
11608 q->Suppressed = ShouldSuppressQuery(q);
11609 if (q->Suppressed != old)
11610 {
11611 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11612 // followed by a negative cache response. Temporarily turn off suppression so that
11613 // AnswerCurrentQuestionWithResourceRecord can answer the question
11614 SuppressStatusChanged(m, q, &restart);
11615 }
11616 }
11617 }
11618 while (restart)
11619 {
11620 q = restart;
11621 restart = restart->next;
11622 q->next = mDNSNULL;
11623 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11624 mDNS_StartQuery_internal(m, q);
11625 }
11626 }
11627
11628 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
RestartUnicastQuestions(mDNS * const m)11629 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11630 {
11631 DNSQuestion *q;
11632 DNSQuestion *restartList = mDNSNULL;
11633
11634 if (m->RestartQuestion)
11635 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11636 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11637 m->RestartQuestion = m->Questions;
11638 while (m->RestartQuestion)
11639 {
11640 q = m->RestartQuestion;
11641 m->RestartQuestion = q->next;
11642 if (q->Restart)
11643 {
11644 if (mDNSOpaque16IsZero(q->TargetQID))
11645 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11646
11647 q->Restart = mDNSfalse;
11648 SuppressStatusChanged(m, q, &restartList);
11649 }
11650 }
11651 while ((q = restartList) != mDNSNULL)
11652 {
11653 restartList = q->next;
11654 q->next = mDNSNULL;
11655 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11656 "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME " (" PUB_S ")",
11657 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
11658 mDNS_StartQuery_internal(m, q);
11659 }
11660 }
11661 #endif
11662
11663 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11664 // DNS Question that are already set by the client before calling mDNS_StartQuery()
ValidateParameters(mDNS * const m,DNSQuestion * const question)11665 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11666 {
11667 if (!ValidateDomainName(&question->qname))
11668 {
11669 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11670 return(mStatus_Invalid);
11671 }
11672
11673 // If this question is referencing a specific interface, verify it exists
11674 if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID))
11675 {
11676 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11677 if (!intf)
11678 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11679 IIDPrintable(question->InterfaceID), question->qname.c, DNSTypeName(question->qtype));
11680 }
11681
11682 return(mStatus_NoError);
11683 }
11684
11685 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11686 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
InitDNSConfig(mDNS * const m,DNSQuestion * const question)11687 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11688 {
11689 // First reset all DNS Configuration
11690 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11691 mdns_forget(&question->dnsservice);
11692 #else
11693 question->qDNSServer = mDNSNULL;
11694 question->validDNSServers = zeroOpaque128;
11695 question->triedAllServersOnce = mDNSfalse;
11696 question->noServerResponse = mDNSfalse;
11697 #endif
11698 question->StopTime = (question->TimeoutQuestion) ? question->StopTime : 0;
11699 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11700 mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
11701 question->metrics.expiredAnswerState = (question->allowExpired != AllowExpired_None) ? ExpiredAnswer_Allowed : ExpiredAnswer_None;
11702 #endif
11703
11704 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11705 if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion)
11706 return;
11707 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11708 if (!mDNSOpaque16IsZero(question->TargetQID))
11709 {
11710 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11711 mDNSu32 timeout = 30;
11712 #else
11713 mDNSu32 timeout = SetValidDNSServers(m, question);
11714 #endif
11715 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11716 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11717 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11718 // it gets a full timeout value even if the original question times out earlier.
11719 if (question->TimeoutQuestion && !question->StopTime)
11720 {
11721 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11722 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11723 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11724 mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11725 }
11726
11727 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11728 Querier_SetDNSServiceForQuestion(question);
11729 #else
11730 question->qDNSServer = GetServerForQuestion(m, question);
11731 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
11732 "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME " " PUB_S " Timeout %d, DNS Server " PRI_IP_ADDR ":%d",
11733 question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname),
11734 DNSTypeName(question->qtype), timeout, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11735 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11736 #endif
11737 }
11738 else if (question->TimeoutQuestion && !question->StopTime)
11739 {
11740 // If the question is to be timed out and its a multicast, local-only or P2P case,
11741 // then set it's stop time.
11742 mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ?
11743 DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question);
11744 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11745 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11746 "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11747 question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11748 }
11749 // Set StopTime here since it is a part of DNS Configuration
11750 if (question->StopTime)
11751 SetNextQueryStopTime(m, question);
11752 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11753 // will never be transmitted on the wire.
11754 if (!(LocalOnlyOrP2PInterface(question->InterfaceID)))
11755 SetNextQueryTime(m,question);
11756 }
11757
11758 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11759 // state fields of the DNS Question. These are independent of the Client layer.
InitCommonState(mDNS * const m,DNSQuestion * const question)11760 mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question)
11761 {
11762 int i;
11763
11764 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11765 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11766 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11767 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11768 // that to go out immediately.
11769 question->next = mDNSNULL;
11770 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11771 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11772 // the question list to check if ThisQInterval is negative which means the question has been
11773 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11774 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11775 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11776 // turned ON which can allocate memory e.g., base64 encoding.
11777 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
11778 question->qnamehash = DomainNameHashValue(&question->qname);
11779 question->DelayAnswering = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0;
11780 question->LastQTime = m->timenow;
11781 question->ExpectUnicastResp = 0;
11782 question->LastAnswerPktNum = m->PktNum;
11783 question->RecentAnswerPkts = 0;
11784 question->CurrentAnswers = 0;
11785
11786 #if APPLE_OSX_mDNSResponder
11787
11788 // Initial browse threshold used by Finder.
11789 #define mDNSFinderBrowseThreshold 20
11790
11791 // Set the threshold at which we move to a passive browse state,
11792 // not actively sending queries.
11793 if (question->flags & kDNSServiceFlagsThresholdOne)
11794 question->BrowseThreshold = 1;
11795 else if (question->flags & kDNSServiceFlagsThresholdFinder)
11796 question->BrowseThreshold = mDNSFinderBrowseThreshold;
11797 else
11798 question->BrowseThreshold = 0;
11799
11800 #else // APPLE_OSX_mDNSResponder
11801 question->BrowseThreshold = 0;
11802 #endif // APPLE_OSX_mDNSResponder
11803 question->CachedAnswerNeedsUpdate = mDNSfalse;
11804
11805 question->LargeAnswers = 0;
11806 question->UniqueAnswers = 0;
11807 question->LOAddressAnswers = 0;
11808 question->FlappingInterface1 = mDNSNULL;
11809 question->FlappingInterface2 = mDNSNULL;
11810
11811 // mDNSPlatformGetDNSRoutePolicy() and InitDNSConfig() may set a DNSQuestion's BlockedByPolicy value,
11812 // so they should be called before calling ShouldSuppressQuery(), which checks BlockedByPolicy.
11813 question->BlockedByPolicy = mDNSfalse;
11814
11815 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11816 // since we would already have the question->ServiceID in that case.
11817 if (!(question->flags & kDNSServiceFlagsServiceIndex))
11818 {
11819 question->ServiceID = -1;
11820 #if APPLE_OSX_mDNSResponder
11821 if (!(question->flags & kDNSServiceFlagsPathEvaluationDone) || question->ForcePathEval)
11822 {
11823 if (question->flags & kDNSServiceFlagsPathEvaluationDone)
11824 {
11825 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11826 "[R%u->Q%u] Forcing another path evaluation", question->request_id, mDNSVal16(question->TargetQID));
11827 }
11828 question->ForcePathEval = mDNSfalse;
11829 mDNSPlatformGetDNSRoutePolicy(question);
11830 }
11831 #endif
11832 }
11833 else
11834 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11835 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11836
11837 InitDNSConfig(m, question);
11838 question->AuthInfo = GetAuthInfoForQuestion(m, question);
11839 question->Suppressed = ShouldSuppressQuery(question);
11840 question->NextInDQList = mDNSNULL;
11841 question->SendQNow = mDNSNULL;
11842 question->SendOnAll = mDNSfalse;
11843 question->RequestUnicast = kDefaultRequestUnicastCount;
11844
11845 #if APPLE_OSX_mDNSResponder
11846 // Set the QU bit in the first query for the following options.
11847 if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder))
11848 {
11849 question->RequestUnicast = SET_QU_IN_FIRST_QUERY;
11850 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11851 DNSTypeName(question->qtype));
11852 }
11853 #endif // APPLE_OSX_mDNSResponder
11854
11855 question->LastQTxTime = m->timenow;
11856 question->CNAMEReferrals = 0;
11857
11858 question->WakeOnResolveCount = 0;
11859 if (question->WakeOnResolve)
11860 {
11861 question->WakeOnResolveCount = InitialWakeOnResolveCount;
11862 }
11863
11864 for (i=0; i<DupSuppressInfoSize; i++)
11865 question->DupSuppress[i].InterfaceID = mDNSNULL;
11866
11867 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11868 question->Restart = mDNSfalse;
11869 #endif
11870
11871 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11872 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11873 NextQSendTime(question) - m->timenow,
11874 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11875 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11876
11877 if (question->DelayAnswering)
11878 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11879 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11880 }
11881
11882 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
InitWABState(DNSQuestion * const question)11883 mDNSlocal void InitWABState(DNSQuestion *const question)
11884 {
11885 // We'll create our question->LocalSocket on demand, if needed.
11886 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11887 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11888 // NAT mapping for receiving inbound add/remove events.
11889 question->LocalSocket = mDNSNULL;
11890 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11891 mdns_querier_forget(&question->querier);
11892 #else
11893 question->unansweredQueries = 0;
11894 #endif
11895 question->nta = mDNSNULL;
11896 question->servAddr = zeroAddr;
11897 question->servPort = zeroIPPort;
11898 question->tcp = mDNSNULL;
11899 question->NoAnswer = NoAnswer_Normal;
11900 }
11901
InitLLQNATState(mDNS * const m)11902 mDNSlocal void InitLLQNATState(mDNS *const m)
11903 {
11904 // If we don't have our NAT mapping active, start it now
11905 if (!m->LLQNAT.clientCallback)
11906 {
11907 m->LLQNAT.Protocol = NATOp_MapUDP;
11908 m->LLQNAT.IntPort = m->UnicastPort4;
11909 m->LLQNAT.RequestedPort = m->UnicastPort4;
11910 m->LLQNAT.clientCallback = LLQNATCallback;
11911 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal just started
11912 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11913 }
11914 }
11915
InitLLQState(DNSQuestion * const question)11916 mDNSlocal void InitLLQState(DNSQuestion *const question)
11917 {
11918 question->state = LLQ_Init;
11919 question->ReqLease = 0;
11920 question->expire = 0;
11921 question->ntries = 0;
11922 question->id = zeroOpaque64;
11923 }
11924
11925 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11926 // DNSSEC & DNS Proxy fields of the DNS Question.
InitDNSSECProxyState(mDNS * const m,DNSQuestion * const question)11927 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11928 {
11929 (void) m;
11930 question->responseFlags = zeroID;
11931 }
11932
11933 // Once the question is completely initialized including the duplicate logic, this function
11934 // is called to finalize the unicast question which requires flushing the cache if needed,
11935 // activating the query etc.
FinalizeUnicastQuestion(mDNS * const m,DNSQuestion * question)11936 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question)
11937 {
11938 // Ensure DNS related info of duplicate question is same as the orig question
11939 if (question->DuplicateOf)
11940 {
11941 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11942 const DNSQuestion *const duplicateOf = question->DuplicateOf;
11943 mdns_replace(&question->dnsservice, duplicateOf->dnsservice);
11944 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11945 "[R%u->DupQ%u->Q%u] Duplicate question " PRI_DM_NAME " (" PUB_S ")",
11946 question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(duplicateOf->TargetQID),
11947 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11948 #else
11949 question->validDNSServers = question->DuplicateOf->validDNSServers;
11950 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11951 // then we log a line as it could indicate an issue
11952 if (question->DuplicateOf->qDNSServer == mDNSNULL)
11953 {
11954 if (question->qDNSServer)
11955 {
11956 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11957 "[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 ")",
11958 question->request_id, mDNSVal16(question->TargetQID), question,
11959 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11960 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort), question->DuplicateOf,
11961 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11962 }
11963 }
11964 question->qDNSServer = question->DuplicateOf->qDNSServer;
11965 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11966 "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME " (" PUB_S "), DNS Server " PRI_IP_ADDR ":%d",
11967 question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID),
11968 question, question->DuplicateOf, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype),
11969 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11970 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11971 #endif
11972 }
11973
11974 ActivateUnicastQuery(m, question, mDNSfalse);
11975
11976 if (question->LongLived)
11977 {
11978 // Unlike other initializations, InitLLQNATState should be done after
11979 // we determine that it is a unicast question. LongLived is set for
11980 // both multicast and unicast browse questions but we should initialize
11981 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11982 // start the NAT traversal that is not needed.
11983 InitLLQNATState(m);
11984 }
11985 }
11986
mDNS_StartQuery_internal(mDNS * const m,DNSQuestion * const question)11987 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
11988 {
11989 DNSQuestion **q;
11990 mStatus vStatus;
11991
11992 // First check for cache space (can't do queries if there is no cache space allocated)
11993 if (m->rrcache_size == 0)
11994 return(mStatus_NoCache);
11995
11996 vStatus = ValidateParameters(m, question);
11997 if (vStatus)
11998 return(vStatus);
11999
12000 #ifdef USE_LIBIDN
12001 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12002 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12003 // This applies to the top label (TLD) only
12004 // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12005 if (IsHighASCIILabel(LastLabel(&question->qname)))
12006 {
12007 domainname newname;
12008 if (PerformNextPunycodeConversion(question, &newname))
12009 AssignDomainName(&question->qname, &newname);
12010 }
12011 #endif // USE_LIBIDN
12012
12013 #ifndef UNICAST_DISABLED
12014 question->TargetQID = Question_uDNS(question) ? mDNS_NewMessageID(m) : zeroID;
12015 #else
12016 question->TargetQID = zeroID;
12017 #endif
12018 debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12019
12020 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12021 q = &m->Questions;
12022 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12023 q = &m->LocalOnlyQuestions;
12024 while (*q && *q != question)
12025 q=&(*q)->next;
12026
12027 if (*q)
12028 {
12029 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12030 question->qname.c, DNSTypeName(question->qtype), question);
12031 return(mStatus_AlreadyRegistered);
12032 }
12033 *q = question;
12034
12035 // Intialize the question. The only ordering constraint we have today is that
12036 // InitDNSSECProxyState should be called after the DNS server is selected (in
12037 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12038 // validation.
12039
12040 InitCommonState(m, question);
12041 InitWABState(question);
12042 InitLLQState(question);
12043 InitDNSSECProxyState(m, question);
12044
12045 // FindDuplicateQuestion should be called last after all the intialization
12046 // as the duplicate logic could be potentially based on any field in the
12047 // question.
12048 question->DuplicateOf = FindDuplicateQuestion(m, question);
12049 if (question->DuplicateOf)
12050 question->AuthInfo = question->DuplicateOf->AuthInfo;
12051
12052 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12053 {
12054 if (!m->NewLocalOnlyQuestions)
12055 m->NewLocalOnlyQuestions = question;
12056 }
12057 else
12058 {
12059 if (!m->NewQuestions)
12060 m->NewQuestions = question;
12061
12062 // If the question's id is non-zero, then it's Wide Area
12063 // MUST NOT do this Wide Area setup until near the end of
12064 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12065 // NS, etc.) and if we haven't finished setting up our own question and setting
12066 // m->NewQuestions if necessary then we could end up recursively re-entering
12067 // this routine with the question list data structures in an inconsistent state.
12068 if (!mDNSOpaque16IsZero(question->TargetQID))
12069 {
12070 FinalizeUnicastQuestion(m, question);
12071 }
12072 else
12073 {
12074 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12075 m->NumAllInterfaceQuestions++;
12076 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12077 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12078 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12079 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12080 {
12081 m->NextBonjourDisableTime = 0;
12082 if (m->BonjourEnabled == 0)
12083 {
12084 // Enable Bonjour immediately by scheduling network changed processing where
12085 // we will join the multicast group on each active interface.
12086 m->BonjourEnabled = 1;
12087 m->NetworkChanged = m->timenow;
12088 }
12089 }
12090 #endif
12091 if (question->WakeOnResolve)
12092 {
12093 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
12094 mDNS_PurgeBeforeResolve(m, question);
12095 }
12096 }
12097 }
12098
12099 return(mStatus_NoError);
12100 }
12101
12102 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
CancelGetZoneData(mDNS * const m,ZoneData * nta)12103 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
12104 {
12105 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
12106 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12107 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12108 // call it again
12109 if (nta->question.ThisQInterval != -1)
12110 {
12111 mDNS_StopQuery_internal(m, &nta->question);
12112 if (nta->question.ThisQInterval != -1)
12113 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
12114 }
12115 mDNSPlatformMemFree(nta);
12116 }
12117
mDNS_StopQuery_internal(mDNS * const m,DNSQuestion * const question)12118 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
12119 {
12120 CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12121 CacheRecord *cr;
12122 DNSQuestion **qp = &m->Questions;
12123
12124 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12125
12126 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12127 qp = &m->LocalOnlyQuestions;
12128 while (*qp && *qp != question) qp=&(*qp)->next;
12129 if (*qp) *qp = (*qp)->next;
12130 else
12131 {
12132 #if !ForceAlerts
12133 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
12134 #endif
12135 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
12136 return(mStatus_BadReferenceErr);
12137 }
12138
12139 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12140 if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID))
12141 {
12142 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12143 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
12144 m->NumAllInterfaceQuestions--;
12145 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12146 "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12147 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12148 }
12149 #endif
12150
12151 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12152 if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.firstQueryTime != 0))
12153 {
12154 mDNSu32 querySendCount = question->metrics.querySendCount;
12155 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12156 if (question->querier)
12157 {
12158 querySendCount += mdns_querier_get_send_count(question->querier);
12159 }
12160 #endif
12161 if (querySendCount > 0)
12162 {
12163 const domainname * queryName;
12164 mDNSBool isForCell;
12165 mDNSu32 durationMs;
12166
12167 queryName = question->metrics.originalQName ? question->metrics.originalQName : &question->qname;
12168 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12169 isForCell = (question->dnsservice && mdns_dns_service_interface_is_cellular(question->dnsservice));
12170 #else
12171 isForCell = (question->qDNSServer && question->qDNSServer->isCell);
12172 #endif
12173 durationMs = ((m->timenow - question->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
12174 MetricsUpdateDNSQueryStats(queryName, question->qtype, mDNSNULL, querySendCount,
12175 question->metrics.expiredAnswerState, question->metrics.dnsOverTCPState, durationMs, isForCell);
12176 }
12177 }
12178 #endif
12179 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12180 UpdateQuestionDuplicates(m, question);
12181 // But don't trash ThisQInterval until afterwards.
12182 question->ThisQInterval = -1;
12183
12184 // If there are any cache records referencing this as their active question, then see if there is any
12185 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12186 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12187 {
12188 if (cr->CRActiveQuestion == question)
12189 {
12190 DNSQuestion *q;
12191 DNSQuestion *replacement = mDNSNULL;
12192 // If we find an active question that is answered by this cached record, use it as the cache record's
12193 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12194 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12195 // via CacheRecordRmv() when the cache record expires.
12196 for (q = m->Questions; q && (q != m->NewQuestions); q = q->next)
12197 {
12198 if (!q->DuplicateOf && !q->Suppressed && CacheRecordAnswersQuestion(cr, q))
12199 {
12200 if (q->ThisQInterval > 0)
12201 {
12202 replacement = q;
12203 break;
12204 }
12205 else if (!replacement)
12206 {
12207 replacement = q;
12208 }
12209 }
12210 }
12211 if (replacement)
12212 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12213 "CurrentAnswers %d, Suppressed %d", replacement, CRDisplayString(m,cr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->Suppressed);
12214 cr->CRActiveQuestion = replacement; // Question used to be active; new value may or may not be null
12215 if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count
12216 }
12217 }
12218
12219 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12220 // bump its pointer forward one question.
12221 if (m->CurrentQuestion == question)
12222 {
12223 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12224 question->qname.c, DNSTypeName(question->qtype));
12225 m->CurrentQuestion = question->next;
12226 }
12227
12228 if (m->NewQuestions == question)
12229 {
12230 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12231 question->qname.c, DNSTypeName(question->qtype));
12232 m->NewQuestions = question->next;
12233 }
12234
12235 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
12236
12237 if (m->RestartQuestion == question)
12238 {
12239 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12240 question->qname.c, DNSTypeName(question->qtype));
12241 m->RestartQuestion = question->next;
12242 }
12243
12244 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12245 question->next = mDNSNULL;
12246
12247 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12248
12249 // And finally, cancel any associated GetZoneData operation that's still running.
12250 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12251 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12252 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12253 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12254 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
12255 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
12256 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12257 Querier_HandleStoppedDNSQuestion(question);
12258 #endif
12259 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
12260 {
12261 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12262 DNSQuestion *q;
12263 for (q = m->Questions; q; q=q->next)
12264 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
12265 if (!q)
12266 {
12267 if (!m->LLQNAT.clientCallback) // Should never happen, but just in case...
12268 {
12269 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12270 }
12271 else
12272 {
12273 LogInfo("Stopping LLQNAT");
12274 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
12275 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
12276 }
12277 }
12278
12279 // If necessary, tell server it can delete this LLQ state
12280 if (question->state == LLQ_Established)
12281 {
12282 question->ReqLease = 0;
12283 sendLLQRefresh(m, question);
12284 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12285 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12286 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12287 // we let that run out its natural course and complete asynchronously.
12288 if (question->tcp)
12289 {
12290 question->tcp->question = mDNSNULL;
12291 question->tcp = mDNSNULL;
12292 }
12293 }
12294 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12295 else if (question->dnsPushServer != mDNSNULL)
12296 {
12297 UnSubscribeToDNSPushNotificationServer(m, question);
12298 }
12299 #endif
12300 }
12301 // wait until we send the refresh above which needs the nta
12302 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
12303
12304 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12305 uDNSMetricsClear(&question->metrics);
12306 #endif
12307
12308 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12309 DNS64ResetState(question);
12310 #endif
12311
12312 return(mStatus_NoError);
12313 }
12314
mDNS_StartQuery(mDNS * const m,DNSQuestion * const question)12315 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
12316 {
12317 mStatus status;
12318 mDNS_Lock(m);
12319 status = mDNS_StartQuery_internal(m, question);
12320 mDNS_Unlock(m);
12321 return(status);
12322 }
12323
mDNS_StopQuery(mDNS * const m,DNSQuestion * const question)12324 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
12325 {
12326 mStatus status;
12327 mDNS_Lock(m);
12328 status = mDNS_StopQuery_internal(m, question);
12329 mDNS_Unlock(m);
12330 return(status);
12331 }
12332
12333 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12334 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12335 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12336 // specifically to catch and report if the client callback does try to make API calls
mDNS_StopQueryWithRemoves(mDNS * const m,DNSQuestion * const question)12337 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12338 {
12339 mStatus status;
12340 DNSQuestion *qq;
12341 mDNS_Lock(m);
12342
12343 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12344 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12345
12346 status = mDNS_StopQuery_internal(m, question);
12347 if (status == mStatus_NoError && !qq)
12348 {
12349 const CacheRecord *cr;
12350 CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12351 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12352 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12353 {
12354 if (cr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameCacheRecordAnswersQuestion(cr, question))
12355 {
12356 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12357 if (question->QuestionCallback)
12358 question->QuestionCallback(m, question, &cr->resrec, mDNSfalse);
12359 }
12360 }
12361 }
12362 mDNS_Unlock(m);
12363 return(status);
12364 }
12365
mDNS_Reconfirm(mDNS * const m,CacheRecord * const cr)12366 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12367 {
12368 mStatus status;
12369 mDNS_Lock(m);
12370 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12371 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12372 mDNS_Unlock(m);
12373 return(status);
12374 }
12375
mDNS_ReconfirmByValue(mDNS * const m,ResourceRecord * const rr)12376 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12377 {
12378 mStatus status = mStatus_BadReferenceErr;
12379 CacheRecord *cr;
12380 mDNS_Lock(m);
12381 cr = FindIdenticalRecordInCache(m, rr);
12382 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12383 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12384 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12385 mDNS_Unlock(m);
12386 return(status);
12387 }
12388
mDNS_StartBrowse_internal(mDNS * const m,DNSQuestion * const question,const domainname * const srv,const domainname * const domain,const mDNSInterfaceID InterfaceID,mDNSu32 flags,mDNSBool ForceMCast,mDNSBool useBackgroundTrafficClass,mDNSQuestionCallback * Callback,void * Context)12389 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12390 const domainname *const srv, const domainname *const domain,
12391 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12392 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12393 mDNSQuestionCallback *Callback, void *Context)
12394 {
12395 question->InterfaceID = InterfaceID;
12396 question->flags = flags;
12397 question->qtype = kDNSType_PTR;
12398 question->qclass = kDNSClass_IN;
12399 question->LongLived = mDNStrue;
12400 question->ExpectUnique = mDNSfalse;
12401 question->ForceMCast = ForceMCast;
12402 question->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
12403 question->SuppressUnusable = mDNSfalse;
12404 question->AppendSearchDomains = mDNSfalse;
12405 question->TimeoutQuestion = 0;
12406 question->WakeOnResolve = 0;
12407 question->UseBackgroundTraffic = useBackgroundTrafficClass;
12408 question->ProxyQuestion = 0;
12409 question->QuestionCallback = Callback;
12410 question->QuestionContext = Context;
12411
12412 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12413 return(mStatus_BadParamErr);
12414
12415 return(mDNS_StartQuery_internal(m, question));
12416 }
12417
mDNS_StartBrowse(mDNS * const m,DNSQuestion * const question,const domainname * const srv,const domainname * const domain,const mDNSInterfaceID InterfaceID,mDNSu32 flags,mDNSBool ForceMCast,mDNSBool useBackgroundTrafficClass,mDNSQuestionCallback * Callback,void * Context)12418 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12419 const domainname *const srv, const domainname *const domain,
12420 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12421 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12422 mDNSQuestionCallback *Callback, void *Context)
12423 {
12424 mStatus status;
12425 mDNS_Lock(m);
12426 status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12427 mDNS_Unlock(m);
12428 return(status);
12429 }
12430
12431
mDNS_GetDomains(mDNS * const m,DNSQuestion * const question,mDNS_DomainType DomainType,const domainname * dom,const mDNSInterfaceID InterfaceID,mDNSQuestionCallback * Callback,void * Context)12432 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12433 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12434 {
12435 question->InterfaceID = InterfaceID;
12436 question->flags = 0;
12437 question->qtype = kDNSType_PTR;
12438 question->qclass = kDNSClass_IN;
12439 question->LongLived = mDNSfalse;
12440 question->ExpectUnique = mDNSfalse;
12441 question->ForceMCast = mDNSfalse;
12442 question->ReturnIntermed = mDNSfalse;
12443 question->SuppressUnusable = mDNSfalse;
12444 question->AppendSearchDomains = mDNSfalse;
12445 question->TimeoutQuestion = 0;
12446 question->WakeOnResolve = 0;
12447 question->UseBackgroundTraffic = mDNSfalse;
12448 question->ProxyQuestion = 0;
12449 question->pid = mDNSPlatformGetPID();
12450 question->euid = 0;
12451 question->QuestionCallback = Callback;
12452 question->QuestionContext = Context;
12453 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12454 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12455 if (!dom) dom = &localdomain;
12456 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12457 return(mDNS_StartQuery(m, question));
12458 }
12459
12460 // ***************************************************************************
12461 #if COMPILER_LIKES_PRAGMA_MARK
12462 #pragma mark -
12463 #pragma mark - Responder Functions
12464 #endif
12465
mDNS_Register(mDNS * const m,AuthRecord * const rr)12466 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12467 {
12468 mStatus status;
12469 mDNS_Lock(m);
12470 status = mDNS_Register_internal(m, rr);
12471 mDNS_Unlock(m);
12472 return(status);
12473 }
12474
mDNS_Update(mDNS * const m,AuthRecord * const rr,mDNSu32 newttl,const mDNSu16 newrdlength,RData * const newrdata,mDNSRecordUpdateCallback * Callback)12475 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12476 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12477 {
12478 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12479 {
12480 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12481 return(mStatus_Invalid);
12482 }
12483
12484 mDNS_Lock(m);
12485
12486 // If TTL is unspecified, leave TTL unchanged
12487 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12488
12489 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12490 if (rr->NewRData)
12491 {
12492 RData *n = rr->NewRData;
12493 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
12494 if (rr->UpdateCallback)
12495 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
12496 }
12497
12498 rr->NewRData = newrdata;
12499 rr->newrdlength = newrdlength;
12500 rr->UpdateCallback = Callback;
12501
12502 #ifndef UNICAST_DISABLED
12503 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12504 {
12505 mStatus status = uDNS_UpdateRecord(m, rr);
12506 // The caller frees the memory on error, don't retain stale pointers
12507 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12508 mDNS_Unlock(m);
12509 return(status);
12510 }
12511 #endif
12512
12513 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12514 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12515 CompleteRDataUpdate(m, rr);
12516 else
12517 {
12518 rr->AnnounceCount = InitialAnnounceCount;
12519 InitializeLastAPTime(m, rr);
12520 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12521 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12522 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12523 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12524 if (rr->UpdateCredits <= 5)
12525 {
12526 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12527 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12528 rr->ThisAPInterval *= 4;
12529 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12530 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12531 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12532 }
12533 rr->resrec.rroriginalttl = newttl;
12534 }
12535
12536 mDNS_Unlock(m);
12537 return(mStatus_NoError);
12538 }
12539
12540 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12541 // the record list and/or question list.
12542 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
mDNS_Deregister(mDNS * const m,AuthRecord * const rr)12543 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12544 {
12545 mStatus status;
12546 mDNS_Lock(m);
12547 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12548 mDNS_Unlock(m);
12549 return(status);
12550 }
12551
12552 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12553 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12554 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12555 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *m, AuthRecord *rr, mStatus result);
12556 #endif
12557
GetInterfaceAddressRecord(NetworkInterfaceInfo * intf,mDNSBool forRandHostname)12558 mDNSlocal AuthRecord *GetInterfaceAddressRecord(NetworkInterfaceInfo *intf, mDNSBool forRandHostname)
12559 {
12560 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12561 return(forRandHostname ? &intf->RR_AddrRand : &intf->RR_A);
12562 #else
12563 (void)forRandHostname; // Unused.
12564 return(&intf->RR_A);
12565 #endif
12566 }
12567
GetFirstAddressRecordEx(const mDNS * const m,const mDNSBool forRandHostname)12568 mDNSlocal AuthRecord *GetFirstAddressRecordEx(const mDNS *const m, const mDNSBool forRandHostname)
12569 {
12570 NetworkInterfaceInfo *intf;
12571 for (intf = m->HostInterfaces; intf; intf = intf->next)
12572 {
12573 if (!intf->Advertise) continue;
12574 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12575 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
12576 #endif
12577 return(GetInterfaceAddressRecord(intf, forRandHostname));
12578 }
12579 return(mDNSNULL);
12580 }
12581 #define GetFirstAddressRecord(M) GetFirstAddressRecordEx(M, mDNSfalse)
12582
12583 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12584 // (It's a set of records, not a set of interfaces.)
12585 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
AdvertiseInterface(mDNS * const m,NetworkInterfaceInfo * set,mDNSBool useRandomizedHostname)12586 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool useRandomizedHostname)
12587 #else
12588 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12589 #endif
12590 {
12591 const domainname *hostname;
12592 mDNSRecordCallback *hostnameCallback;
12593 AuthRecord *addrAR;
12594 AuthRecord *ptrAR;
12595 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12596 const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12597 #endif
12598 mDNSu8 addrRecordType;
12599 char buffer[MAX_REVERSE_MAPPING_NAME];
12600
12601 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12602 if (interfaceIsAWDL || useRandomizedHostname)
12603 {
12604 hostname = &m->RandomizedHostname;
12605 hostnameCallback = mDNS_RandomizedHostNameCallback;
12606 }
12607 else
12608 #endif
12609 {
12610 hostname = &m->MulticastHostname;
12611 hostnameCallback = mDNS_HostNameCallback;
12612 }
12613
12614 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12615 if (!interfaceIsAWDL && useRandomizedHostname)
12616 {
12617 addrAR = &set->RR_AddrRand;
12618 ptrAR = mDNSNULL;
12619 }
12620 else
12621 #endif
12622 {
12623 addrAR = &set->RR_A;
12624 ptrAR = &set->RR_PTR;
12625 }
12626 if (addrAR->resrec.RecordType != kDNSRecordTypeUnregistered) return;
12627
12628 addrRecordType = set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
12629 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12630 if (hostname == &m->RandomizedHostname) addrRecordType = kDNSRecordTypeKnownUnique;
12631 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12632 "AdvertiseInterface: Advertising " PUB_S " hostname on interface " PUB_S,
12633 (hostname == &m->RandomizedHostname) ? "randomized" : "normal", set->ifname);
12634 #else
12635 LogInfo("AdvertiseInterface: Advertising for ifname %s", set->ifname);
12636 #endif
12637
12638 // Send dynamic update for non-linklocal IPv4 Addresses
12639 mDNS_SetupResourceRecord(addrAR, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, addrRecordType, AuthRecordAny, hostnameCallback, set);
12640 if (ptrAR) mDNS_SetupResourceRecord(ptrAR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12641
12642 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12643 addrAR->AllowRemoteQuery = mDNStrue;
12644 if (ptrAR) ptrAR->AllowRemoteQuery = mDNStrue;
12645 #endif
12646 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12647 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12648 AssignDomainName(&addrAR->namestorage, hostname);
12649 if (set->ip.type == mDNSAddrType_IPv4)
12650 {
12651 addrAR->resrec.rrtype = kDNSType_A;
12652 addrAR->resrec.rdata->u.ipv4 = set->ip.ip.v4;
12653 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12654 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12655 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12656 }
12657 else if (set->ip.type == mDNSAddrType_IPv6)
12658 {
12659 int i;
12660 addrAR->resrec.rrtype = kDNSType_AAAA;
12661 addrAR->resrec.rdata->u.ipv6 = set->ip.ip.v6;
12662 for (i = 0; i < 16; i++)
12663 {
12664 static const char hexValues[] = "0123456789ABCDEF";
12665 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12666 buffer[i * 4 + 1] = '.';
12667 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12668 buffer[i * 4 + 3] = '.';
12669 }
12670 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12671 }
12672
12673 if (ptrAR)
12674 {
12675 MakeDomainNameFromDNSNameString(&ptrAR->namestorage, buffer);
12676 ptrAR->AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12677 ptrAR->ForceMCast = mDNStrue; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12678 }
12679
12680 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12681 addrAR->RRSet = interfaceIsAWDL ? addrAR : GetFirstAddressRecordEx(m, useRandomizedHostname);
12682 #else
12683 addrAR->RRSet = GetFirstAddressRecord(m);
12684 #endif
12685 if (!addrAR->RRSet) addrAR->RRSet = addrAR;
12686 mDNS_Register_internal(m, addrAR);
12687 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Initialized RRSet for " PRI_S, ARDisplayString(m, addrAR));
12688 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "RRSet: " PRI_S, ARDisplayString(m, addrAR->RRSet));
12689 if (ptrAR) mDNS_Register_internal(m, ptrAR);
12690
12691 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12692 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12693 D2D_start_advertising_interface(set);
12694 #endif
12695 }
12696
AdvertiseInterfaceIfNeeded(mDNS * const m,NetworkInterfaceInfo * set)12697 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set)
12698 {
12699 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12700 if (mDNSPlatformInterfaceIsAWDL(set->InterfaceID))
12701 {
12702 if ((m->AutoTargetAWDLIncludedCount > 0) || (m->AutoTargetAWDLOnlyCount > 0))
12703 {
12704 AdvertiseInterface(m, set, mDNSfalse);
12705 }
12706 }
12707 else
12708 {
12709 if (m->AutoTargetServices > 0) AdvertiseInterface(m, set, mDNSfalse);
12710 if (m->AutoTargetAWDLIncludedCount > 0) AdvertiseInterface(m, set, mDNStrue);
12711 }
12712 #else
12713 if (m->AutoTargetServices > 0) AdvertiseInterface(m, set);
12714 #endif
12715 }
12716
DeadvertiseInterface(mDNS * const m,NetworkInterfaceInfo * set,DeadvertiseFlags flags)12717 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags)
12718 {
12719 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12720 const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12721 #endif
12722
12723 // Unregister these records.
12724 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12725 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12726 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12727 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12728 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12729 if ((!interfaceIsAWDL && (flags & kDeadvertiseFlag_NormalHostname)) ||
12730 ( interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname)))
12731 #else
12732 if (flags & kDeadvertiseFlag_NormalHostname)
12733 #endif
12734 {
12735 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12736 "DeadvertiseInterface: Deadvertising " PUB_S " hostname on interface " PUB_S,
12737 (flags & kDeadvertiseFlag_RandHostname) ? "randomized" : "normal", set->ifname);
12738 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12739 D2D_stop_advertising_interface(set);
12740 #endif
12741 if (set->RR_A.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
12742 if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12743 }
12744 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12745 if (!interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname))
12746 {
12747 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12748 "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S, set->ifname);
12749 AuthRecord *const ar = &set->RR_AddrRand;
12750 if (ar->resrec.RecordType) mDNS_Deregister_internal(m, ar, mDNS_Dereg_normal);
12751 }
12752 #endif
12753 }
12754
12755 // Change target host name for record.
UpdateTargetHostName(mDNS * const m,AuthRecord * const rr)12756 mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr)
12757 {
12758 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12759 // If this record was also registered with any D2D plugins, stop advertising
12760 // the version with the old host name.
12761 D2D_stop_advertising_record(rr);
12762 #endif
12763
12764 SetTargetToHostName(m, rr);
12765
12766 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12767 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12768 D2D_start_advertising_record(rr);
12769 #endif
12770 }
12771
DeadvertiseAllInterfaceRecords(mDNS * const m,DeadvertiseFlags flags)12772 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m, DeadvertiseFlags flags)
12773 {
12774 NetworkInterfaceInfo *intf;
12775 for (intf = m->HostInterfaces; intf; intf = intf->next)
12776 {
12777 if (intf->Advertise) DeadvertiseInterface(m, intf, flags);
12778 }
12779 }
12780
mDNS_SetFQDN(mDNS * const m)12781 mDNSexport void mDNS_SetFQDN(mDNS *const m)
12782 {
12783 domainname newmname;
12784 AuthRecord *rr;
12785 newmname.c[0] = 0;
12786
12787 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12788 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12789
12790 mDNS_Lock(m);
12791
12792 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12793 else
12794 {
12795 AssignDomainName(&m->MulticastHostname, &newmname);
12796 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_NormalHostname);
12797 AdvertiseNecessaryInterfaceRecords(m);
12798 }
12799
12800 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12801 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12802 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12803
12804 mDNS_Unlock(m);
12805 }
12806
mDNS_HostNameCallback(mDNS * const m,AuthRecord * const rr,mStatus result)12807 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12808 {
12809 (void)rr; // Unused parameter
12810
12811 #if MDNS_DEBUGMSGS
12812 {
12813 char *msg = "Unknown result";
12814 if (result == mStatus_NoError) msg = "Name registered";
12815 else if (result == mStatus_NameConflict) msg = "Name conflict";
12816 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12817 }
12818 #endif
12819
12820 if (result == mStatus_NoError)
12821 {
12822 // Notify the client that the host name is successfully registered
12823 if (m->MainCallback)
12824 m->MainCallback(m, mStatus_NoError);
12825 }
12826 else if (result == mStatus_NameConflict)
12827 {
12828 domainlabel oldlabel = m->hostlabel;
12829
12830 // 1. First give the client callback a chance to pick a new name
12831 if (m->MainCallback)
12832 m->MainCallback(m, mStatus_NameConflict);
12833
12834 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12835 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12836 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12837 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12838 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12839
12840 // 3. Generate the FQDNs from the hostlabel,
12841 // and make sure all SRV records, etc., are updated to reference our new hostname
12842 mDNS_SetFQDN(m);
12843 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12844 }
12845 else if (result == mStatus_MemFree)
12846 {
12847 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12848 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12849 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12850 }
12851 else
12852 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
12853 }
12854
12855 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
mDNS_RandomizedHostNameCallback(mDNS * const m,AuthRecord * const addrRecord,const mStatus result)12856 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *const m, AuthRecord *const addrRecord, const mStatus result)
12857 {
12858 (void)addrRecord; // Unused parameter
12859
12860 if (result == mStatus_NameConflict)
12861 {
12862 AuthRecord *rr;
12863 domainlabel newUUIDLabel;
12864
12865 GetRandomUUIDLabel(&newUUIDLabel);
12866 if (SameDomainLabel(newUUIDLabel.c, m->RandomizedHostname.c))
12867 {
12868 IncrementLabelSuffix(&newUUIDLabel, mDNSfalse);
12869 }
12870
12871 mDNS_Lock(m);
12872
12873 m->RandomizedHostname.c[0] = 0;
12874 AppendDomainLabel(&m->RandomizedHostname, &newUUIDLabel);
12875 AppendLiteralLabelString(&m->RandomizedHostname, "local");
12876
12877 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_RandHostname);
12878 AdvertiseNecessaryInterfaceRecords(m);
12879 for (rr = m->ResourceRecords; rr; rr = rr->next)
12880 {
12881 if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12882 }
12883 for (rr = m->DuplicateRecords; rr; rr = rr->next)
12884 {
12885 if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12886 }
12887
12888 mDNS_Unlock(m);
12889 }
12890 }
12891 #endif
12892
UpdateInterfaceProtocols(mDNS * const m,NetworkInterfaceInfo * active)12893 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12894 {
12895 NetworkInterfaceInfo *intf;
12896 active->IPv4Available = mDNSfalse;
12897 active->IPv6Available = mDNSfalse;
12898 for (intf = m->HostInterfaces; intf; intf = intf->next)
12899 if (intf->InterfaceID == active->InterfaceID)
12900 {
12901 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12902 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12903 }
12904 }
12905
RestartRecordGetZoneData(mDNS * const m)12906 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12907 {
12908 AuthRecord *rr;
12909 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12910 for (rr = m->ResourceRecords; rr; rr=rr->next)
12911 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12912 {
12913 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12914 // Zero out the updateid so that if we have a pending response from the server, it won't
12915 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12916 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12917 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12918 }
12919 }
12920
InitializeNetWakeState(mDNS * const m,NetworkInterfaceInfo * set)12921 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12922 {
12923 int i;
12924 // We initialize ThisQInterval to -1 indicating that the question has not been started
12925 // yet. If the question (browse) is started later during interface registration, it will
12926 // be stopped during interface deregistration. We can't sanity check to see if the
12927 // question has been stopped or not before initializing it to -1 because we need to
12928 // initialize it to -1 the very first time.
12929
12930 set->NetWakeBrowse.ThisQInterval = -1;
12931 for (i=0; i<3; i++)
12932 {
12933 set->NetWakeResolve[i].ThisQInterval = -1;
12934 set->SPSAddr[i].type = mDNSAddrType_None;
12935 }
12936 set->NextSPSAttempt = -1;
12937 set->NextSPSAttemptTime = m->timenow;
12938 }
12939
mDNS_ActivateNetWake_internal(mDNS * const m,NetworkInterfaceInfo * set)12940 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12941 {
12942 NetworkInterfaceInfo *p = m->HostInterfaces;
12943 while (p && p != set) p=p->next;
12944 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12945
12946 if (set->InterfaceActive)
12947 {
12948 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12949 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12950 }
12951 }
12952
mDNS_DeactivateNetWake_internal(mDNS * const m,NetworkInterfaceInfo * set)12953 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12954 {
12955 NetworkInterfaceInfo *p = m->HostInterfaces;
12956 while (p && p != set) p=p->next;
12957 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12958
12959 // Note: We start the browse only if the interface is NetWake capable and we use this to
12960 // stop the resolves also. Hence, the resolves should not be started without the browse
12961 // being started i.e, resolves should not happen unless NetWake capable which is
12962 // guaranteed by BeginSleepProcessing.
12963 if (set->NetWakeBrowse.ThisQInterval >= 0)
12964 {
12965 int i;
12966 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12967
12968 // Stop our browse and resolve operations
12969 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12970 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12971
12972 // Make special call to the browse callback to let it know it can to remove all records for this interface
12973 if (m->SPSBrowseCallback)
12974 {
12975 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
12976 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
12977 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
12978 }
12979
12980 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12981 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12982 InitializeNetWakeState(m, set);
12983 }
12984 }
12985
mDNS_RegisterInterface(mDNS * const m,NetworkInterfaceInfo * set,InterfaceActivationSpeed activationSpeed)12986 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
12987 {
12988 AuthRecord *rr;
12989 mDNSBool FirstOfType = mDNStrue;
12990 NetworkInterfaceInfo **p = &m->HostInterfaces;
12991
12992 if (!set->InterfaceID)
12993 {
12994 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
12995 "Tried to register a NetworkInterfaceInfo with zero InterfaceID - ifaddr: " PRI_IP_ADDR, &set->ip);
12996 return(mStatus_Invalid);
12997 }
12998
12999 if (!mDNSAddressIsValidNonZero(&set->mask))
13000 {
13001 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13002 "Tried to register a NetworkInterfaceInfo with invalid mask - ifaddr: " PRI_IP_ADDR ", ifmask: " PUB_IP_ADDR,
13003 &set->ip, &set->mask);
13004 return(mStatus_Invalid);
13005 }
13006
13007 mDNS_Lock(m);
13008
13009 // Assume this interface will be active now, unless we find a duplicate already in the list
13010 set->InterfaceActive = mDNStrue;
13011 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
13012 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
13013
13014 InitializeNetWakeState(m, set);
13015
13016 // Scan list to see if this InterfaceID is already represented
13017 while (*p)
13018 {
13019 if (*p == set)
13020 {
13021 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13022 "Tried to register a NetworkInterfaceInfo that's already in the list - "
13023 "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip);
13024 mDNS_Unlock(m);
13025 return(mStatus_AlreadyRegistered);
13026 }
13027
13028 if ((*p)->InterfaceID == set->InterfaceID)
13029 {
13030 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13031 set->InterfaceActive = mDNSfalse;
13032 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
13033 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
13034 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
13035 }
13036
13037 p=&(*p)->next;
13038 }
13039
13040 set->next = mDNSNULL;
13041 *p = set;
13042
13043 if (set->Advertise) AdvertiseInterfaceIfNeeded(m, set);
13044
13045 if (set->InterfaceActive)
13046 {
13047 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13048 "Interface not represented in list; marking active and retriggering queries - "
13049 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13050 }
13051 else
13052 {
13053 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13054 "Interface already represented in list - "
13055 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13056 }
13057
13058 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
13059
13060 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13061 // giving the false impression that there's an active representative of this interface when there really isn't.
13062 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13063 // even if we believe that we previously had an active representative of this interface.
13064 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
13065 {
13066 DNSQuestion *q;
13067 // Normally, after an interface comes up, we pause half a second before beginning probing.
13068 // This is to guard against cases where there's rapid interface changes, where we could be confused by
13069 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13070 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13071 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13072 // and think it's a conflicting answer to our probe.
13073 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13074 mDNSs32 probedelay;
13075 mDNSu8 numannounce;
13076 switch (activationSpeed)
13077 {
13078 case FastActivation:
13079 probedelay = (mDNSs32)0;
13080 numannounce = InitialAnnounceCount;
13081 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13082 "Using fast activation for DirectLink interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13083 set->ifname, &set->ip);
13084 break;
13085
13086 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13087 case SlowActivation:
13088 probedelay = mDNSPlatformOneSecond * 5;
13089 numannounce = (mDNSu8)1;
13090 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13091 "Frequent transitions for interface, doing slow activation - "
13092 "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip);
13093 m->mDNSStats.InterfaceUpFlap++;
13094 break;
13095 #endif
13096
13097 case NormalActivation:
13098 default:
13099 probedelay = mDNSPlatformOneSecond / 2;
13100 numannounce = InitialAnnounceCount;
13101 break;
13102 }
13103
13104 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13105 "Interface probe will be delayed - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR ", probe delay: %d",
13106 set->ifname, &set->ip, probedelay);
13107
13108 // No probe or sending suppression on DirectLink type interfaces.
13109 if (activationSpeed == FastActivation)
13110 {
13111 m->SuppressSending = 0;
13112 m->SuppressProbes = 0;
13113 }
13114 else
13115 {
13116 // Use a small amount of randomness:
13117 // In the case of a network administrator turning on an Ethernet hub so that all the
13118 // connected machines establish link at exactly the same time, we don't want them all
13119 // to go and hit the network with identical queries at exactly the same moment.
13120 // We set a random delay of up to InitialQuestionInterval (1/3 second).
13121 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13122 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13123 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13124 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13125 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13126 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
13127
13128 if (m->SuppressProbes == 0 ||
13129 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
13130 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
13131 }
13132
13133 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13134 // it here also handles the wake up case as the network link comes UP after waking causing
13135 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13136 // that the network link comes UP after 60 seconds and we never set the OWNER option
13137 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
13138 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Setting AnnounceOwner");
13139
13140 m->mDNSStats.InterfaceUp++;
13141 for (q = m->Questions; q; q=q->next) // Scan our list of questions
13142 {
13143 if (mDNSOpaque16IsZero(q->TargetQID))
13144 {
13145 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
13146 { // then reactivate this question
13147 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13148 // If flapping, delay between first and second queries is nine seconds instead of one second
13149 mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
13150 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
13151 mDNSs32 qdelay = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0;
13152 if (dodelay)
13153 {
13154 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13155 "No cache records expired for the question " PRI_DM_NAME " (" PUB_S ");"
13156 " delaying it by %d seconds", DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), qdelay);
13157 }
13158 #else
13159 mDNSs32 initial = InitialQuestionInterval;
13160 mDNSs32 qdelay = 0;
13161 #endif
13162
13163 if (!q->ThisQInterval || q->ThisQInterval > initial)
13164 {
13165 q->ThisQInterval = initial;
13166 q->RequestUnicast = kDefaultRequestUnicastCount;
13167 }
13168 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
13169 q->RecentAnswerPkts = 0;
13170 SetNextQueryTime(m,q);
13171 }
13172 }
13173 }
13174
13175 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13176 // we now need them to re-probe if necessary, and then re-announce.
13177 for (rr = m->ResourceRecords; rr; rr=rr->next)
13178 {
13179 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
13180 {
13181 mDNSCoreRestartRegistration(m, rr, numannounce);
13182 }
13183 }
13184 }
13185
13186 RestartRecordGetZoneData(m);
13187
13188 mDNS_UpdateAllowSleep(m);
13189
13190 mDNS_Unlock(m);
13191 return(mStatus_NoError);
13192 }
13193
AdjustAddressRecordSetsEx(mDNS * const m,NetworkInterfaceInfo * removedIntf,mDNSBool forRandHostname)13194 mDNSlocal void AdjustAddressRecordSetsEx(mDNS *const m, NetworkInterfaceInfo *removedIntf, mDNSBool forRandHostname)
13195 {
13196 NetworkInterfaceInfo *intf;
13197 const AuthRecord *oldAR;
13198 AuthRecord *newAR;
13199 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13200 if (mDNSPlatformInterfaceIsAWDL(removedIntf->InterfaceID)) return;
13201 #endif
13202 oldAR = GetInterfaceAddressRecord(removedIntf, forRandHostname);
13203 newAR = GetFirstAddressRecordEx(m, forRandHostname);
13204 for (intf = m->HostInterfaces; intf; intf = intf->next)
13205 {
13206 AuthRecord *ar;
13207 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13208 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
13209 #endif
13210 ar = GetInterfaceAddressRecord(intf, forRandHostname);
13211 if (ar->RRSet == oldAR)
13212 {
13213 ar->RRSet = newAR ? newAR : ar;
13214 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Changed RRSet for " PRI_S, ARDisplayString(m, ar));
13215 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "New RRSet: " PRI_S, ARDisplayString(m, ar->RRSet));
13216 }
13217 }
13218 }
13219 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13220 #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue)
13221 #endif
13222 #define AdjustAddressRecordSets(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse)
13223
13224 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13225 // the record list and/or question list.
13226 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
mDNS_DeregisterInterface(mDNS * const m,NetworkInterfaceInfo * set,InterfaceActivationSpeed activationSpeed)13227 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13228 {
13229 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13230 (void)activationSpeed; // Unused parameter
13231 #endif
13232 NetworkInterfaceInfo **p = &m->HostInterfaces;
13233 mDNSBool revalidate = mDNSfalse;
13234 NetworkInterfaceInfo *intf;
13235
13236 mDNS_Lock(m);
13237
13238 // Find this record in our list
13239 while (*p && *p != set) p=&(*p)->next;
13240 if (!*p)
13241 {
13242 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "NetworkInterfaceInfo not found in list");
13243 mDNS_Unlock(m);
13244 return;
13245 }
13246
13247 mDNS_DeactivateNetWake_internal(m, set);
13248
13249 // Unlink this record from our list
13250 *p = (*p)->next;
13251 set->next = mDNSNULL;
13252
13253 if (!set->InterfaceActive)
13254 {
13255 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13256 for (intf = m->HostInterfaces; intf; intf = intf->next)
13257 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13258 UpdateInterfaceProtocols(m, intf);
13259 }
13260 else
13261 {
13262 intf = FirstInterfaceForID(m, set->InterfaceID);
13263 if (intf)
13264 {
13265 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13266 "Another representative of InterfaceID exists - ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13267 IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13268 if (intf->InterfaceActive)
13269 {
13270 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13271 "intf->InterfaceActive already set for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13272 set->ifname, &set->ip);
13273 }
13274 intf->InterfaceActive = mDNStrue;
13275 UpdateInterfaceProtocols(m, intf);
13276
13277 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13278
13279 // See if another representative *of the same type* exists. If not, we mave have gone from
13280 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13281 for (intf = m->HostInterfaces; intf; intf = intf->next)
13282 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13283 break;
13284 if (!intf) revalidate = mDNStrue;
13285 }
13286 else
13287 {
13288 mDNSu32 slot;
13289 CacheGroup *cg;
13290 CacheRecord *rr;
13291 DNSQuestion *q;
13292 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13293 mDNSu32 cacheHitMulticastCount = 0;
13294 mDNSu32 cacheMissMulticastCount = 0;
13295 mDNSu32 cacheHitUnicastCount = 0;
13296 mDNSu32 cacheMissUnicastCount = 0;
13297 #endif
13298 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13299 "Last representative of InterfaceID deregistered; marking questions etc. dormant - "
13300 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13301 IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13302
13303 m->mDNSStats.InterfaceDown++;
13304
13305 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13306 if (set->McastTxRx && (activationSpeed == SlowActivation))
13307 {
13308 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13309 "Frequent transitions for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13310 set->ifname, &set->ip);
13311 m->mDNSStats.InterfaceDownFlap++;
13312 }
13313 #endif
13314
13315 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13316 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13317 for (q = m->Questions; q; q=q->next)
13318 {
13319 if (mDNSOpaque16IsZero(q->TargetQID)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13320 {
13321 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13322 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13323 {
13324 q->FlappingInterface2 = q->FlappingInterface1;
13325 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
13326 }
13327 }
13328 }
13329
13330 // 2. Flush any cache records received on this interface
13331 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
13332 FORALL_CACHERECORDS(slot, cg, rr)
13333 {
13334 if (rr->resrec.InterfaceID == set->InterfaceID)
13335 {
13336 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13337 // If this interface is deemed flapping,
13338 // postpone deleting the cache records in case the interface comes back again
13339 if (set->McastTxRx && (activationSpeed == SlowActivation))
13340 {
13341 // For a flapping interface we want these records to go away after
13342 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13343 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13344 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13345 // if the interface does come back, any relevant questions will be reactivated anyway
13346 rr->UnansweredQueries = MaxUnansweredQueries;
13347 }
13348 else
13349 #endif
13350 {
13351 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13352 if (rr->LastCachedAnswerTime)
13353 {
13354 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13355 if (rr->resrec.dnsservice) cacheHitUnicastCount++;
13356 #else
13357 if (rr->resrec.rDNSServer) cacheHitUnicastCount++;
13358 #endif
13359 else cacheHitMulticastCount++;
13360 }
13361 else
13362 {
13363 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13364 if (rr->resrec.dnsservice) cacheMissUnicastCount++;
13365 #else
13366 if (rr->resrec.rDNSServer) cacheMissUnicastCount++;
13367 #endif
13368 else cacheMissMulticastCount++;
13369 }
13370 #endif
13371 mDNS_PurgeCacheResourceRecord(m, rr);
13372 }
13373 }
13374 }
13375 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13376 dnssd_analytics_update_cache_usage_counts(cacheHitMulticastCount, cacheMissMulticastCount, cacheHitUnicastCount, cacheMissUnicastCount);
13377 #endif
13378 }
13379 }
13380
13381 // If we still have address records referring to this one, update them.
13382 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13383 // so the call to AdjustAddressRecordSets*() won’t accidentally find it.
13384 AdjustAddressRecordSets(m, set);
13385 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13386 AdjustAddressRecordSetsForRandHostname(m, set);
13387 #endif
13388
13389 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13390 if (set->Advertise) DeadvertiseInterface(m, set, kDeadvertiseFlag_All);
13391
13392 // If we have any cache records received on this interface that went away, then re-verify them.
13393 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13394 // giving the false impression that there's an active representative of this interface when there really isn't.
13395 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13396 if (revalidate && !m->ShutdownTime)
13397 {
13398 mDNSu32 slot;
13399 CacheGroup *cg;
13400 CacheRecord *rr;
13401 FORALL_CACHERECORDS(slot, cg, rr)
13402 if (rr->resrec.InterfaceID == set->InterfaceID)
13403 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13404 }
13405
13406 mDNS_UpdateAllowSleep(m);
13407
13408 mDNS_Unlock(m);
13409 }
13410
ServiceCallback(mDNS * const m,AuthRecord * const rr,mStatus result)13411 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13412 {
13413 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13414 (void)m; // Unused parameter
13415
13416 #if MDNS_DEBUGMSGS
13417 {
13418 char *msg = "Unknown result";
13419 if (result == mStatus_NoError) msg = "Name Registered";
13420 else if (result == mStatus_NameConflict) msg = "Name Conflict";
13421 else if (result == mStatus_MemFree) msg = "Memory Free";
13422 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13423 }
13424 #endif
13425
13426 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13427 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13428
13429 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13430 if (result == mStatus_NameConflict)
13431 {
13432 sr->Conflict = mDNStrue; // Record that this service set had a conflict
13433 mDNS_DeregisterService(m, sr); // Unlink the records from our list
13434 return;
13435 }
13436
13437 if (result == mStatus_MemFree)
13438 {
13439 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13440 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13441 // every record is finished cleaning up.
13442 mDNSu32 i;
13443 ExtraResourceRecord *e = sr->Extras;
13444
13445 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13446 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13447 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13448 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13449 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13450
13451 while (e)
13452 {
13453 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13454 e = e->next;
13455 }
13456
13457 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13458 // then we can now report the NameConflict to the client
13459 if (sr->Conflict) result = mStatus_NameConflict;
13460
13461 }
13462
13463 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13464 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13465 // function is allowed to do anything, including deregistering this service and freeing its memory.
13466 if (sr->ServiceCallback)
13467 sr->ServiceCallback(m, sr, result);
13468 }
13469
NSSCallback(mDNS * const m,AuthRecord * const rr,mStatus result)13470 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13471 {
13472 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13473 if (sr->ServiceCallback)
13474 sr->ServiceCallback(m, sr, result);
13475 }
13476
13477
13478 // Derive AuthRecType from the kDNSServiceFlags* values.
setAuthRecType(mDNSInterfaceID InterfaceID,mDNSu32 flags)13479 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13480 {
13481 AuthRecType artype;
13482
13483 if (InterfaceID == mDNSInterface_LocalOnly)
13484 artype = AuthRecordLocalOnly;
13485 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13486 artype = AuthRecordP2P;
13487 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
13488 && (flags & kDNSServiceFlagsIncludeAWDL))
13489 artype = AuthRecordAnyIncludeAWDLandP2P;
13490 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
13491 artype = AuthRecordAnyIncludeP2P;
13492 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
13493 artype = AuthRecordAnyIncludeAWDL;
13494 else
13495 artype = AuthRecordAny;
13496
13497 return artype;
13498 }
13499
13500 // Note:
13501 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13502 // Type is service type (e.g. "_ipp._tcp.")
13503 // Domain is fully qualified domain name (i.e. ending with a null label)
13504 // We always register a TXT, even if it is empty (so that clients are not
13505 // left waiting forever looking for a nonexistent record.)
13506 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13507 // then the default host name (m->MulticastHostname) is automatically used
13508 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
mDNS_RegisterService(mDNS * const m,ServiceRecordSet * sr,const domainlabel * const name,const domainname * const type,const domainname * const domain,const domainname * const host,mDNSIPPort port,RData * const txtrdata,const mDNSu8 txtinfo[],mDNSu16 txtlen,AuthRecord * SubTypes,mDNSu32 NumSubTypes,mDNSInterfaceID InterfaceID,mDNSServiceCallback Callback,void * Context,mDNSu32 flags)13509 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13510 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13511 const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13512 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13513 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13514 {
13515 mStatus err;
13516 mDNSu32 i;
13517 AuthRecType artype;
13518 mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13519
13520 sr->ServiceCallback = Callback;
13521 sr->ServiceContext = Context;
13522 sr->Conflict = mDNSfalse;
13523
13524 sr->Extras = mDNSNULL;
13525 sr->NumSubTypes = NumSubTypes;
13526 sr->SubTypes = SubTypes;
13527 sr->flags = flags;
13528
13529 artype = setAuthRecType(InterfaceID, flags);
13530
13531 // Initialize the AuthRecord objects to sane values
13532 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13533 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13534 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13535
13536 if (flags & kDNSServiceFlagsWakeOnlyService)
13537 {
13538 sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13539 }
13540
13541 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, recordType, artype, ServiceCallback, sr);
13542 mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr);
13543
13544 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13545 if (mDNSIPPortIsZero(port))
13546 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13547
13548 // If the caller is registering an oversized TXT record,
13549 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13550 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13551 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13552
13553 // Set up the record names
13554 // For now we only create an advisory record for the main type, not for subtypes
13555 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13556 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13557 return(mStatus_BadParamErr);
13558 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13559 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13560 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13561
13562 // 1. Set up the ADV record rdata to advertise our service type
13563 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13564
13565 // 2. Set up the PTR record rdata to point to our service name
13566 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13567 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13568 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13569 sr->RR_PTR.Additional1 = &sr->RR_SRV;
13570 sr->RR_PTR.Additional2 = &sr->RR_TXT;
13571
13572 // 2a. Set up any subtype PTRs to point to our service name
13573 // If the client is using subtypes, it is the client's responsibility to have
13574 // already set the first label of the record name to the subtype being registered
13575 for (i=0; i<NumSubTypes; i++)
13576 {
13577 domainname st;
13578 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13579 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13580 AppendDomainName(&st, type);
13581 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13582 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13583 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13584 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13585 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13586 }
13587
13588 // 3. Set up the SRV record rdata.
13589 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13590 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
13591 sr->RR_SRV.resrec.rdata->u.srv.port = port;
13592
13593 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13594 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13595 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13596
13597 // 4. Set up the TXT record rdata,
13598 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13599 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13600 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13601 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13602 {
13603 sr->RR_TXT.resrec.rdlength = txtlen;
13604 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13605 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13606 }
13607 sr->RR_TXT.DependentOn = &sr->RR_SRV;
13608
13609 mDNS_Lock(m);
13610 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13611 // that if the SRV cannot find a target, rest of the records that belong to this service
13612 // will not be activated.
13613 err = mDNS_Register_internal(m, &sr->RR_SRV);
13614 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13615 // any list and hence no need to deregister. We could probably do similar checks for other
13616 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13617 if (err)
13618 {
13619 mDNS_Unlock(m);
13620 return err;
13621 }
13622 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13623 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13624 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13625 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13626 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13627 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13628 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13629 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13630 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13631
13632 mDNS_Unlock(m);
13633
13634 if (err) mDNS_DeregisterService(m, sr);
13635 return(err);
13636 }
13637
mDNS_AddRecordToService(mDNS * const m,ServiceRecordSet * sr,ExtraResourceRecord * extra,RData * rdata,mDNSu32 ttl,mDNSu32 flags)13638 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13639 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags)
13640 {
13641 ExtraResourceRecord **e;
13642 mStatus status;
13643 AuthRecType artype;
13644 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13645 ResourceRecord *rr;
13646
13647 artype = setAuthRecType(InterfaceID, flags);
13648
13649 extra->next = mDNSNULL;
13650 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13651 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13652 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13653
13654 mDNS_Lock(m);
13655 rr = mDNSNULL;
13656 if (extra->r.resrec.rrtype == kDNSType_TXT)
13657 {
13658 if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec;
13659 }
13660 else if (extra->r.resrec.rrtype == kDNSType_SRV)
13661 {
13662 if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec;
13663 }
13664
13665 if (!rr)
13666 {
13667 ExtraResourceRecord *srExtra;
13668
13669 for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next)
13670 {
13671 if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask))
13672 {
13673 rr = &srExtra->r.resrec;
13674 break;
13675 }
13676 }
13677 }
13678
13679 if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl))
13680 {
13681 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13682 extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec));
13683 extra->r.resrec.rroriginalttl = rr->rroriginalttl;
13684 }
13685
13686 e = &sr->Extras;
13687 while (*e) e = &(*e)->next;
13688
13689 extra->r.DependentOn = &sr->RR_SRV;
13690
13691 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13692 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13693
13694 status = mDNS_Register_internal(m, &extra->r);
13695 if (status == mStatus_NoError) *e = extra;
13696
13697 mDNS_Unlock(m);
13698 return(status);
13699 }
13700
mDNS_RemoveRecordFromService(mDNS * const m,ServiceRecordSet * sr,ExtraResourceRecord * extra,mDNSRecordCallback MemFreeCallback,void * Context)13701 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13702 mDNSRecordCallback MemFreeCallback, void *Context)
13703 {
13704 ExtraResourceRecord **e;
13705 mStatus status;
13706
13707 mDNS_Lock(m);
13708 e = &sr->Extras;
13709 while (*e && *e != extra) e = &(*e)->next;
13710 if (!*e)
13711 {
13712 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13713 status = mStatus_BadReferenceErr;
13714 }
13715 else
13716 {
13717 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13718 extra->r.RecordCallback = MemFreeCallback;
13719 extra->r.RecordContext = Context;
13720 *e = (*e)->next;
13721 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13722 }
13723 mDNS_Unlock(m);
13724 return(status);
13725 }
13726
mDNS_RenameAndReregisterService(mDNS * const m,ServiceRecordSet * const sr,const domainlabel * newname)13727 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13728 {
13729 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13730 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13731 domainlabel name1, name2;
13732 domainname type, domain;
13733 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13734 ExtraResourceRecord *extras = sr->Extras;
13735 mStatus err;
13736
13737 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13738 if (!newname)
13739 {
13740 name2 = name1;
13741 IncrementLabelSuffix(&name2, mDNStrue);
13742 newname = &name2;
13743 }
13744
13745 if (SameDomainName(&domain, &localdomain))
13746 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13747 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13748
13749 // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13750 // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13751 if (sr->RR_TXT.NewRData) CompleteRDataUpdate(m, &sr->RR_TXT);
13752 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13753 host, sr->RR_SRV.resrec.rdata->u.srv.port,
13754 (sr->RR_TXT.resrec.rdata != &sr->RR_TXT.rdatastorage) ? sr->RR_TXT.resrec.rdata : mDNSNULL,
13755 sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13756 sr->SubTypes, sr->NumSubTypes,
13757 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13758
13759 // mDNS_RegisterService() just reset sr->Extras to NULL.
13760 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13761 // through the old list of extra records, and re-add them to our freshly created service registration
13762 while (!err && extras)
13763 {
13764 ExtraResourceRecord *e = extras;
13765 extras = extras->next;
13766 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13767 }
13768
13769 return(err);
13770 }
13771
13772 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13773 // which may change the record list and/or question list.
13774 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
mDNS_DeregisterService_drt(mDNS * const m,ServiceRecordSet * sr,mDNS_Dereg_type drt)13775 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13776 {
13777 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13778 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13779
13780 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13781 {
13782 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13783 return(mStatus_BadReferenceErr);
13784 }
13785 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13786 {
13787 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13788 // Avoid race condition:
13789 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13790 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13791 // If the client happens to deregister the service in the middle of that process, then
13792 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13793 // instead of incorrectly promoting it to mStatus_NameConflict.
13794 // This race condition is exposed particularly when the conformance test generates
13795 // a whole batch of simultaneous conflicts across a range of services all advertised
13796 // using the same system default name, and if we don't take this precaution then
13797 // we end up incrementing m->nicelabel multiple times instead of just once.
13798 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13799 sr->Conflict = mDNSfalse;
13800 return(mStatus_NoError);
13801 }
13802 else
13803 {
13804 mDNSu32 i;
13805 mStatus status;
13806 ExtraResourceRecord *e;
13807 mDNS_Lock(m);
13808 e = sr->Extras;
13809
13810 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13811 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13812 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13813 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13814 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13815
13816 // We deregister all of the extra records, but we leave the sr->Extras list intact
13817 // in case the client wants to do a RenameAndReregister and reinstate the registration
13818 while (e)
13819 {
13820 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13821 e = e->next;
13822 }
13823
13824 for (i=0; i<sr->NumSubTypes; i++)
13825 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13826
13827 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13828 mDNS_Unlock(m);
13829 return(status);
13830 }
13831 }
13832
13833 // Create a registration that asserts that no such service exists with this name.
13834 // This can be useful where there is a given function is available through several protocols.
13835 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13836 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13837 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13838 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
mDNS_RegisterNoSuchService(mDNS * const m,AuthRecord * const rr,const domainlabel * const name,const domainname * const type,const domainname * const domain,const domainname * const host,const mDNSInterfaceID InterfaceID,mDNSRecordCallback Callback,void * Context,mDNSu32 flags)13839 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13840 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13841 const domainname *const host,
13842 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13843 {
13844 AuthRecType artype;
13845
13846 artype = setAuthRecType(InterfaceID, flags);
13847
13848 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13849 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13850 rr->resrec.rdata->u.srv.priority = 0;
13851 rr->resrec.rdata->u.srv.weight = 0;
13852 rr->resrec.rdata->u.srv.port = zeroIPPort;
13853 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13854 else rr->AutoTarget = Target_AutoHost;
13855 return(mDNS_Register(m, rr));
13856 }
13857
mDNS_AdvertiseDomains(mDNS * const m,AuthRecord * rr,mDNS_DomainType DomainType,const mDNSInterfaceID InterfaceID,char * domname)13858 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13859 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13860 {
13861 AuthRecType artype;
13862
13863 if (InterfaceID == mDNSInterface_LocalOnly)
13864 artype = AuthRecordLocalOnly;
13865 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13866 artype = AuthRecordP2P;
13867 else
13868 artype = AuthRecordAny;
13869 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13870 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13871 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13872 return(mDNS_Register(m, rr));
13873 }
13874
mDNS_IdUsedInResourceRecordsList(mDNS * const m,mDNSOpaque16 id)13875 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13876 {
13877 AuthRecord *r;
13878 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13879 return mDNSfalse;
13880 }
13881
mDNS_IdUsedInQuestionsList(mDNS * const m,mDNSOpaque16 id)13882 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13883 {
13884 DNSQuestion *q;
13885 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13886 return mDNSfalse;
13887 }
13888
mDNS_NewMessageID(mDNS * const m)13889 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13890 {
13891 mDNSOpaque16 id;
13892 int i;
13893
13894 for (i=0; i<10; i++)
13895 {
13896 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13897 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13898 }
13899
13900 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13901
13902 return id;
13903 }
13904
13905 // ***************************************************************************
13906 #if COMPILER_LIKES_PRAGMA_MARK
13907 #pragma mark -
13908 #pragma mark - Sleep Proxy Server
13909 #endif
13910
RestartARPProbing(mDNS * const m,AuthRecord * const rr)13911 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13912 {
13913 // If we see an ARP from a machine we think is sleeping, then either
13914 // (i) the machine has woken, or
13915 // (ii) it's just a stray old packet from before the machine slept
13916 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13917 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13918 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13919 // 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*
13920 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13921 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13922
13923 rr->resrec.RecordType = kDNSRecordTypeUnique;
13924 rr->ProbeCount = DefaultProbeCountForTypeUnique;
13925 rr->ProbeRestartCount++;
13926
13927 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13928 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13929 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13930 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13931 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13932 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13933 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13934 InitializeLastAPTime(m, rr);
13935 else
13936 {
13937 rr->AnnounceCount = InitialAnnounceCount;
13938 rr->ThisAPInterval = mDNSPlatformOneSecond;
13939 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13940 SetNextAnnounceProbeTime(m, rr);
13941 }
13942 }
13943
mDNSCoreReceiveRawARP(mDNS * const m,const ARP_EthIP * const arp,const mDNSInterfaceID InterfaceID)13944 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13945 {
13946 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13947 AuthRecord *rr;
13948 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13949 if (!intf) return;
13950
13951 mDNS_Lock(m);
13952
13953 // Pass 1:
13954 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13955 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13956 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13957 // The times we might need to react to an ARP Announcement are:
13958 // (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
13959 // (ii) if it's a conflicting Announcement from another host
13960 // -- and we check for these in Pass 2 below.
13961 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13962 {
13963 for (rr = m->ResourceRecords; rr; rr=rr->next)
13964 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13965 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13966 {
13967 static const char msg1[] = "ARP Req from owner -- re-probing";
13968 static const char msg2[] = "Ignoring ARP Request from ";
13969 static const char msg3[] = "Creating Local ARP Cache entry ";
13970 static const char msg4[] = "Answering ARP Request from ";
13971 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13972 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13973 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
13974 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13975 intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b,
13976 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13977 if (msg == msg1)
13978 {
13979 if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13980 RestartARPProbing(m, rr);
13981 else
13982 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13983 }
13984 else if (msg == msg3)
13985 {
13986 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13987 }
13988 else if (msg == msg4)
13989 {
13990 SendARP(m, 2, rr, (mDNSv4Addr *)arp->tpa.b, &arp->sha, (mDNSv4Addr *)arp->spa.b, &arp->sha);
13991 }
13992 }
13993 }
13994
13995 // Pass 2:
13996 // 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.
13997 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13998 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13999 // 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.
14000 // If we see an apparently conflicting ARP, we check the sender hardware address:
14001 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
14002 // 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.
14003 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
14004 debugf("ARP from self for %.4a", arp->tpa.b);
14005 else
14006 {
14007 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
14008 for (rr = m->ResourceRecords; rr; rr=rr->next)
14009 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14010 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14011 {
14012 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14013 {
14014 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14015 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14016 }
14017 else
14018 {
14019 RestartARPProbing(m, rr);
14020 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
14021 {
14022 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
14023 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
14024 arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr));
14025 }
14026 else
14027 {
14028 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14029 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14030 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14031 }
14032 }
14033 }
14034 }
14035
14036 mDNS_Unlock(m);
14037 }
14038
14039 /*
14040 // Option 1 is Source Link Layer Address Option
14041 // Option 2 is Target Link Layer Address Option
14042 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14043 {
14044 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14045 while (options < end)
14046 {
14047 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14048 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14049 options += options[1] * 8;
14050 }
14051 return mDNSNULL;
14052 }
14053 */
14054
mDNSCoreReceiveRawND(mDNS * const m,const mDNSEthAddr * const sha,const mDNSv6Addr * spa,const IPv6NDP * const ndp,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID)14055 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
14056 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14057 {
14058 AuthRecord *rr;
14059 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
14060 if (!intf) return;
14061
14062 mDNS_Lock(m);
14063
14064 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14065 if (ndp->type == NDP_Sol)
14066 {
14067 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14068 (void)end;
14069 for (rr = m->ResourceRecords; rr; rr=rr->next)
14070 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14071 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
14072 {
14073 static const char msg1[] = "NDP Req from owner -- re-probing";
14074 static const char msg2[] = "Ignoring NDP Request from ";
14075 static const char msg3[] = "Creating Local NDP Cache entry ";
14076 static const char msg4[] = "Answering NDP Request from ";
14077 static const char msg5[] = "Answering NDP Probe from ";
14078 const char *const msg = mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
14079 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
14080 mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
14081 mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
14082 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14083 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14084 if (msg == msg1)
14085 {
14086 if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
14087 RestartARPProbing(m, rr);
14088 else
14089 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
14090 }
14091 else if (msg == msg3)
14092 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14093 else if (msg == msg4)
14094 SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
14095 else if (msg == msg5)
14096 SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
14097 }
14098 }
14099
14100 // 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.
14101 if (mDNSSameEthAddress(sha, &intf->MAC))
14102 debugf("NDP from self for %.16a", &ndp->target);
14103 else
14104 {
14105 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14106 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14107 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14108 // Hence it is the NDP target address we care about, not the actual packet source address.
14109 if (ndp->type == NDP_Adv) spa = &ndp->target;
14110 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
14111 for (rr = m->ResourceRecords; rr; rr=rr->next)
14112 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14113 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14114 {
14115 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14116 {
14117 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14118 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14119 }
14120 else
14121 {
14122 RestartARPProbing(m, rr);
14123 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
14124 {
14125 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
14126 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
14127 }
14128 else
14129 {
14130 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14131 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14132 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14133 }
14134 }
14135 }
14136 }
14137
14138 mDNS_Unlock(m);
14139 }
14140
mDNSCoreReceiveRawTransportPacket(mDNS * const m,const mDNSEthAddr * const sha,const mDNSAddr * const src,const mDNSAddr * const dst,const mDNSu8 protocol,const mDNSu8 * const p,const TransportLayerPacket * const t,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID,const mDNSu16 len)14141 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
14142 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
14143 {
14144 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
14145 mDNSBool wake = mDNSfalse;
14146 mDNSBool kaWake = mDNSfalse;
14147
14148 switch (protocol)
14149 {
14150 #define XX wake ? "Received" : "Ignoring", end-p
14151 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
14152 break;
14153
14154 case 0x06: {
14155 AuthRecord *kr;
14156 mDNSu32 seq, ack;
14157 #define TH_FIN 0x01
14158 #define TH_SYN 0x02
14159 #define TH_RST 0x04
14160 #define TH_ACK 0x10
14161
14162 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
14163 if (kr)
14164 {
14165 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
14166 // Plan to wake if
14167 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14168 // (b) packet that contains new data and acks a sequence number higher than the one
14169 // we have been sending in the keepalive
14170
14171 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
14172 if (!wake)
14173 {
14174 mDNSu8 *ptr;
14175 mDNSu32 pseq, pack;
14176 mDNSBool data = mDNSfalse;
14177 mDNSu8 tcphlen;
14178
14179 // Convert to host order
14180 ptr = (mDNSu8 *)&seq;
14181 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14182
14183 ptr = (mDNSu8 *)&ack;
14184 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14185
14186 pseq = t->tcp.seq;
14187 ptr = (mDNSu8 *)&pseq;
14188 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14189
14190 pack = t->tcp.ack;
14191 ptr = (mDNSu8 *)&pack;
14192 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14193
14194 // If the other side is acking one more than our sequence number (keepalive is one
14195 // less than the last valid sequence sent) and it's sequence is more than what we
14196 // acked before
14197 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14198 tcphlen = ((t->tcp.offset >> 4) * 4);
14199 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
14200 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
14201
14202 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14203 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
14204 ((int)(ack - pseq) == 1))
14205 {
14206 // Send an ACK;
14207 mDNS_SendKeepaliveACK(m, kr);
14208 }
14209 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14210 end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
14211 }
14212 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
14213 kaWake = wake;
14214 }
14215 else
14216 {
14217 // Plan to wake if
14218 // (a) RST is not set, AND
14219 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14220 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
14221
14222 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14223 // except for ssh connections, where we'll wake for plain data packets too
14224 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
14225
14226 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
14227 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
14228 (t->tcp.flags & 2) ? " SYN" : "",
14229 (t->tcp.flags & 1) ? " FIN" : "",
14230 (t->tcp.flags & 4) ? " RST" : "");
14231 }
14232 break;
14233 }
14234
14235 case 0x11: {
14236 #define ARD_AsNumber 3283
14237 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
14238 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
14239 if (udplen >= sizeof(UDPHeader))
14240 {
14241 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
14242 wake = mDNStrue;
14243
14244 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14245 if (mDNSSameIPPort(port, IPSECPort))
14246 {
14247 // Specifically ignore NAT keepalive packets
14248 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14249 else
14250 {
14251 // Skip over the Non-ESP Marker if present
14252 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14253 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
14254 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14255 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14256 if ((ike->Version & 0x10) == 0x10)
14257 {
14258 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14259 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14260 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14261 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14262 }
14263 }
14264 }
14265
14266 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14267 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14268 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14269 // UDP header (8 bytes)
14270 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14271 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14272
14273 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14274 }
14275 }
14276 break;
14277
14278 case 0x3A: if (&t->bytes[len] <= end)
14279 {
14280 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14281 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14282 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14283 }
14284 break;
14285
14286 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14287 break;
14288 }
14289
14290 if (wake)
14291 {
14292 AuthRecord *rr, *r2;
14293
14294 mDNS_Lock(m);
14295 for (rr = m->ResourceRecords; rr; rr=rr->next)
14296 if (rr->resrec.InterfaceID == InterfaceID &&
14297 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14298 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14299 {
14300 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14301 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14302 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14303 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14304 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14305 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14306 break;
14307 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14308 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record
14309 if (r2)
14310 {
14311 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14312 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14313 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14314 }
14315 else
14316 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14317 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14318 }
14319 mDNS_Unlock(m);
14320 }
14321 }
14322
mDNSCoreReceiveRawPacket(mDNS * const m,const mDNSu8 * const p,const mDNSu8 * const end,const mDNSInterfaceID InterfaceID)14323 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14324 {
14325 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14326 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14327 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14328 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14329 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14330
14331 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14332 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14333 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14334 // since it points to a an address 14 bytes before pkt.
14335 const EthernetHeader *const eth = (const EthernetHeader *)p;
14336 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14337 mDNSAddr src, dst;
14338 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14339
14340 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14341 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14342 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14343 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14344 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14345 {
14346 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14347 const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14348 if (transEnd > end) transEnd = end;
14349 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src.b, &pkt->v4.dst.b);
14350 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14351 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14352 if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14353 mDNSCoreReceiveRawTransportPacket(m, ð->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14354 }
14355 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14356 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14357 {
14358 const mDNSu8 *const trans = p + 54;
14359 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src.b, &pkt->v6.dst.b);
14360 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14361 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14362 if (end >= trans + RequiredCapLen(pkt->v6.pro))
14363 mDNSCoreReceiveRawTransportPacket(m, ð->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14364 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14365 }
14366 }
14367
ConstructSleepProxyServerName(mDNS * const m,domainlabel * name)14368 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14369 {
14370 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14371 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14372 }
14373
14374 #ifndef SPC_DISABLED
SleepProxyServerCallback(mDNS * const m,ServiceRecordSet * const srs,mStatus result)14375 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14376 {
14377 if (result == mStatus_NameConflict)
14378 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14379 else if (result == mStatus_MemFree)
14380 {
14381 if (m->SleepState)
14382 m->SPSState = 3;
14383 else
14384 {
14385 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14386 if (m->SPSState)
14387 {
14388 domainlabel name;
14389 ConstructSleepProxyServerName(m, &name);
14390 mDNS_RegisterService(m, srs,
14391 &name, &SleepProxyServiceType, &localdomain,
14392 mDNSNULL, m->SPSSocket->port, // Host, port
14393 mDNSNULL,
14394 (mDNSu8 *)"", 1, // TXT data, length
14395 mDNSNULL, 0, // Subtypes (none)
14396 mDNSInterface_Any, // Interface ID
14397 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14398 }
14399 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14400 }
14401 }
14402 }
14403 #endif
14404
14405 // Called with lock held
mDNSCoreBeSleepProxyServer_internal(mDNS * const m,mDNSu8 sps,mDNSu8 port,mDNSu8 marginalpower,mDNSu8 totpower,mDNSu8 features)14406 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14407 {
14408 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14409 mDNS_DropLockBeforeCallback();
14410
14411 // If turning off SPS, close our socket
14412 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14413 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14414
14415 // If turning off, or changing type, deregister old name
14416 #ifndef SPC_DISABLED
14417 if (m->SPSState == 1 && sps != m->SPSType)
14418 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14419 #endif // SPC_DISABLED
14420
14421 // Record our new SPS parameters
14422 m->SPSType = sps;
14423 m->SPSPortability = port;
14424 m->SPSMarginalPower = marginalpower;
14425 m->SPSTotalPower = totpower;
14426 m->SPSFeatureFlags = features;
14427 // If turning on, open socket and advertise service
14428 if (sps)
14429 {
14430 if (!m->SPSSocket)
14431 {
14432 m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort);
14433 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14434 }
14435 #ifndef SPC_DISABLED
14436 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14437 #endif // SPC_DISABLED
14438 }
14439 else if (m->SPSState)
14440 {
14441 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14442 m->NextScheduledSPS = m->timenow;
14443 }
14444 fail:
14445 mDNS_ReclaimLockAfterCallback();
14446 }
14447
14448 // ***************************************************************************
14449 #if COMPILER_LIKES_PRAGMA_MARK
14450 #pragma mark -
14451 #pragma mark - Startup and Shutdown
14452 #endif
14453
mDNS_GrowCache_internal(mDNS * const m,CacheEntity * storage,mDNSu32 numrecords)14454 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14455 {
14456 if (storage && numrecords)
14457 {
14458 mDNSu32 i;
14459 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14460 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14461 storage[numrecords-1].next = m->rrcache_free;
14462 m->rrcache_free = storage;
14463 m->rrcache_size += numrecords;
14464 }
14465 }
14466
mDNS_GrowCache(mDNS * const m,CacheEntity * storage,mDNSu32 numrecords)14467 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14468 {
14469 mDNS_Lock(m);
14470 mDNS_GrowCache_internal(m, storage, numrecords);
14471 mDNS_Unlock(m);
14472 }
14473
mDNS_InitStorage(mDNS * const m,mDNS_PlatformSupport * const p,CacheEntity * rrcachestorage,mDNSu32 rrcachesize,mDNSBool AdvertiseLocalAddresses,mDNSCallback * Callback,void * Context)14474 mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p,
14475 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14476 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14477 {
14478 mDNSu32 slot;
14479 mDNSs32 timenow;
14480 mStatus result;
14481
14482 if (!rrcachestorage) rrcachesize = 0;
14483
14484 m->p = p;
14485 m->NetworkChanged = 0;
14486 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14487 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
14488 m->DivertMulticastAdvertisements = mDNSfalse;
14489 m->mDNSPlatformStatus = mStatus_Waiting;
14490 m->UnicastPort4 = zeroIPPort;
14491 m->UnicastPort6 = zeroIPPort;
14492 m->PrimaryMAC = zeroEthAddr;
14493 m->MainCallback = Callback;
14494 m->MainContext = Context;
14495 m->rec.r.resrec.RecordType = 0;
14496
14497 // For debugging: To catch and report locking failures
14498 m->mDNS_busy = 0;
14499 m->mDNS_reentrancy = 0;
14500 m->ShutdownTime = 0;
14501 m->lock_rrcache = 0;
14502 m->lock_Questions = 0;
14503 m->lock_Records = 0;
14504
14505 // Task Scheduling variables
14506 result = mDNSPlatformTimeInit();
14507 if (result != mStatus_NoError) return(result);
14508 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14509 timenow = mDNS_TimeNow_NoLock(m);
14510
14511 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14512 m->timenow_last = timenow;
14513 m->NextScheduledEvent = timenow;
14514 m->SuppressSending = timenow;
14515 m->NextCacheCheck = timenow + FutureTime;
14516 m->NextScheduledQuery = timenow + FutureTime;
14517 m->NextScheduledProbe = timenow + FutureTime;
14518 m->NextScheduledResponse = timenow + FutureTime;
14519 m->NextScheduledNATOp = timenow + FutureTime;
14520 m->NextScheduledSPS = timenow + FutureTime;
14521 m->NextScheduledKA = timenow + FutureTime;
14522 m->NextScheduledStopTime = timenow + FutureTime;
14523 m->NextBLEServiceTime = 0; // zero indicates inactive
14524
14525 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14526 m->NextBonjourDisableTime = 0; // Timer active when non zero.
14527 m->BonjourEnabled = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14528 #endif
14529
14530 m->RandomQueryDelay = 0;
14531 m->RandomReconfirmDelay = 0;
14532 m->PktNum = 0;
14533 m->MPktNum = 0;
14534 m->LocalRemoveEvents = mDNSfalse;
14535 m->SleepState = SleepState_Awake;
14536 m->SleepSeqNum = 0;
14537 m->SystemWakeOnLANEnabled = mDNSfalse;
14538 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14539 m->DelaySleep = 0;
14540 m->SleepLimit = 0;
14541
14542 #if APPLE_OSX_mDNSResponder
14543 m->UnicastPacketsSent = 0;
14544 m->MulticastPacketsSent = 0;
14545 m->RemoteSubnet = 0;
14546 #endif // APPLE_OSX_mDNSResponder
14547
14548 // These fields only required for mDNS Searcher...
14549 m->Questions = mDNSNULL;
14550 m->NewQuestions = mDNSNULL;
14551 m->CurrentQuestion = mDNSNULL;
14552 m->LocalOnlyQuestions = mDNSNULL;
14553 m->NewLocalOnlyQuestions = mDNSNULL;
14554 m->RestartQuestion = mDNSNULL;
14555 m->rrcache_size = 0;
14556 m->rrcache_totalused = 0;
14557 m->rrcache_active = 0;
14558 m->rrcache_report = 10;
14559 m->rrcache_free = mDNSNULL;
14560
14561 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14562 {
14563 m->rrcache_hash[slot] = mDNSNULL;
14564 m->rrcache_nextcheck[slot] = timenow + FutureTime;;
14565 }
14566
14567 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14568 m->rrauth.rrauth_free = mDNSNULL;
14569
14570 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14571 m->rrauth.rrauth_hash[slot] = mDNSNULL;
14572
14573 // Fields below only required for mDNS Responder...
14574 m->hostlabel.c[0] = 0;
14575 m->nicelabel.c[0] = 0;
14576 m->MulticastHostname.c[0] = 0;
14577 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14578 m->RandomizedHostname.c[0] = 0;
14579 #endif
14580 m->HIHardware.c[0] = 0;
14581 m->HISoftware.c[0] = 0;
14582 m->ResourceRecords = mDNSNULL;
14583 m->DuplicateRecords = mDNSNULL;
14584 m->NewLocalRecords = mDNSNULL;
14585 m->NewLocalOnlyRecords = mDNSfalse;
14586 m->CurrentRecord = mDNSNULL;
14587 m->HostInterfaces = mDNSNULL;
14588 m->ProbeFailTime = 0;
14589 m->NumFailedProbes = 0;
14590 m->SuppressProbes = 0;
14591
14592 #ifndef UNICAST_DISABLED
14593 m->NextuDNSEvent = timenow + FutureTime;
14594 m->NextSRVUpdate = timenow + FutureTime;
14595
14596 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14597 m->DNSServers = mDNSNULL;
14598 #endif
14599
14600 m->Router = zeroAddr;
14601 m->AdvertisedV4 = zeroAddr;
14602 m->AdvertisedV6 = zeroAddr;
14603
14604 m->AuthInfoList = mDNSNULL;
14605
14606 m->ReverseMap.ThisQInterval = -1;
14607 m->StaticHostname.c[0] = 0;
14608 m->FQDN.c[0] = 0;
14609 m->Hostnames = mDNSNULL;
14610
14611 m->WABBrowseQueriesCount = 0;
14612 m->WABLBrowseQueriesCount = 0;
14613 m->WABRegQueriesCount = 0;
14614 m->AutoTargetServices = 0;
14615
14616 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14617 m->NumAllInterfaceRecords = 0;
14618 m->NumAllInterfaceQuestions = 0;
14619 #endif
14620 // NAT traversal fields
14621 m->LLQNAT.clientCallback = mDNSNULL;
14622 m->LLQNAT.clientContext = mDNSNULL;
14623 m->NATTraversals = mDNSNULL;
14624 m->CurrentNATTraversal = mDNSNULL;
14625 m->retryIntervalGetAddr = 0; // delta between time sent and retry
14626 m->retryGetAddr = timenow + FutureTime; // absolute time when we retry
14627 m->ExtAddress = zerov4Addr;
14628 m->PCPNonce[0] = mDNSRandom(-1);
14629 m->PCPNonce[1] = mDNSRandom(-1);
14630 m->PCPNonce[2] = mDNSRandom(-1);
14631
14632 m->NATMcastRecvskt = mDNSNULL;
14633 m->LastNATupseconds = 0;
14634 m->LastNATReplyLocalTime = timenow;
14635 m->LastNATMapResultCode = NATErr_None;
14636
14637 m->UPnPInterfaceID = 0;
14638 m->SSDPSocket = mDNSNULL;
14639 m->SSDPWANPPPConnection = mDNSfalse;
14640 m->UPnPRouterPort = zeroIPPort;
14641 m->UPnPSOAPPort = zeroIPPort;
14642 m->UPnPRouterURL = mDNSNULL;
14643 m->UPnPWANPPPConnection = mDNSfalse;
14644 m->UPnPSOAPURL = mDNSNULL;
14645 m->UPnPRouterAddressString = mDNSNULL;
14646 m->UPnPSOAPAddressString = mDNSNULL;
14647 m->SPSType = 0;
14648 m->SPSPortability = 0;
14649 m->SPSMarginalPower = 0;
14650 m->SPSTotalPower = 0;
14651 m->SPSFeatureFlags = 0;
14652 m->SPSState = 0;
14653 m->SPSProxyListChanged = mDNSNULL;
14654 m->SPSSocket = mDNSNULL;
14655 m->SPSBrowseCallback = mDNSNULL;
14656 m->ProxyRecords = 0;
14657
14658 m->DNSPushServers = mDNSNULL;
14659 m->DNSPushZones = mDNSNULL;
14660 #endif
14661
14662 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14663 if (WCFConnectionNew)
14664 {
14665 m->WCF = WCFConnectionNew();
14666 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14667 }
14668 #endif
14669
14670 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
14671 result = init_and_load_trust_anchors();
14672 if (result != mStatus_NoError) return(result);
14673 #endif
14674
14675 return(result);
14676 }
14677
mDNS_Init(mDNS * const m,mDNS_PlatformSupport * const p,CacheEntity * rrcachestorage,mDNSu32 rrcachesize,mDNSBool AdvertiseLocalAddresses,mDNSCallback * Callback,void * Context)14678 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14679 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14680 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14681 {
14682 mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context);
14683 if (result != mStatus_NoError)
14684 return(result);
14685
14686 #if MDNS_MALLOC_DEBUGGING
14687 static mDNSListValidator lv;
14688 mDNSPlatformAddListValidator(&lv, mDNS_ValidateLists, "mDNS_ValidateLists", m);
14689 #endif
14690 result = mDNSPlatformInit(m);
14691
14692 #ifndef UNICAST_DISABLED
14693 // It's better to do this *after* the platform layer has set up the
14694 // interface list and security credentials
14695 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
14696 #endif
14697
14698 return(result);
14699 }
14700
mDNS_ConfigChanged(mDNS * const m)14701 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14702 {
14703 if (m->SPSState == 1)
14704 {
14705 domainlabel name, newname;
14706 #ifndef SPC_DISABLED
14707 domainname type, domain;
14708 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14709 #endif // SPC_DISABLED
14710 ConstructSleepProxyServerName(m, &newname);
14711 if (!SameDomainLabelCS(name.c, newname.c))
14712 {
14713 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14714 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14715 // it will reregister the service under the new name
14716 m->SPSState = 2;
14717 #ifndef SPC_DISABLED
14718 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14719 #endif // SPC_DISABLED
14720 }
14721 }
14722
14723 if (m->MainCallback)
14724 m->MainCallback(m, mStatus_ConfigChanged);
14725 }
14726
DynDNSHostNameCallback(mDNS * const m,AuthRecord * const rr,mStatus result)14727 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14728 {
14729 (void)m; // unused
14730 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14731 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14732 }
14733
14734 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
PurgeOrReconfirmCacheRecord(mDNS * const m,CacheRecord * cr)14735 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr)
14736 {
14737 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14738 cr->resrec.rrtype == kDNSType_A ||
14739 cr->resrec.rrtype == kDNSType_AAAA ||
14740 cr->resrec.rrtype == kDNSType_SRV ||
14741 cr->resrec.rrtype == kDNSType_CNAME;
14742
14743 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14744 purge ? "purging" : "reconfirming",
14745 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
14746 cr->resrec.rDNSServer ? mDNSVal16(cr->resrec.rDNSServer->port) : -1,
14747 cr->resrec.rDNSServer ? cr->resrec.rDNSServer->domain.c : mDNSNULL, CRDisplayString(m, cr));
14748
14749 if (purge)
14750 {
14751 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14752 mDNS_PurgeCacheResourceRecord(m, cr);
14753 }
14754 else
14755 {
14756 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14757 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14758 }
14759 }
14760 #endif
14761
mDNS_PurgeBeforeResolve(mDNS * const m,DNSQuestion * q)14762 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
14763 {
14764 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14765 CacheRecord *rp;
14766 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14767 {
14768 if (SameNameCacheRecordAnswersQuestion(rp, q))
14769 {
14770 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
14771 mDNS_PurgeCacheResourceRecord(m, rp);
14772 }
14773 }
14774 }
14775
14776 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
DNSServerChangeForQuestion(mDNS * const m,DNSQuestion * q,DNSServer * new)14777 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14778 {
14779 DNSQuestion *qptr;
14780
14781 (void) m;
14782
14783 if (q->DuplicateOf)
14784 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14785
14786 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14787 // of events for all of them are consistent. Duplicates for a question are always inserted
14788 // after in the list.
14789 q->qDNSServer = new;
14790 for (qptr = q->next ; qptr; qptr = qptr->next)
14791 {
14792 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14793 }
14794 }
14795 #endif
14796
SetConfigState(mDNS * const m,mDNSBool delete)14797 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14798 {
14799 McastResolver *mr;
14800 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14801 DNSServer *ptr;
14802 #endif
14803
14804 if (delete)
14805 {
14806 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14807 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14808 {
14809 ptr->penaltyTime = 0;
14810 ptr->flags |= DNSServerFlag_Delete;
14811 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14812 if (ptr->flags & DNSServerFlag_Unreachable)
14813 NumUnreachableDNSServers--;
14814 #endif
14815 }
14816 #endif
14817 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14818 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14819 // API
14820 for (mr = m->McastResolvers; mr; mr = mr->next)
14821 mr->flags |= McastResolver_FlagDelete;
14822 }
14823 else
14824 {
14825 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14826 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14827 {
14828 ptr->penaltyTime = 0;
14829 ptr->flags &= ~DNSServerFlag_Delete;
14830 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14831 if (ptr->flags & DNSServerFlag_Unreachable)
14832 NumUnreachableDNSServers++;
14833 #endif
14834 }
14835 #endif
14836 for (mr = m->McastResolvers; mr; mr = mr->next)
14837 mr->flags &= ~McastResolver_FlagDelete;
14838 }
14839 }
14840
SetDynDNSHostNameIfChanged(mDNS * const m,domainname * const fqdn)14841 mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn)
14842 {
14843 // Did our FQDN change?
14844 if (!SameDomainName(fqdn, &m->FQDN))
14845 {
14846 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14847
14848 AssignDomainName(&m->FQDN, fqdn);
14849
14850 if (m->FQDN.c[0])
14851 {
14852 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14853 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14854 }
14855 }
14856 }
14857
14858 // Even though this is called “Setup” it is not called just once at startup.
14859 // It’s actually called multiple times, every time there’s a configuration change.
uDNS_SetupDNSConfig(mDNS * const m)14860 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14861 {
14862 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14863 mDNSu32 slot;
14864 CacheGroup *cg;
14865 CacheRecord *cr;
14866 #endif
14867 mDNSAddr v4, v6, r;
14868 domainname fqdn;
14869 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14870 DNSServer *ptr, **p = &m->DNSServers;
14871 const DNSServer *oldServers = m->DNSServers;
14872 DNSQuestion *q;
14873 #endif
14874 McastResolver *mr, **mres = &m->McastResolvers;
14875 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14876 DNSPushNotificationServer **psp;
14877 #endif
14878
14879 debugf("uDNS_SetupDNSConfig: entry");
14880
14881 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14882 uDNS_SetupWABQueries(m);
14883
14884 mDNS_Lock(m);
14885
14886 // We need to first mark all the entries to be deleted. If the configuration changed, then
14887 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14888 //
14889 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14890 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14891 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14892 // for the dns configuration change notification.
14893 SetConfigState(m, mDNStrue);
14894 if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14895 {
14896 SetDynDNSHostNameIfChanged(m, &fqdn);
14897 SetConfigState(m, mDNSfalse);
14898 mDNS_Unlock(m);
14899 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14900 return mStatus_NoError;
14901 }
14902
14903 // For now, we just delete the mcast resolvers. We don't deal with cache or
14904 // questions here. Neither question nor cache point to mcast resolvers. Questions
14905 // do inherit the timeout values from mcast resolvers. But we don't bother
14906 // affecting them as they never change.
14907 while (*mres)
14908 {
14909 if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14910 {
14911 mr = *mres;
14912 *mres = (*mres)->next;
14913 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14914 mDNSPlatformMemFree(mr);
14915 }
14916 else
14917 {
14918 (*mres)->flags &= ~McastResolver_FlagNew;
14919 mres = &(*mres)->next;
14920 }
14921 }
14922
14923 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14924 Querier_ProcessDNSServiceChanges();
14925 #else
14926 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14927 //
14928 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14929 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14930 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14931 // DNSServers and flush the cache.
14932 //
14933 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14934 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14935 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14936 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14937 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14938 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14939 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14940 // the same resGroupID.
14941 //
14942 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14943 // of the old followed by ADD of the new records.
14944 //
14945 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14946 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14947 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14948 //
14949 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14950 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14951 // non-scoped question and vice versa.
14952 //
14953 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14954 DNS64RestartQuestions(m);
14955 #endif
14956
14957 // First, restart questions whose suppression status will change. The suppression status of each question in a given
14958 // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14959 // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14960 // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14961 // suppressed (or non-suppressed).
14962 for (q = m->Questions; q; q = q->next)
14963 {
14964 DNSServer *s;
14965 const DNSServer *t;
14966 mDNSBool oldSuppressed;
14967
14968 if (mDNSOpaque16IsZero(q->TargetQID)) continue;
14969
14970 SetValidDNSServers(m, q);
14971 q->triedAllServersOnce = mDNSfalse;
14972 s = GetServerForQuestion(m, q);
14973 t = q->qDNSServer;
14974 if (s != t)
14975 {
14976 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
14977 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR ":%d (" PRI_DM_NAME ") to "
14978 PRI_IP_ADDR ":%d (" PRI_DM_NAME ") for question " PRI_DM_NAME " (" PUB_S ") (scope:%p)",
14979 q->request_id, mDNSVal16(q->TargetQID),
14980 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), DM_NAME_PARAM(t ? &t->domain : mDNSNULL),
14981 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), DM_NAME_PARAM(s ? &s->domain : mDNSNULL),
14982 DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->InterfaceID);
14983 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14984 // If this question had a DNS Push server associated with it, substitute the new server for the
14985 // old one. If there is no new server, then we'll clean up the push server later.
14986 if (!q->DuplicateOf && (q->dnsPushServer != mDNSNULL))
14987 {
14988 if (q->dnsPushServer->qDNSServer == t)
14989 {
14990 q->dnsPushServer->qDNSServer = s; // which might be null
14991 }
14992 // If it is null, do the accounting and drop the push server.
14993 if (q->dnsPushServer->qDNSServer == mDNSNULL)
14994 {
14995 DNSPushReconcileConnection(m, q);
14996 }
14997 }
14998 #endif
14999 }
15000 oldSuppressed = q->Suppressed;
15001 q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15002 if (!q->Suppressed != !oldSuppressed) q->Restart = mDNStrue;
15003 }
15004 RestartUnicastQuestions(m);
15005
15006 // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
15007 // have already had their server changed by being restarted.
15008 for (q = m->Questions; q; q = q->next)
15009 {
15010 DNSServer *s;
15011 const DNSServer *t;
15012
15013 if (mDNSOpaque16IsZero(q->TargetQID) || q->DuplicateOf) continue;
15014
15015 SetValidDNSServers(m, q);
15016 q->triedAllServersOnce = mDNSfalse;
15017 s = GetServerForQuestion(m, q);
15018 t = q->qDNSServer;
15019 DNSServerChangeForQuestion(m, q, s);
15020 if (s == t) continue;
15021
15022 q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15023 q->unansweredQueries = 0;
15024 q->TargetQID = mDNS_NewMessageID(m);
15025 if (!q->Suppressed) ActivateUnicastQuery(m, q, mDNStrue);
15026 }
15027
15028 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15029 // The above code may have found some DNS Push servers that are no longer valid. Now that we
15030 // are done running through the code, we need to drop our connections to those servers.
15031 // When we get here, any such servers should have zero questions associated with them.
15032 for (psp = &m->DNSPushServers; *psp != mDNSNULL; )
15033 {
15034 DNSPushNotificationServer *server = *psp;
15035
15036 // It's possible that a push server whose DNS server has been deleted could be still connected but
15037 // not referenced by any questions. In this case, we just delete the push server rather than trying
15038 // to figure out with which DNS server (if any) to associate it.
15039 if (server->qDNSServer != mDNSNULL && server->qDNSServer->flags & DNSServerFlag_Delete)
15040 {
15041 server->qDNSServer = mDNSNULL;
15042 }
15043
15044 if (server->qDNSServer == mDNSNULL)
15045 {
15046 // This would be a programming error, so should never happen.
15047 if (server->numberOfQuestions != 0)
15048 {
15049 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server->serverName);
15050 }
15051 DNSPushServerDrop(server);
15052 *psp = server->next;
15053 mDNSPlatformMemFree(server);
15054 }
15055 else
15056 {
15057 psp = &(*psp)->next;
15058 }
15059 }
15060 #endif
15061
15062 FORALL_CACHERECORDS(slot, cg, cr)
15063 {
15064 if (cr->resrec.InterfaceID) continue;
15065
15066 // We already walked the questions and restarted/reactivated them if the dns server
15067 // change affected the question. That should take care of updating the cache. But
15068 // what if there is no active question at this point when the DNS server change
15069 // happened ? There could be old cache entries lying around and if we don't flush
15070 // them, a new question after the DNS server change could pick up these stale
15071 // entries and get a wrong answer.
15072 //
15073 // For cache entries that have active questions we might have skipped rescheduling
15074 // the questions if they were suppressed (see above). To keep it simple, we walk
15075 // all the cache entries to make sure that there are no stale entries. We use the
15076 // active question's InterfaceID/ServiceID for looking up the right DNS server.
15077 //
15078 // Note: If GetServerForName returns NULL, it could either mean that there are no
15079 // DNS servers or no matching DNS servers for this question. In either case,
15080 // the cache should get purged below when we process deleted DNS servers.
15081
15082 if (cr->CRActiveQuestion)
15083 {
15084 // Purge or Reconfirm if this cache entry would use the new DNS server
15085 ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion->InterfaceID, cr->CRActiveQuestion->ServiceID);
15086 if (ptr && (ptr != cr->resrec.rDNSServer))
15087 {
15088 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15089 CRDisplayString(m, cr), &ptr->addr,
15090 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL);
15091 PurgeOrReconfirmCacheRecord(m, cr);
15092
15093 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15094 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15095 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion->qDNSServer)
15096 {
15097 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->CRActiveQuestion->qDNSServer->addr, CRDisplayString(m, cr));
15098 cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer;
15099 }
15100 }
15101
15102 if (cr->resrec.rDNSServer && cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15103 {
15104 DNSQuestion *qptr = cr->CRActiveQuestion;
15105 if (qptr->qDNSServer == cr->resrec.rDNSServer)
15106 {
15107 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15108 " to be freed", CRDisplayString(m, cr),
15109 qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15110 &cr->resrec.rDNSServer->addr);
15111 qptr->validDNSServers = zeroOpaque128;
15112 qptr->qDNSServer = mDNSNULL;
15113 cr->resrec.rDNSServer = mDNSNULL;
15114 }
15115 else
15116 {
15117 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15118 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr),
15119 qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15120 &cr->resrec.rDNSServer->addr,
15121 qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL);
15122 cr->resrec.rDNSServer = qptr->qDNSServer;
15123 }
15124 PurgeOrReconfirmCacheRecord(m, cr);
15125 }
15126 }
15127 else if (!cr->resrec.rDNSServer || cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15128 {
15129 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
15130 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S ", DNS server " PUB_S " " PRI_IP_ADDR " " PUB_S,
15131 CRDisplayString(m, cr), !cr->resrec.rDNSServer ? "(to be deleted)" : "",
15132 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
15133 cr->resrec.rDNSServer ? DNSScopeToString(cr->resrec.rDNSServer->scopeType) : "" );
15134 cr->resrec.rDNSServer = mDNSNULL;
15135 mDNS_PurgeCacheResourceRecord(m, cr);
15136 }
15137 }
15138
15139 // Delete all the DNS servers that are flagged for deletion
15140 while (*p)
15141 {
15142 if (((*p)->flags & DNSServerFlag_Delete) != 0)
15143 {
15144 ptr = *p;
15145 *p = (*p)->next;
15146 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
15147 mDNSPlatformMemFree(ptr);
15148 }
15149 else
15150 {
15151 p = &(*p)->next;
15152 }
15153 }
15154 LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m));
15155
15156 // 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).
15157 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15158 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15159 // 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.
15160 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
15161 {
15162 int count = 0;
15163 FORALL_CACHERECORDS(slot, cg, cr)
15164 {
15165 if (!cr->resrec.InterfaceID)
15166 {
15167 mDNS_PurgeCacheResourceRecord(m, cr);
15168 count++;
15169 }
15170 }
15171 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15172 m->DNSServers ? "DNS server became" : "No DNS servers", count);
15173
15174 // Force anything that needs to get zone data to get that information again
15175 RestartRecordGetZoneData(m);
15176 }
15177 #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
15178
15179 SetDynDNSHostNameIfChanged(m, &fqdn);
15180
15181 mDNS_Unlock(m);
15182
15183 // handle router and primary interface changes
15184 v4 = v6 = r = zeroAddr;
15185 v4.type = r.type = mDNSAddrType_IPv4;
15186
15187 if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
15188 {
15189 mDNS_SetPrimaryInterfaceInfo(m,
15190 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
15191 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
15192 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL);
15193 }
15194 else
15195 {
15196 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
15197 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
15198 }
15199
15200 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m));
15201 return mStatus_NoError;
15202 }
15203
mDNSCoreInitComplete(mDNS * const m,mStatus result)15204 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
15205 {
15206 m->mDNSPlatformStatus = result;
15207 if (m->MainCallback)
15208 {
15209 mDNS_Lock(m);
15210 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15211 m->MainCallback(m, mStatus_NoError);
15212 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15213 mDNS_Unlock(m);
15214 }
15215 }
15216
DeregLoop(mDNS * const m,AuthRecord * const start)15217 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
15218 {
15219 m->CurrentRecord = start;
15220 while (m->CurrentRecord)
15221 {
15222 AuthRecord *rr = m->CurrentRecord;
15223 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15224 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
15225 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15226 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15227 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15228 else if (rr->AnnounceCount > 1)
15229 {
15230 rr->AnnounceCount = 1;
15231 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15232 }
15233 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15234 // new records could have been added to the end of the list as a result of that call.
15235 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15236 m->CurrentRecord = rr->next;
15237 }
15238 }
15239
mDNS_StartExit(mDNS * const m)15240 mDNSexport void mDNS_StartExit(mDNS *const m)
15241 {
15242 AuthRecord *rr;
15243
15244 mDNS_Lock(m);
15245
15246 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit");
15247 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15248
15249 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15250
15251 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15252 if (WCFConnectionDealloc)
15253 {
15254 if (m->WCF)
15255 {
15256 WCFConnectionDealloc(m->WCF);
15257 m->WCF = mDNSNULL;
15258 }
15259 }
15260 #endif
15261
15262 #ifndef UNICAST_DISABLED
15263 {
15264 SearchListElem *s;
15265 SuspendLLQs(m);
15266 // Don't need to do SleepRecordRegistrations() here
15267 // because we deregister all records and services later in this routine
15268 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15269
15270 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15271 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15272 // and we may crash because the list still contains dangling pointers.
15273 for (s = SearchList; s; s = s->next)
15274 while (s->AuthRecs)
15275 {
15276 ARListElem *dereg = s->AuthRecs;
15277 s->AuthRecs = s->AuthRecs->next;
15278 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15279 }
15280 }
15281 #endif
15282
15283 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_All);
15284
15285 // Shut down all our active NAT Traversals
15286 while (m->NATTraversals)
15287 {
15288 NATTraversalInfo *t = m->NATTraversals;
15289 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15290
15291 // After stopping the NAT Traversal, we zero out the fields.
15292 // This has particularly important implications for our AutoTunnel records --
15293 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15294 // handlers to just turn around and attempt to re-register those same records.
15295 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15296 // to not do this.
15297 t->ExternalAddress = zerov4Addr;
15298 t->NewAddress = zerov4Addr;
15299 t->ExternalPort = zeroIPPort;
15300 t->RequestedPort = zeroIPPort;
15301 t->Lifetime = 0;
15302 t->Result = mStatus_NoError;
15303 }
15304
15305 // Make sure there are nothing but deregistering records remaining in the list
15306 if (m->CurrentRecord)
15307 {
15308 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
15309 "mDNS_StartExit: ERROR m->CurrentRecord already set " PRI_S, ARDisplayString(m, m->CurrentRecord));
15310 }
15311
15312 // We're in the process of shutting down, so queries, etc. are no longer available.
15313 // Consequently, determining certain information, e.g. the uDNS update server's IP
15314 // address, will not be possible. The records on the main list are more likely to
15315 // already contain such information, so we deregister the duplicate records first.
15316 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering duplicate resource records");
15317 DeregLoop(m, m->DuplicateRecords);
15318 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering resource records");
15319 DeregLoop(m, m->ResourceRecords);
15320
15321 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15322 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15323 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15324 {
15325 m->NextScheduledResponse = m->timenow;
15326 m->SuppressSending = 0;
15327 }
15328
15329 if (m->ResourceRecords)
15330 {
15331 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Sending final record deregistrations");
15332 }
15333 else
15334 {
15335 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: No deregistering records remain");
15336 }
15337
15338 for (rr = m->DuplicateRecords; rr; rr = rr->next)
15339 {
15340 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
15341 "mDNS_StartExit: Should not still have Duplicate Records remaining: %02X " PRI_S,
15342 rr->resrec.RecordType, ARDisplayString(m, rr));
15343 }
15344
15345 // If any deregistering records remain, send their deregistration announcements before we exit
15346 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
15347
15348 mDNS_Unlock(m);
15349
15350 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: done");
15351 }
15352
mDNS_FinalExit(mDNS * const m)15353 mDNSexport void mDNS_FinalExit(mDNS *const m)
15354 {
15355 mDNSu32 rrcache_active = 0;
15356 mDNSu32 rrcache_totalused = m->rrcache_totalused;
15357 mDNSu32 slot;
15358 AuthRecord *rr;
15359
15360 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: mDNSPlatformClose");
15361 mDNSPlatformClose(m);
15362
15363 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
15364 {
15365 while (m->rrcache_hash[slot])
15366 {
15367 CacheGroup *cg = m->rrcache_hash[slot];
15368 while (cg->members)
15369 {
15370 CacheRecord *cr = cg->members;
15371 cg->members = cg->members->next;
15372 if (cr->CRActiveQuestion) rrcache_active++;
15373 ReleaseCacheRecord(m, cr);
15374 }
15375 cg->rrcache_tail = &cg->members;
15376 ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15377 }
15378 }
15379 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15380 if (rrcache_active != m->rrcache_active)
15381 LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
15382
15383 for (rr = m->ResourceRecords; rr; rr = rr->next)
15384 LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15385
15386 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15387 uninit_trust_anchors();
15388 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15389
15390 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: done");
15391 }
15392
15393 #ifdef UNIT_TEST
15394 #include "../unittests/mdns_ut.c"
15395 #endif
15396