]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNS.c
mDNSResponder-1096.40.7.tar.gz
[apple/mdnsresponder.git] / mDNSCore / mDNS.c
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-2019 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 "DNSCommon.h" // Defines general DNS utility routines
27 #include "uDNS.h" // Defines entry points into unicast-specific routines
28 #include "nsec.h"
29 #include "dnssec.h"
30
31 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
32 #include "D2D.h"
33 #endif
34
35 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
36 #include "SymptomReporter.h"
37 #endif
38
39 // Disable certain benign warnings with Microsoft compilers
40 #if (defined(_MSC_VER))
41 // Disable "conditional expression is constant" warning for debug macros.
42 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
43 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
44 #pragma warning(disable:4127)
45
46 // Disable "assignment within conditional expression".
47 // Other compilers understand the convention that if you place the assignment expression within an extra pair
48 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
49 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
50 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
51 #pragma warning(disable:4706)
52 #endif
53
54 #include "dns_sd.h" // for kDNSServiceFlags* definitions
55 #include "dns_sd_internal.h"
56
57 #if APPLE_OSX_mDNSResponder
58 // Delay in seconds before disabling multicast after there are no active queries or registrations.
59 #define BONJOUR_DISABLE_DELAY 60
60 #endif
61
62 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
63 #include <WebFilterDNS/WebFilterDNS.h>
64
65 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
66 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
67 #endif
68
69 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
70 #include "Metrics.h"
71 #endif
72
73 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
74 #include "DNS64.h"
75 #endif
76
77 // Forward declarations
78 mDNSlocal void BeginSleepProcessing(mDNS *const m);
79 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
80 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly);
81 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
82 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
83 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q);
84 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
85 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
86 mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
87
88 typedef mDNSu32 DeadvertiseFlags;
89 #define kDeadvertiseFlag_NormalHostname (1U << 0)
90 #define kDeadvertiseFlag_RandHostname (1U << 1)
91 #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
92
93 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags);
94 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set);
95 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords);
96 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
97 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records);
98 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
99
100 // ***************************************************************************
101 #if COMPILER_LIKES_PRAGMA_MARK
102 #pragma mark - Program Constants
103 #endif
104
105 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
106 #define MDNS_TRACER 1
107
108 // Any records bigger than this are considered 'large' records
109 #define SmallRecordLimit 1024
110
111 #define kMaxUpdateCredits 10
112 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
113
114 // define special NR_AnswerTo values
115 #define NR_AnswerMulticast (mDNSu8*)~0
116 #define NR_AnswerUnicast (mDNSu8*)~1
117
118 // Question default timeout values
119 #define DEFAULT_MCAST_TIMEOUT 5
120 #define DEFAULT_LO_OR_P2P_TIMEOUT 5
121
122 // The code (see SendQueries() and BuildQuestion()) needs to have the
123 // RequestUnicast value set to a value one greater than the number of times you want the query
124 // sent with the "request unicast response" (QU) bit set.
125 #define SET_QU_IN_FIRST_QUERY 2
126 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
127
128 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
129 #define DARK_WAKE_DELAY_SLEEP 5
130 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
131
132 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
133 #define MAX_CONFLICT_PROCESSING_DELAYS 3
134
135 // RFC 6762 defines Passive Observation Of Failures (POOF)
136 //
137 // A host observes the multicast queries issued by the other hosts on
138 // the network. One of the major benefits of also sending responses
139 // using multicast is that it allows all hosts to see the responses
140 // (or lack thereof) to those queries.
141 //
142 // If a host sees queries, for which a record in its cache would be
143 // expected to be given as an answer in a multicast response, but no
144 // such answer is seen, then the host may take this as an indication
145 // that the record may no longer be valid.
146 //
147 // After seeing two or more of these queries, and seeing no multicast
148 // response containing the expected answer within ten seconds, then even
149 // though its TTL may indicate that it is not yet due to expire, that
150 // record SHOULD be flushed from the cache.
151 //
152 // <https://tools.ietf.org/html/rfc6762#section-10.5>
153
154 #define POOF_ENABLED 1
155
156 mDNSexport const char *const mDNS_DomainTypeNames[] =
157 {
158 "b._dns-sd._udp.", // Browse
159 "db._dns-sd._udp.", // Default Browse
160 "lb._dns-sd._udp.", // Automatic Browse
161 "r._dns-sd._udp.", // Registration
162 "dr._dns-sd._udp." // Default Registration
163 };
164
165 #ifdef UNICAST_DISABLED
166 #define uDNS_IsActiveQuery(q, u) mDNSfalse
167 #endif
168
169 // ***************************************************************************
170 #if COMPILER_LIKES_PRAGMA_MARK
171 #pragma mark -
172 #pragma mark - General Utility Functions
173 #endif
174
175 #if MDNS_MALLOC_DEBUGGING
176 // When doing memory allocation debugging, this function traverses all lists in the mDNS query
177 // structures and caches and checks each entry in the list to make sure it's still good.
178 mDNSlocal void mDNS_ValidateLists(void *context)
179 {
180 mDNS *m = context;
181 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
182 mDNSu32 NumAllInterfaceRecords = 0;
183 mDNSu32 NumAllInterfaceQuestions = 0;
184 #endif
185
186 // Check core mDNS lists
187 AuthRecord *rr;
188 for (rr = m->ResourceRecords; rr; rr=rr->next)
189 {
190 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
191 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
192 if (rr->resrec.name != &rr->namestorage)
193 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
194 rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
195 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
196 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
197 #endif
198 }
199
200 for (rr = m->DuplicateRecords; rr; rr=rr->next)
201 {
202 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
203 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
204 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
205 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
206 #endif
207 }
208
209 rr = m->NewLocalRecords;
210 if (rr)
211 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
212 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType);
213
214 rr = m->CurrentRecord;
215 if (rr)
216 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
217 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType);
218
219 DNSQuestion *q;
220 for (q = m->Questions; q; q=q->next)
221 {
222 if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0)
223 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next);
224 if (q->DuplicateOf && q->LocalSocket)
225 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
226 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
227 if (!LocalOnlyOrP2PInterface(q->InterfaceID) && mDNSOpaque16IsZero(q->TargetQID))
228 NumAllInterfaceQuestions++;
229 #endif
230 }
231
232 CacheGroup *cg;
233 CacheRecord *cr;
234 mDNSu32 slot;
235 FORALL_CACHERECORDS(slot, cg, cr)
236 {
237 if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
238 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType);
239 if (cr->CRActiveQuestion)
240 {
241 for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break;
242 if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr));
243 }
244 }
245
246 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
247 if (m->NumAllInterfaceRecords != NumAllInterfaceRecords)
248 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords);
249
250 if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions)
251 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions);
252 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
253 }
254 #endif // MDNS_MALLOC_DEBUGGING
255
256 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type
257 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out
258 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
259 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
260 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
261 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
262 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
263 (rr)->resrec.rrtype == kDNSType_CNAME || \
264 (rr)->resrec.rrtype == kDNSType_PTR))
265
266 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
267 {
268 mDNS_CheckLock(m);
269
270 if (m->NextScheduledStopTime - q->StopTime > 0)
271 m->NextScheduledStopTime = q->StopTime;
272 }
273
274 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
275 {
276 mDNS_CheckLock(m);
277
278 if (ActiveQuestion(q))
279 {
280 // Depending on whether this is a multicast or unicast question we want to set either:
281 // m->NextScheduledQuery = NextQSendTime(q) or
282 // m->NextuDNSEvent = NextQSendTime(q)
283 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
284 if (*timer - NextQSendTime(q) > 0)
285 *timer = NextQSendTime(q);
286 }
287 }
288
289 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
290 {
291 #if MDNS_MALLOC_DEBUGGING >= 1
292 unsigned int i;
293 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
294 #endif
295 e->next = r->rrauth_free;
296 r->rrauth_free = e;
297 r->rrauth_totalused--;
298 }
299
300 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
301 {
302 AuthEntity *e = (AuthEntity *)(*cp);
303 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c);
304 if ((*cp)->rrauth_tail != &(*cp)->members)
305 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
306 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
307 (*cp)->name = mDNSNULL;
308 *cp = (*cp)->next; // Cut record from list
309 ReleaseAuthEntity(r, e);
310 }
311
312 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
313 {
314 AuthEntity *e = mDNSNULL;
315
316 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
317 r->rrauth_lock = 1;
318
319 if (!r->rrauth_free)
320 {
321 // We allocate just one AuthEntity at a time because we need to be able
322 // free them all individually which normally happens when we parse /etc/hosts into
323 // AuthHash where we add the "new" entries and discard (free) the already added
324 // entries. If we allocate as chunks, we can't free them individually.
325 AuthEntity *storage = (AuthEntity *) mDNSPlatformMemAllocateClear(sizeof(*storage));
326 storage->next = mDNSNULL;
327 r->rrauth_free = storage;
328 }
329
330 // If we still have no free records, recycle all the records we can.
331 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
332 if (!r->rrauth_free)
333 {
334 mDNSu32 oldtotalused = r->rrauth_totalused;
335 mDNSu32 slot;
336 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
337 {
338 AuthGroup **cp = &r->rrauth_hash[slot];
339 while (*cp)
340 {
341 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
342 else ReleaseAuthGroup(r, cp);
343 }
344 }
345 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
346 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
347 }
348
349 if (r->rrauth_free) // If there are records in the free list, take one
350 {
351 e = r->rrauth_free;
352 r->rrauth_free = e->next;
353 if (++r->rrauth_totalused >= r->rrauth_report)
354 {
355 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
356 if (r->rrauth_report < 100) r->rrauth_report += 10;
357 else if (r->rrauth_report < 1000) r->rrauth_report += 100;
358 else r->rrauth_report += 1000;
359 }
360 mDNSPlatformMemZero(e, sizeof(*e));
361 }
362
363 r->rrauth_lock = 0;
364
365 return(e);
366 }
367
368 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name)
369 {
370 AuthGroup *ag;
371 const mDNSu32 slot = namehash % AUTH_HASH_SLOTS;
372
373 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
374 if (ag->namehash == namehash && SameDomainName(ag->name, name))
375 break;
376 return(ag);
377 }
378
379 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr)
380 {
381 return(AuthGroupForName(r, rr->namehash, rr->name));
382 }
383
384 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr)
385 {
386 mDNSu16 namelen = DomainNameLength(rr->name);
387 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
388 const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS;
389 if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
390 ag->next = r->rrauth_hash[slot];
391 ag->namehash = rr->namehash;
392 ag->members = mDNSNULL;
393 ag->rrauth_tail = &ag->members;
394 ag->NewLocalOnlyRecords = mDNSNULL;
395 if (namelen > sizeof(ag->namestorage))
396 ag->name = (domainname *) mDNSPlatformMemAllocate(namelen);
397 else
398 ag->name = (domainname*)ag->namestorage;
399 if (!ag->name)
400 {
401 LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
402 ReleaseAuthEntity(r, (AuthEntity*)ag);
403 return(mDNSNULL);
404 }
405 AssignDomainName(ag->name, rr->name);
406
407 if (AuthGroupForRecord(r, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
408 r->rrauth_hash[slot] = ag;
409 if (AuthGroupForRecord(r, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
410
411 return(ag);
412 }
413
414 // Returns the AuthGroup in which the AuthRecord was inserted
415 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
416 {
417 AuthGroup *ag;
418
419 (void)m;
420 ag = AuthGroupForRecord(r, &rr->resrec);
421 if (!ag) ag = GetAuthGroup(r, &rr->resrec); // If we don't have a AuthGroup for this name, make one now
422 if (ag)
423 {
424 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list
425 ag->rrauth_tail = &(rr->next); // Advance tail pointer
426 }
427 return ag;
428 }
429
430 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
431 {
432 AuthGroup *a;
433 AuthRecord **rp;
434
435 a = AuthGroupForRecord(r, &rr->resrec);
436 if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
437 rp = &a->members;
438 while (*rp)
439 {
440 if (*rp != rr)
441 rp=&(*rp)->next;
442 else
443 {
444 // We don't break here, so that we can set the tail below without tracking "prev" pointers
445
446 LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
447 *rp = (*rp)->next; // Cut record from list
448 }
449 }
450 // TBD: If there are no more members, release authgroup ?
451 a->rrauth_tail = rp;
452 return a;
453 }
454
455 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name)
456 {
457 CacheGroup *cg;
458 mDNSu32 slot = HashSlotFromNameHash(namehash);
459 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
460 if (cg->namehash == namehash && SameDomainName(cg->name, name))
461 break;
462 return(cg);
463 }
464
465 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr)
466 {
467 return(CacheGroupForName(m, rr->namehash, rr->name));
468 }
469
470 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
471 {
472 NetworkInterfaceInfo *intf;
473
474 if (addr->type == mDNSAddrType_IPv4)
475 {
476 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
477 if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
478 for (intf = m->HostInterfaces; intf; intf = intf->next)
479 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
480 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
481 return(mDNStrue);
482 }
483
484 if (addr->type == mDNSAddrType_IPv6)
485 {
486 if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
487 for (intf = m->HostInterfaces; intf; intf = intf->next)
488 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
489 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
490 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
491 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
492 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
493 return(mDNStrue);
494 }
495
496 return(mDNSfalse);
497 }
498
499 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
500 {
501 NetworkInterfaceInfo *intf = m->HostInterfaces;
502 while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
503 return(intf);
504 }
505
506 mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
507 {
508 NetworkInterfaceInfo *intf;
509
510 if (!InterfaceID)
511 return mDNSNULL;
512
513 // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
514 // we still want to find the first IPv4 Link-Local interface
515 for (intf = m->HostInterfaces; intf; intf = intf->next)
516 {
517 if (intf->InterfaceID == InterfaceID &&
518 intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
519 {
520 debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
521 return intf;
522 }
523 }
524 return (mDNSNULL);
525 }
526
527 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
528 {
529 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
530 return(intf ? intf->ifname : mDNSNULL);
531 }
532
533 // Caller should hold the lock
534 mDNSlocal void GenerateNegativeResponseEx(mDNS *const m, mDNSInterfaceID InterfaceID, QC_result qc, mDNSBool noData)
535 {
536 DNSQuestion *q;
537 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
538 q = m->CurrentQuestion;
539 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
540 "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME " (" PUB_S ")",
541 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype));
542
543 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, InterfaceID, mDNSNULL);
544 m->rec.r.resrec.negativeRecordType = noData ? kNegativeRecordType_NoData : kNegativeRecordType_Unspecified;
545
546 // We need to force the response through in the following cases
547 //
548 // a) SuppressUnusable questions that are suppressed
549 // b) Append search domains and retry the question
550 //
551 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
552 // through we use "QC_forceresponse".
553 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
554 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question
555 // Don't touch the question after this
556 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
557 }
558 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
559
560 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
561 {
562 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
563 if (q->CNAMEReferrals >= 10 || selfref)
564 {
565 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
566 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ") NOT following CNAME referral %d" PUB_S " for " PRI_S,
567 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype),
568 q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
569
570 }
571 else
572 {
573 const mDNSu32 c = q->CNAMEReferrals + 1; // Stash a copy of the new q->CNAMEReferrals value
574 UDPSocket *sock = q->LocalSocket;
575 mDNSOpaque16 id = q->TargetQID;
576 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
577 uDNSMetrics metrics;
578 #endif
579
580 q->LocalSocket = mDNSNULL;
581
582 // The SameDomainName check above is to ignore bogus CNAME records that point right back at
583 // themselves. Without that check we can get into a case where we have two duplicate questions,
584 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
585 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
586 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
587 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
588 // for either of them. This is not a problem for CNAME loops of two or more records because in
589 // those cases the newly re-appended question A has a different target name and therefore cannot be
590 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
591
592 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
593 // and track CNAMEs coming and going, we should really create a subordinate query here,
594 // which we would subsequently cancel and retract if the CNAME referral record were removed.
595 // In reality this is such a corner case we'll ignore it until someone actually needs it.
596
597 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
598 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ") following CNAME referral %d for " PRI_S,
599 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype),
600 q->CNAMEReferrals, RRDisplayString(m, rr));
601
602 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
603 if ((q->CNAMEReferrals == 0) && !q->metrics.originalQName)
604 {
605 domainname * qName;
606 mDNSu16 qNameLen;
607
608 qNameLen = DomainNameLength(&q->qname);
609 if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
610 {
611 qName = (domainname *) mDNSPlatformMemAllocate(qNameLen);
612 if (qName)
613 {
614 mDNSPlatformMemCopy(qName->c, q->qname.c, qNameLen);
615 q->metrics.originalQName = qName;
616 }
617 }
618 }
619 metrics = q->metrics;
620 mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics));
621 #endif
622 mDNS_StopQuery_internal(m, q); // Stop old query
623 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname
624 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
625 // If a unicast query results in a CNAME that points to a .local, we need to re-try
626 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
627 // to try this as unicast query even though it is a .local name
628 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
629 {
630 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
631 "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME " (" PUB_S ") Record " PRI_S,
632 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype), RRDisplayString(m, rr));
633 q->IsUnicastDotLocal = mDNStrue;
634 }
635 mDNS_StartQuery_internal(m, q); // start new query
636 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
637 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
638 q->CNAMEReferrals = c;
639 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
640 metrics.expiredAnswerState = q->metrics.expiredAnswerState; // We want the newly initialized state for this value
641 metrics.dnsOverTCPState = q->metrics.dnsOverTCPState; // We want the newly initialized state for this value
642 q->metrics = metrics;
643 #endif
644 if (sock)
645 {
646 // If our new query is a duplicate, then it can't have a socket of its own, so we have to close the one we saved.
647 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
648 else
649 {
650 // Transplant the old socket into the new question, and copy the query ID across too.
651 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
652 q->LocalSocket = sock;
653 q->TargetQID = id;
654 }
655 }
656 }
657 }
658
659 #ifdef USE_LIBIDN
660
661 #include <unicode/uidna.h>
662
663 // #define DEBUG_PUNYCODE 1
664
665 mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end)
666 {
667 UErrorCode errorCode = U_ZERO_ERROR;
668 UIDNAInfo info = UIDNA_INFO_INITIALIZER;
669 UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode);
670 int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, end-(dst+1), &info, &errorCode);
671 uidna_close(uts46);
672 #if DEBUG_PUNYCODE
673 if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode);
674 if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors);
675 if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len);
676 #endif
677 if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL;
678 *dst = len;
679 return(dst + 1 + len);
680 }
681
682 mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d)
683 {
684 int i;
685 for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue;
686 return mDNSfalse;
687 }
688
689 mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d)
690 {
691 const mDNSu8 *ptr = d->c;
692 const mDNSu8 *ans = mDNSNULL;
693 while (ptr[0])
694 {
695 const mDNSu8 *const next = ptr + 1 + ptr[0];
696 if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL;
697 if (IsHighASCIILabel(ptr)) ans = ptr;
698 ptr = next;
699 }
700 return ans;
701 }
702
703 mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname)
704 {
705 const mDNSu8 *h = FindLastHighASCIILabel(&q->qname);
706 #if DEBUG_PUNYCODE
707 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h);
708 #endif
709 if (!h) return mDNSfalse; // There are no high-ascii labels to convert
710
711 mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME);
712 if (!dst)
713 return mDNSfalse; // The label was not convertible to Punycode
714 else
715 {
716 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
717 const mDNSu8 *const src = h + 1 + h[0];
718 const mDNSu8 remainder = DomainNameLength((domainname*)src);
719 if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse; // Name too long -- cannot be converted to Punycode
720
721 mDNSPlatformMemCopy(newname->c, q->qname.c, h - q->qname.c); // Fill in the leading part
722 mDNSPlatformMemCopy(dst, src, remainder); // Fill in the trailing part
723 #if DEBUG_PUNYCODE
724 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c);
725 #endif
726 return mDNStrue;
727 }
728 }
729
730 #endif // USE_LIBIDN
731
732 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
733 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
734 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
735 {
736 DNSQuestion *q = m->CurrentQuestion;
737 mDNSBool followcname;
738
739 if (!q)
740 {
741 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
742 return;
743 }
744
745 followcname = FollowCNAME(q, &rr->resrec, AddRecord);
746
747 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
748 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
749 {
750 LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
751 AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
752 return;
753 }
754
755 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
756 if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
757 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
758 if (q->QuestionCallback && !q->NoAnswer)
759 {
760 q->CurrentAnswers += AddRecord ? 1 : -1;
761 if (UniqueLocalOnlyRecord(rr))
762 {
763 if (!followcname || q->ReturnIntermed)
764 {
765 // Don't send this packet on the wire as we answered from /etc/hosts
766 q->ThisQInterval = 0;
767 q->LOAddressAnswers += AddRecord ? 1 : -1;
768 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
769 }
770 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
771 // The callback above could have caused the question to stop. Detect that
772 // using m->CurrentQuestion
773 if (followcname && m->CurrentQuestion == q)
774 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
775 return;
776 }
777 else
778 {
779 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
780 }
781 }
782 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
783 }
784
785 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
786 {
787 if (m->CurrentQuestion)
788 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
789 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
790 m->CurrentQuestion = m->Questions;
791 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
792 {
793 mDNSBool answered;
794 DNSQuestion *q = m->CurrentQuestion;
795 if (RRAny(ar))
796 answered = AuthRecordAnswersQuestion(ar, q);
797 else
798 answered = LocalOnlyRecordAnswersQuestion(ar, q);
799 if (answered)
800 AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again
801 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
802 m->CurrentQuestion = q->next;
803 }
804 m->CurrentQuestion = mDNSNULL;
805 }
806
807 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
808 // delivers the appropriate add/remove events to listening questions:
809 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
810 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
811 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
812 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
813 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
814 //
815 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
816 // and by mDNS_Deregister_internal()
817
818 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
819 {
820 if (m->CurrentQuestion)
821 LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
822 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
823
824 m->CurrentQuestion = m->LocalOnlyQuestions;
825 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
826 {
827 mDNSBool answered;
828 DNSQuestion *q = m->CurrentQuestion;
829 // We are called with both LocalOnly/P2P record or a regular AuthRecord
830 if (RRAny(ar))
831 answered = AuthRecordAnswersQuestion(ar, q);
832 else
833 answered = LocalOnlyRecordAnswersQuestion(ar, q);
834 if (answered)
835 AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again
836 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
837 m->CurrentQuestion = q->next;
838 }
839
840 m->CurrentQuestion = mDNSNULL;
841
842 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
843 if (ar->ARType == AuthRecordLocalOnly || ar->ARType == AuthRecordP2P)
844 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, ar, AddRecord);
845
846 }
847
848 // ***************************************************************************
849 #if COMPILER_LIKES_PRAGMA_MARK
850 #pragma mark -
851 #pragma mark - Resource Record Utility Functions
852 #endif
853
854 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
855
856 mDNSlocal mDNSBool ResourceRecordIsValidAnswer(const AuthRecord *const rr)
857 {
858 if ((rr->resrec.RecordType & kDNSRecordTypeActiveMask) &&
859 ((rr->Additional1 == mDNSNULL) || (rr->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
860 ((rr->Additional2 == mDNSNULL) || (rr->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
861 ((rr->DependentOn == mDNSNULL) || (rr->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)))
862 {
863 return mDNStrue;
864 }
865 else
866 {
867 return mDNSfalse;
868 }
869 }
870
871 mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *const rr, const mDNSInterfaceID InterfaceID)
872 {
873 if (rr->resrec.InterfaceID == mDNSInterface_Any)
874 {
875 return mDNSPlatformValidRecordForInterface(rr, InterfaceID);
876 }
877 else
878 {
879 return ((rr->resrec.InterfaceID == InterfaceID) ? mDNStrue : mDNSfalse);
880 }
881 }
882
883 mDNSlocal mDNSBool ResourceRecordIsValidInterfaceAnswer(const AuthRecord *const rr, const mDNSInterfaceID interfaceID)
884 {
885 return ((IsInterfaceValidForAuthRecord(rr, interfaceID) && ResourceRecordIsValidAnswer(rr)) ? mDNStrue : mDNSfalse);
886 }
887
888 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
889 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
890
891 // Parameters for handling probing conflicts
892 #define kMaxAllowedMCastProbingConflicts 1 // Maximum number of conflicts to allow from mcast messages.
893 #define kProbingConflictPauseDuration mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
894
895 // See RFC 6762: "8.3 Announcing"
896 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
897 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
898 #define InitialAnnounceCount ((mDNSu8)4)
899
900 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
901 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
902 // and then if the machine fails to wake, 3 goodbye packets).
903 #define GoodbyeCount ((mDNSu8)3)
904 #define WakeupCount ((mDNSu8)18)
905 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
906 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week
907
908 // Number of wakeups we send if WakeOnResolve is set in the question
909 #define InitialWakeOnResolveCount ((mDNSu8)3)
910
911 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
912 // This means that because the announce interval is doubled after sending the first packet, the first
913 // observed on-the-wire inter-packet interval between announcements is actually one second.
914 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
915 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
916 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
917 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
918
919 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
920 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \
921 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
922
923 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
924 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
925 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
926
927 // Adjustment factor to avoid race condition (used for unicast cache entries) :
928 // Suppose real record has TTL of 3600, and our local caching server has held it for 3500 seconds, so it returns an aged TTL of 100.
929 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
930 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
931 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
932 // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
933 // the cached copy at our local caching server will already have expired, so the server will be forced
934 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
935
936 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
937 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
938
939 #define MaxUnansweredQueries 4
940
941 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
942 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
943 // TTL and rdata may differ.
944 // This is used for cache flush management:
945 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
946 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
947
948 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
949
950 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
951
952 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
953 {
954 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
955 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
956 if (r1->resrec.InterfaceID &&
957 r2->resrec.InterfaceID &&
958 r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
959 return (mDNSBool)(
960 r1->resrec.rrclass == r2->resrec.rrclass &&
961 r1->resrec.namehash == r2->resrec.namehash &&
962 SameDomainName(r1->resrec.name, r2->resrec.name));
963 }
964
965 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
966 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
967 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
968 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
969 // so a response of any type should match, even if it is not actually the type the client plans to use.
970
971 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
972 // and require the rrtypes to match for the rdata to be considered potentially conflicting
973 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
974 {
975 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
976 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
977 if (pktrr->resrec.InterfaceID &&
978 authrr->resrec.InterfaceID &&
979 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
980 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
981 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
982 if ((authrr->resrec.InterfaceID == mDNSInterface_Any) &&
983 !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse);
984 return (mDNSBool)(
985 pktrr->resrec.rrclass == authrr->resrec.rrclass &&
986 pktrr->resrec.namehash == authrr->resrec.namehash &&
987 SameDomainName(pktrr->resrec.name, authrr->resrec.name));
988 }
989
990 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
991 // This is the information that the requester believes to be correct.
992 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
993 // This is the information that we believe to be correct.
994 // We've already determined that we plan to give this answer on this interface
995 // (either the record is non-specific, or it is specific to this interface)
996 // so now we just need to check the name, type, class, rdata and TTL.
997 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
998 {
999 // If RR signature is different, or data is different, then don't suppress our answer
1000 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
1001
1002 // If the requester's indicated TTL is less than half the real TTL,
1003 // we need to give our answer before the requester's copy expires.
1004 // If the requester's indicated TTL is at least half the real TTL,
1005 // then we can suppress our answer this time.
1006 // If the requester's indicated TTL is greater than the TTL we believe,
1007 // then that's okay, and we don't need to do anything about it.
1008 // (If two responders on the network are offering the same information,
1009 // that's okay, and if they are offering the information with different TTLs,
1010 // the one offering the lower TTL should defer to the one offering the higher TTL.)
1011 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
1012 }
1013
1014 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
1015 {
1016 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1017 {
1018 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
1019 {
1020 LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
1021 LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
1022 }
1023 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1024 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
1025 // Some defensive code:
1026 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1027 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1028 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1029 if (m->NextScheduledProbe - m->timenow < 0)
1030 m->NextScheduledProbe = m->timenow;
1031 }
1032 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
1033 {
1034 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1035 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
1036 }
1037 }
1038
1039 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
1040 {
1041 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1042 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
1043
1044 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1045 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1046 // records that are going to probe, then we delay its first announcement so that it will
1047 // go out synchronized with the first announcement for the other records that *are* probing.
1048 // This is a minor performance tweak that helps keep groups of related records synchronized together.
1049 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1050 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1051 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1052 // because they will meet the criterion of being at least half-way to their scheduled announcement time.
1053 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1054
1055 if (rr->ProbeCount)
1056 {
1057 rr->ProbingConflictCount = 0;
1058 // If we have no probe suppression time set, or it is in the past, set it now
1059 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
1060 {
1061 // To allow us to aggregate probes when a group of services are registered together,
1062 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1063 // This means the common-case behaviour is:
1064 // randomized wait; probe
1065 // 1/4 second wait; probe
1066 // 1/4 second wait; probe
1067 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1068 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1069
1070 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1071 if (m->SuppressProbes - m->NextScheduledProbe >= 0)
1072 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
1073 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
1074 m->SuppressProbes = m->timenow;
1075
1076 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1077 if (m->SuppressProbes - m->NextScheduledQuery >= 0)
1078 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
1079 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past
1080 m->SuppressProbes = m->timenow;
1081
1082 // except... don't expect to be able to send before the m->SuppressSending timer fires
1083 if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
1084 m->SuppressProbes = NonZeroTime(m->SuppressSending);
1085
1086 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
1087 {
1088 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1089 m->SuppressProbes - m->timenow,
1090 m->NextScheduledProbe - m->timenow,
1091 m->NextScheduledQuery - m->timenow,
1092 m->SuppressSending,
1093 m->SuppressSending - m->timenow);
1094 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1095 }
1096 }
1097 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
1098 }
1099 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1100 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1101 else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0))
1102 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
1103 else
1104 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1105
1106 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1107 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1108 // After three probes one second apart with no answer, we conclude the client is now sleeping
1109 // and we can begin broadcasting our announcements to take over ownership of that IP address.
1110 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1111 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1112 if (rr->AddressProxy.type)
1113 rr->LastAPTime = m->timenow;
1114
1115 // Set LastMCTime to now, to inhibit multicast responses
1116 // (no need to send additional multicast responses when we're announcing anyway)
1117 rr->LastMCTime = m->timenow;
1118 rr->LastMCInterface = mDNSInterfaceMark;
1119
1120 SetNextAnnounceProbeTime(m, rr);
1121 }
1122
1123 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
1124 {
1125 const domainname *target;
1126 if (rr->AutoTarget)
1127 {
1128 rr->AutoTarget = Target_AutoHostAndNATMAP;
1129 }
1130
1131 target = GetServiceTarget(m, rr);
1132 if (!target || target->c[0] == 0)
1133 {
1134 // defer registration until we've got a target
1135 LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
1136 rr->state = regState_NoTarget;
1137 return mDNSNULL;
1138 }
1139 else
1140 {
1141 LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
1142 return target;
1143 }
1144 }
1145
1146 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1147 mDNSlocal mDNSBool AuthRecordIncludesOrIsAWDL(const AuthRecord *const ar)
1148 {
1149 return ((AuthRecordIncludesAWDL(ar) || mDNSPlatformInterfaceIsAWDL(ar->resrec.InterfaceID)) ? mDNStrue : mDNSfalse);
1150 }
1151 #endif
1152
1153 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1154 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1155 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
1156 {
1157 domainname *const target = GetRRDomainNameTarget(&rr->resrec);
1158 const domainname *newname;
1159
1160 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1161 if (AuthRecordIncludesOrIsAWDL(rr))
1162 {
1163 newname = &m->RandomizedHostname;
1164 }
1165 else
1166 #endif
1167 {
1168 newname = &m->MulticastHostname;
1169 }
1170 if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
1171
1172 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
1173 {
1174 const domainname *const n = SetUnicastTargetToHostName(m, rr);
1175 if (n) newname = n;
1176 else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
1177 }
1178
1179 if (target && SameDomainName(target, newname))
1180 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
1181
1182 if (target && !SameDomainName(target, newname))
1183 {
1184 AssignDomainName(target, newname);
1185 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash
1186
1187 // If we're in the middle of probing this record, we need to start again,
1188 // because changing its rdata may change the outcome of the tie-breaker.
1189 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1190 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1191
1192 // If we've announced this record, we really should send a goodbye packet for the old rdata before
1193 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1194 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1195 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
1196 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1197 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1198
1199 rr->AnnounceCount = InitialAnnounceCount;
1200 rr->RequireGoodbye = mDNSfalse;
1201 rr->ProbeRestartCount = 0;
1202 InitializeLastAPTime(m, rr);
1203 }
1204 }
1205
1206 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
1207 {
1208 if (rr->RecordCallback)
1209 {
1210 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1211 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1212 rr->Acknowledged = mDNStrue;
1213 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
1214 rr->RecordCallback(m, rr, mStatus_NoError);
1215 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
1216 }
1217 }
1218
1219 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
1220 {
1221 // Make sure that we don't activate the SRV record and associated service records, if it is in
1222 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1223 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1224 // the target becomes available, the records will be reregistered.
1225 if (rr->resrec.rrtype != kDNSType_SRV)
1226 {
1227 AuthRecord *srvRR = mDNSNULL;
1228 if (rr->resrec.rrtype == kDNSType_PTR)
1229 srvRR = rr->Additional1;
1230 else if (rr->resrec.rrtype == kDNSType_TXT)
1231 srvRR = rr->DependentOn;
1232 if (srvRR)
1233 {
1234 if (srvRR->resrec.rrtype != kDNSType_SRV)
1235 {
1236 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1237 }
1238 else
1239 {
1240 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1241 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1242 rr->state = srvRR->state;
1243 }
1244 }
1245 }
1246
1247 if (rr->state == regState_NoTarget)
1248 {
1249 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1250 return;
1251 }
1252 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1253 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1254 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1255 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1256 // to sleep, then it is okay to start in Pending state as we will go back to NoTarget state if we don't have a target.
1257 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1258 {
1259 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1260 rr->state = regState_DeregPending;
1261 }
1262 else
1263 {
1264 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1265 rr->state = regState_Pending;
1266 }
1267 rr->ProbingConflictCount = 0;
1268 rr->LastConflictPktNum = 0;
1269 rr->ProbeRestartCount = 0;
1270 rr->ProbeCount = 0;
1271 rr->AnnounceCount = 0;
1272 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1273 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1274 rr->expire = 0; // Forget about all the leases, start fresh
1275 rr->uselease = mDNStrue;
1276 rr->updateid = zeroID;
1277 rr->SRVChanged = mDNSfalse;
1278 rr->updateError = mStatus_NoError;
1279 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1280 // The records might already be registered with the server and hence could have NAT state.
1281 if (rr->NATinfo.clientContext)
1282 {
1283 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1284 rr->NATinfo.clientContext = mDNSNULL;
1285 }
1286 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1287 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1288 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1289 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1290 }
1291
1292 // Two records qualify to be local duplicates if:
1293 // (a) the RecordTypes are the same, or
1294 // (b) one is Unique and the other Verified
1295 // (c) either is in the process of deregistering
1296 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1297 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1298 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1299
1300 #define RecordIsLocalDuplicate(A,B) \
1301 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1302
1303 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1304 {
1305 const AuthGroup *a;
1306 AuthRecord *rp;
1307
1308 a = AuthGroupForRecord(r, &rr->resrec);
1309 if (!a) return mDNSNULL;
1310 rp = a->members;
1311 while (rp)
1312 {
1313 if (!RecordIsLocalDuplicate(rp, rr))
1314 rp = rp->next;
1315 else
1316 {
1317 if (rp->resrec.RecordType == kDNSRecordTypeDeregistering)
1318 {
1319 rp->AnnounceCount = 0;
1320 rp = rp->next;
1321 }
1322 else return rp;
1323 }
1324 }
1325 return (mDNSNULL);
1326 }
1327
1328 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1329 {
1330 const AuthGroup *a;
1331 const AuthRecord *rp;
1332
1333 a = AuthGroupForRecord(r, &rr->resrec);
1334 if (!a) return mDNSfalse;
1335 rp = a->members;
1336 while (rp)
1337 {
1338 const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1339 const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp;
1340 if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec))
1341 return mDNStrue;
1342 else
1343 rp = rp->next;
1344 }
1345 return (mDNSfalse);
1346 }
1347
1348 // checks to see if "rr" is already present
1349 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1350 {
1351 const AuthGroup *a;
1352 AuthRecord *rp;
1353
1354 a = AuthGroupForRecord(r, &rr->resrec);
1355 if (!a) return mDNSNULL;
1356 rp = a->members;
1357 while (rp)
1358 {
1359 if (rp != rr)
1360 rp = rp->next;
1361 else
1362 {
1363 return rp;
1364 }
1365 }
1366 return (mDNSNULL);
1367 }
1368
1369 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1370 {
1371 if (RRLocalOnly(rr))
1372 {
1373 // A sanity check, this should be prevented in calling code.
1374 LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1375 return;
1376 }
1377
1378 if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1379 {
1380 NetworkInterfaceInfo *intf;
1381 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1382 DeadvertiseFlags flags = 0; // DeadvertiseFlags for non-AWDL interfaces.
1383 DeadvertiseFlags flagsAWDL = 0; // DeadvertiseFlags for AWDL interfaces.
1384 if (AuthRecordIncludesOrIsAWDL(rr))
1385 {
1386 if (AuthRecordIncludesAWDL(rr))
1387 {
1388 m->AutoTargetAWDLIncludedCount--;
1389 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1390 "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1391 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1392 if (m->AutoTargetAWDLIncludedCount == 0)
1393 {
1394 flags |= kDeadvertiseFlag_RandHostname;
1395 if (m->AutoTargetAWDLOnlyCount == 0) flagsAWDL |= kDeadvertiseFlag_RandHostname;
1396 }
1397 }
1398 else
1399 {
1400 m->AutoTargetAWDLOnlyCount--;
1401 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1402 "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1403 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1404 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1405 {
1406 flagsAWDL |= kDeadvertiseFlag_RandHostname;
1407 }
1408 }
1409 if (flags || flagsAWDL)
1410 {
1411 for (intf = m->HostInterfaces; intf; intf = intf->next)
1412 {
1413 if (!intf->Advertise) continue;
1414 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID))
1415 {
1416 if (flagsAWDL) DeadvertiseInterface(m, intf, flagsAWDL);
1417 }
1418 else
1419 {
1420 if (flags) DeadvertiseInterface(m, intf, flags);
1421 }
1422 }
1423 }
1424 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1425 {
1426 GetRandomUUIDLocalHostname(&m->RandomizedHostname);
1427 }
1428 }
1429 else
1430 #endif
1431 {
1432 m->AutoTargetServices--;
1433 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1434 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1435 m->AutoTargetServices, ARDisplayString(m, rr));
1436 if (m->AutoTargetServices == 0)
1437 {
1438 for (intf = m->HostInterfaces; intf; intf = intf->next)
1439 {
1440 if (intf->Advertise) DeadvertiseInterface(m, intf, kDeadvertiseFlag_NormalHostname);
1441 }
1442 }
1443 }
1444 }
1445
1446 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1447 if (!AuthRecord_uDNS(rr))
1448 {
1449 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1450 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
1451 m->NumAllInterfaceRecords--;
1452 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1453 "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1454 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1455 }
1456 #endif
1457 }
1458
1459 mDNSlocal void AdvertiseNecessaryInterfaceRecords(mDNS *const m)
1460 {
1461 NetworkInterfaceInfo *intf;
1462 for (intf = m->HostInterfaces; intf; intf = intf->next)
1463 {
1464 if (intf->Advertise) AdvertiseInterfaceIfNeeded(m, intf);
1465 }
1466 }
1467
1468 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1469 {
1470 mDNSBool enablingBonjour = mDNSfalse;
1471
1472 if (RRLocalOnly(rr))
1473 {
1474 // A sanity check, this should be prevented in calling code.
1475 LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1476 return;
1477 }
1478
1479 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1480 if (!AuthRecord_uDNS(rr))
1481 {
1482 m->NumAllInterfaceRecords++;
1483 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1484 "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1485 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1486 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1487 {
1488 m->NextBonjourDisableTime = 0;
1489 if (m->BonjourEnabled == 0)
1490 {
1491 // Enable Bonjour immediately by scheduling network changed processing where
1492 // we will join the multicast group on each active interface.
1493 m->BonjourEnabled = 1;
1494 enablingBonjour = mDNStrue;
1495 m->NetworkChanged = m->timenow;
1496 }
1497 }
1498 }
1499 #endif
1500
1501 if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1502 {
1503 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1504 if (AuthRecordIncludesAWDL(rr))
1505 {
1506 m->AutoTargetAWDLIncludedCount++;
1507 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1508 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1509 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1510 }
1511 else if (mDNSPlatformInterfaceIsAWDL(rr->resrec.InterfaceID))
1512 {
1513 m->AutoTargetAWDLOnlyCount++;
1514 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1515 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1516 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1517 }
1518 else
1519 #endif
1520 {
1521 m->AutoTargetServices++;
1522 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1523 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1524 m->AutoTargetServices, ARDisplayString(m, rr));
1525 }
1526 // If this is the first advertised service and we did not just enable Bonjour above, then
1527 // advertise all the interface records. If we did enable Bonjour above, the interface records will
1528 // be advertised during the network changed processing scheduled above, so no need
1529 // to do it here.
1530 if (!enablingBonjour) AdvertiseNecessaryInterfaceRecords(m);
1531 }
1532 }
1533
1534 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1535 {
1536 mDNSAddr laddr = zeroAddr;
1537 mDNSEthAddr eth = zeroEthAddr;
1538 mDNSIPPort lport = zeroIPPort;
1539 mDNSIPPort rport = zeroIPPort;
1540 mDNSu32 timeout = 0;
1541 mDNSu32 seq = 0;
1542 mDNSu32 ack = 0;
1543 mDNSu16 win = 0;
1544
1545 if (mDNS_KeepaliveRecord(&rr->resrec))
1546 {
1547 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1548 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1549 {
1550 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1551 return;
1552 }
1553 }
1554 }
1555
1556 // Exported so uDNS.c can call this
1557 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1558 {
1559 domainname *target = GetRRDomainNameTarget(&rr->resrec);
1560 AuthRecord *r;
1561 AuthRecord **p = &m->ResourceRecords;
1562 AuthRecord **d = &m->DuplicateRecords;
1563
1564 if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1565 { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1566
1567 if (!rr->resrec.RecordType)
1568 { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1569
1570 if (m->ShutdownTime)
1571 { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1572
1573 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1574 {
1575 mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1576 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1577 {
1578 rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1579 rr->ARType = AuthRecordLocalOnly;
1580 }
1581 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1582 {
1583 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1584 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1585 }
1586 if (rr->resrec.InterfaceID != previousID)
1587 LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1588 }
1589
1590 if (RRLocalOnly(rr))
1591 {
1592 if (CheckAuthSameRecord(&m->rrauth, rr))
1593 {
1594 LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1595 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1596 return(mStatus_AlreadyRegistered);
1597 }
1598 }
1599 else
1600 {
1601 while (*p && *p != rr) p=&(*p)->next;
1602 if (*p)
1603 {
1604 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1605 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1606 return(mStatus_AlreadyRegistered);
1607 }
1608 }
1609
1610 while (*d && *d != rr) d=&(*d)->next;
1611 if (*d)
1612 {
1613 LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1614 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1615 return(mStatus_AlreadyRegistered);
1616 }
1617
1618 if (rr->DependentOn)
1619 {
1620 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1621 rr->resrec.RecordType = kDNSRecordTypeVerified;
1622 else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique)
1623 {
1624 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1625 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1626 return(mStatus_Invalid);
1627 }
1628 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1629 {
1630 LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1631 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1632 return(mStatus_Invalid);
1633 }
1634 }
1635
1636 rr->next = mDNSNULL;
1637
1638 // Field Group 1: The actual information pertaining to this resource record
1639 // Set up by client prior to call
1640
1641 // Field Group 2: Persistent metadata for Authoritative Records
1642 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1643 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1644 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1645 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
1646 // rr->Callback = already set in mDNS_SetupResourceRecord
1647 // rr->Context = already set in mDNS_SetupResourceRecord
1648 // rr->RecordType = already set in mDNS_SetupResourceRecord
1649 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1650 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1651 // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1652 if (rr->AutoTarget && target) target->c[0] = 0;
1653
1654 // Field Group 3: Transient state for Authoritative Records
1655 rr->Acknowledged = mDNSfalse;
1656 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1657 rr->ProbeRestartCount = 0;
1658 rr->AnnounceCount = InitialAnnounceCount;
1659 rr->RequireGoodbye = mDNSfalse;
1660 rr->AnsweredLocalQ = mDNSfalse;
1661 rr->IncludeInProbe = mDNSfalse;
1662 rr->ImmedUnicast = mDNSfalse;
1663 rr->SendNSECNow = mDNSNULL;
1664 rr->ImmedAnswer = mDNSNULL;
1665 rr->ImmedAdditional = mDNSNULL;
1666 rr->SendRNow = mDNSNULL;
1667 rr->v4Requester = zerov4Addr;
1668 rr->v6Requester = zerov6Addr;
1669 rr->NextResponse = mDNSNULL;
1670 rr->NR_AnswerTo = mDNSNULL;
1671 rr->NR_AdditionalTo = mDNSNULL;
1672 if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1673 // rr->LastAPTime = Set for us in InitializeLastAPTime()
1674 // rr->LastMCTime = Set for us in InitializeLastAPTime()
1675 // rr->LastMCInterface = Set for us in InitializeLastAPTime()
1676 rr->NewRData = mDNSNULL;
1677 rr->newrdlength = 0;
1678 rr->UpdateCallback = mDNSNULL;
1679 rr->UpdateCredits = kMaxUpdateCredits;
1680 rr->NextUpdateCredit = 0;
1681 rr->UpdateBlocked = 0;
1682
1683 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1684 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1685
1686 // Field Group 4: Transient uDNS state for Authoritative Records
1687 rr->state = regState_Zero;
1688 rr->uselease = 0;
1689 rr->expire = 0;
1690 rr->Private = 0;
1691 rr->updateid = zeroID;
1692 rr->updateIntID = zeroOpaque64;
1693 rr->zone = rr->resrec.name;
1694 rr->nta = mDNSNULL;
1695 rr->tcp = mDNSNULL;
1696 rr->OrigRData = 0;
1697 rr->OrigRDLen = 0;
1698 rr->InFlightRData = 0;
1699 rr->InFlightRDLen = 0;
1700 rr->QueuedRData = 0;
1701 rr->QueuedRDLen = 0;
1702 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1703 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1704 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1705 // times with different values if the external NAT port changes during the lifetime of the service registration.
1706 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1707
1708 // rr->resrec.interface = already set in mDNS_SetupResourceRecord
1709 // rr->resrec.name->c = MUST be set by client
1710 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord
1711 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord
1712 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord
1713 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1714
1715 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1716 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1717 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1718 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1719
1720 if (rr->AutoTarget)
1721 {
1722 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1723 #ifndef UNICAST_DISABLED
1724 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1725 // In this case we leave the record half-formed in the list, and later we'll remove it from the list and re-add it properly.
1726 if (rr->state == regState_NoTarget)
1727 {
1728 // Initialize the target so that we don't crash while logging etc.
1729 domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1730 if (tar) tar->c[0] = 0;
1731 LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1732 }
1733 #endif
1734 }
1735 else
1736 {
1737 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse);
1738 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1739 }
1740
1741 if (!ValidateDomainName(rr->resrec.name))
1742 { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1743
1744 // Don't do this until *after* we've set rr->resrec.rdlength
1745 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1746 { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1747
1748 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
1749 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1750
1751 if (RRLocalOnly(rr))
1752 {
1753 // If this is supposed to be unique, make sure we don't have any name conflicts.
1754 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1755 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1756 // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1757 // Hence, just bail out.
1758 // This comment is doesn’t make any sense. -- SC
1759 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1760 {
1761 if (CheckAuthRecordConflict(&m->rrauth, rr))
1762 {
1763 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1764 return mStatus_NameConflict;
1765 }
1766 }
1767 }
1768
1769 // For uDNS records, we don't support duplicate checks at this time.
1770 #ifndef UNICAST_DISABLED
1771 if (AuthRecord_uDNS(rr))
1772 {
1773 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1774 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1775 // records to the list, so we now need to update p to advance to the new end to the list before appending our new record.
1776 while (*p) p=&(*p)->next;
1777 *p = rr;
1778 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1779 rr->ProbeCount = 0;
1780 rr->ProbeRestartCount = 0;
1781 rr->AnnounceCount = 0;
1782 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1783 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point
1784 }
1785 #endif
1786
1787 // Now that we've finished building our new record, make sure it's not identical to one we already have
1788 if (RRLocalOnly(rr))
1789 {
1790 rr->ProbeCount = 0;
1791 rr->ProbeRestartCount = 0;
1792 rr->AnnounceCount = 0;
1793 r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1794 }
1795 else
1796 {
1797 for (r = m->ResourceRecords; r; r=r->next)
1798 if (RecordIsLocalDuplicate(r, rr))
1799 {
1800 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1801 else break;
1802 }
1803 }
1804
1805 if (r)
1806 {
1807 LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr));
1808 *d = rr;
1809 // If the previous copy of this record is already verified unique,
1810 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1811 // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1812 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1813 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1814 rr->ProbeCount = 0;
1815 }
1816 else
1817 {
1818 LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1819 if (RRLocalOnly(rr))
1820 {
1821 AuthGroup *ag;
1822 ag = InsertAuthRecord(m, &m->rrauth, rr);
1823 if (ag && !ag->NewLocalOnlyRecords)
1824 {
1825 m->NewLocalOnlyRecords = mDNStrue;
1826 ag->NewLocalOnlyRecords = rr;
1827 }
1828 // No probing for LocalOnly records; acknowledge them right away
1829 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1830 AcknowledgeRecord(m, rr);
1831 return(mStatus_NoError);
1832 }
1833 else
1834 {
1835 if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1836 *p = rr;
1837 }
1838 }
1839
1840 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above
1841 {
1842 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1843 IncrementAutoTargetServices(m, rr);
1844
1845 // For records that are not going to probe, acknowledge them right away
1846 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1847 AcknowledgeRecord(m, rr);
1848
1849 // Adding a record may affect whether or not we should sleep
1850 mDNS_UpdateAllowSleep(m);
1851 }
1852
1853 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1854 // This is used by the in-NIC proxy to send the keepalive packets.
1855 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1856 {
1857 mDNSAddr raddr;
1858 // Set the record type to known unique to prevent probing keep alive records.
1859 // Also make sure we do not announce the keepalive records.
1860 rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1861 rr->AnnounceCount = 0;
1862 getKeepaliveRaddr(m, rr, &raddr);
1863 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1864 // asynchronous task to update the resource record
1865 mDNSPlatformGetRemoteMacAddr(&raddr);
1866 }
1867
1868 return(mStatus_NoError);
1869 }
1870
1871 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1872 {
1873 m->ProbeFailTime = m->timenow;
1874 m->NumFailedProbes++;
1875 // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1876 // If a bunch of hosts have all been configured with the same name, then they'll all
1877 // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1878 // up to name-10. After that they'll start adding random increments in the range 1-100,
1879 // so they're more likely to branch out in the available namespace and settle on a set of
1880 // unique names quickly. If after five more tries the host is still conflicting, then we
1881 // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1882 if (m->NumFailedProbes >= 15)
1883 {
1884 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1885 LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1886 m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1887 }
1888 }
1889
1890 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1891 {
1892 RData *OldRData = rr->resrec.rdata;
1893 mDNSu16 OldRDLen = rr->resrec.rdlength;
1894 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata
1895 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
1896 if (rr->UpdateCallback)
1897 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know
1898 }
1899
1900 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1901 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1902 // Exported so uDNS.c can call this
1903 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1904 {
1905 AuthRecord *r2;
1906 mDNSu8 RecordType = rr->resrec.RecordType;
1907 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
1908 mDNSBool dupList = mDNSfalse;
1909
1910 if (RRLocalOnly(rr))
1911 {
1912 AuthGroup *a;
1913 AuthRecord **rp;
1914
1915 a = AuthGroupForRecord(&m->rrauth, &rr->resrec);
1916 if (!a) return mDNSfalse;
1917 rp = &a->members;
1918 while (*rp && *rp != rr) rp=&(*rp)->next;
1919 p = rp;
1920 }
1921 else
1922 {
1923 while (*p && *p != rr) p=&(*p)->next;
1924 }
1925
1926 if (*p)
1927 {
1928 // We found our record on the main list. See if there are any duplicates that need special handling.
1929 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment
1930 {
1931 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1932 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1933 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1934 }
1935 else
1936 {
1937 // Before we delete the record (and potentially send a goodbye packet)
1938 // first see if we have a record on the duplicate list ready to take over from it.
1939 AuthRecord **d = &m->DuplicateRecords;
1940 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1941 if (*d)
1942 {
1943 AuthRecord *dup = *d;
1944 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1945 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1946 *d = dup->next; // Cut replacement record from DuplicateRecords list
1947 if (RRLocalOnly(rr))
1948 {
1949 dup->next = mDNSNULL;
1950 if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1951 }
1952 else
1953 {
1954 dup->next = rr->next; // And then...
1955 rr->next = dup; // ... splice it in right after the record we're about to delete
1956 }
1957 dup->resrec.RecordType = rr->resrec.RecordType;
1958 dup->ProbeCount = rr->ProbeCount;
1959 dup->ProbeRestartCount = rr->ProbeRestartCount;
1960 dup->AnnounceCount = rr->AnnounceCount;
1961 dup->RequireGoodbye = rr->RequireGoodbye;
1962 dup->AnsweredLocalQ = rr->AnsweredLocalQ;
1963 dup->ImmedAnswer = rr->ImmedAnswer;
1964 dup->ImmedUnicast = rr->ImmedUnicast;
1965 dup->ImmedAdditional = rr->ImmedAdditional;
1966 dup->v4Requester = rr->v4Requester;
1967 dup->v6Requester = rr->v6Requester;
1968 dup->ThisAPInterval = rr->ThisAPInterval;
1969 dup->LastAPTime = rr->LastAPTime;
1970 dup->LastMCTime = rr->LastMCTime;
1971 dup->LastMCInterface = rr->LastMCInterface;
1972 dup->Private = rr->Private;
1973 dup->state = rr->state;
1974 rr->RequireGoodbye = mDNSfalse;
1975 rr->AnsweredLocalQ = mDNSfalse;
1976 }
1977 }
1978 }
1979 else
1980 {
1981 // We didn't find our record on the main list; try the DuplicateRecords list instead.
1982 p = &m->DuplicateRecords;
1983 while (*p && *p != rr) p=&(*p)->next;
1984 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1985 if (*p)
1986 {
1987 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1988 // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1989 // also that have been marked above in this function. In that case, we come here and if we don't
1990 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1991 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1992 // details.
1993 rr->WakeUp.HMAC = zeroEthAddr;
1994 rr->RequireGoodbye = mDNSfalse;
1995 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1996 dupList = mDNStrue;
1997 }
1998 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1999 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2000 }
2001
2002 if (!*p)
2003 {
2004 // No need to log an error message if we already know this is a potentially repeated deregistration
2005 if (drt != mDNS_Dereg_repeat)
2006 LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
2007 return(mStatus_BadReferenceErr);
2008 }
2009
2010 // If this is a shared record and we've announced it at least once,
2011 // we need to retract that announcement before we delete the record
2012
2013 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2014 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2015 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2016 // mechanism to cope with the client callback modifying the question list while that's happening.
2017 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2018 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2019 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2020 // records, thereby invoking yet more callbacks, without limit.
2021 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2022 // actual goodbye packets.
2023
2024 #ifndef UNICAST_DISABLED
2025 if (AuthRecord_uDNS(rr))
2026 {
2027 if (rr->RequireGoodbye)
2028 {
2029 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2030 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2031 m->LocalRemoveEvents = mDNStrue;
2032 uDNS_DeregisterRecord(m, rr);
2033 // At this point unconditionally we bail out
2034 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2035 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2036 // process and will complete asynchronously. Either way we don't need to do anything more here.
2037 return(mStatus_NoError);
2038 }
2039 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2040 // from the server. In that case, if the records have been part of a group update, clear the
2041 // state here.
2042 rr->updateid = zeroID;
2043
2044 // We defer cleaning up NAT state only after sending goodbyes. This is important because
2045 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2046 // This happens today when we turn on/off interface where we get multiple network transitions
2047 // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2048 // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2049 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2050 // NAT state here takes care of the case where we did not send goodbyes at all.
2051 if (rr->NATinfo.clientContext)
2052 {
2053 mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2054 rr->NATinfo.clientContext = mDNSNULL;
2055 }
2056 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
2057 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2058 }
2059 #endif // UNICAST_DISABLED
2060
2061 if (RecordType == kDNSRecordTypeUnregistered)
2062 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
2063 else if (RecordType == kDNSRecordTypeDeregistering)
2064 {
2065 LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
2066 return(mStatus_BadReferenceErr);
2067 }
2068
2069 if (rr->WakeUp.HMAC.l[0] ||
2070 (((RecordType == kDNSRecordTypeShared) || (rr->ARType == AuthRecordLocalOnly)) &&
2071 (rr->RequireGoodbye || rr->AnsweredLocalQ)))
2072 {
2073 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
2074 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2075 rr->resrec.rroriginalttl = 0;
2076 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
2077 rr->ThisAPInterval = mDNSPlatformOneSecond * 2;
2078 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
2079 m->LocalRemoveEvents = mDNStrue;
2080 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
2081 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
2082 }
2083 else
2084 {
2085 if (!dupList && RRLocalOnly(rr))
2086 {
2087 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
2088 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
2089 }
2090 else
2091 {
2092 *p = rr->next; // Cut this record from the list
2093 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
2094 DecrementAutoTargetServices(m, rr);
2095 }
2096 // If someone is about to look at this, bump the pointer forward
2097 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
2098 rr->next = mDNSNULL;
2099
2100 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
2101 rr->resrec.RecordType = kDNSRecordTypeUnregistered;
2102
2103 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
2104 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2105 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2106
2107 // If we have an update queued up which never executed, give the client a chance to free that memory
2108 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
2109
2110
2111 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2112 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2113 // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2114 // so any attempt to touch rr after this is likely to lead to a crash.
2115 if (drt != mDNS_Dereg_conflict)
2116 {
2117 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2118 LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr));
2119 if (rr->RecordCallback)
2120 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this
2121 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2122 }
2123 else
2124 {
2125 RecordProbeFailure(m, rr);
2126 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
2127 if (rr->RecordCallback)
2128 rr->RecordCallback(m, rr, mStatus_NameConflict); // MUST NOT touch rr after this
2129 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
2130 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2131 // Note that with all the client callbacks going on, by the time we get here all the
2132 // records we marked may have been explicitly deregistered by the client anyway.
2133 r2 = m->DuplicateRecords;
2134 while (r2)
2135 {
2136 if (r2->ProbeCount != 0xFF)
2137 {
2138 r2 = r2->next;
2139 }
2140 else
2141 {
2142 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2143 // See if this record was also registered with any D2D plugins.
2144 D2D_stop_advertising_record(r2);
2145 #endif
2146 mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
2147 // As this is a duplicate record, it will be unlinked from the list
2148 // immediately
2149 r2 = m->DuplicateRecords;
2150 }
2151 }
2152 }
2153 }
2154 mDNS_UpdateAllowSleep(m);
2155 return(mStatus_NoError);
2156 }
2157
2158 // ***************************************************************************
2159 #if COMPILER_LIKES_PRAGMA_MARK
2160 #pragma mark -
2161 #pragma mark - Packet Sending Functions
2162 #endif
2163
2164 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
2165 {
2166 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
2167 {
2168 **nrpp = rr;
2169 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2170 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2171 // The referenced record will definitely be acceptable (by recursive application of this rule)
2172 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
2173 rr->NR_AdditionalTo = add;
2174 *nrpp = &rr->NextResponse;
2175 }
2176 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2177 }
2178
2179 mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID)
2180 {
2181 AuthRecord *rr2;
2182 if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask)
2183 {
2184 for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next)
2185 {
2186 if ((rr2->resrec.namehash == additional->resrec.namehash) &&
2187 (rr2->resrec.rrtype == additional->resrec.rrtype) &&
2188 (rr2 != additional) &&
2189 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) &&
2190 (rr2->resrec.rrclass == additional->resrec.rrclass) &&
2191 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&
2192 SameDomainName(rr2->resrec.name, additional->resrec.name))
2193 {
2194 AddRecordToResponseList(nrpp, rr2, rr);
2195 }
2196 }
2197 }
2198 }
2199
2200 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
2201 {
2202 AuthRecord *rr, *rr2;
2203 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put
2204 {
2205 // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2206 // later in the "for" loop, and we will follow further "additional" links then.)
2207 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
2208 {
2209 AddRecordToResponseList(nrpp, rr->Additional1, rr);
2210 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID);
2211 }
2212
2213 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
2214 {
2215 AddRecordToResponseList(nrpp, rr->Additional2, rr);
2216 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID);
2217 }
2218
2219 // For SRV records, automatically add the Address record(s) for the target host
2220 if (rr->resrec.rrtype == kDNSType_SRV)
2221 {
2222 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2223 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2224 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2225 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target
2226 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
2227 AddRecordToResponseList(nrpp, rr2, rr);
2228 }
2229 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional
2230 {
2231 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records
2232 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ...
2233 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ...
2234 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name
2235 SameDomainName(rr->resrec.name, rr2->resrec.name))
2236 AddRecordToResponseList(nrpp, rr2, rr);
2237 }
2238 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record
2239 {
2240 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
2241 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2242 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
2243 }
2244 }
2245 }
2246
2247 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
2248 {
2249 AuthRecord *rr;
2250 AuthRecord *ResponseRecords = mDNSNULL;
2251 AuthRecord **nrp = &ResponseRecords;
2252 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2253
2254 // Make a list of all our records that need to be unicast to this destination
2255 for (rr = m->ResourceRecords; rr; rr=rr->next)
2256 {
2257 // If we find we can no longer unicast this answer, clear ImmedUnicast
2258 if (rr->ImmedAnswer == mDNSInterfaceMark ||
2259 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
2260 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) )
2261 rr->ImmedUnicast = mDNSfalse;
2262
2263 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
2264 {
2265 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
2266 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
2267 {
2268 rr->ImmedAnswer = mDNSNULL; // Clear the state fields
2269 rr->ImmedUnicast = mDNSfalse;
2270 rr->v4Requester = zerov4Addr;
2271 rr->v6Requester = zerov6Addr;
2272
2273 // Only sent records registered for P2P over P2P interfaces
2274 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))
2275 {
2276 continue;
2277 }
2278
2279 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo
2280 {
2281 rr->NR_AnswerTo = NR_AnswerMulticast;
2282 *nrp = rr;
2283 nrp = &rr->NextResponse;
2284 }
2285 }
2286 }
2287 }
2288
2289 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
2290
2291 while (ResponseRecords)
2292 {
2293 mDNSu8 *responseptr = m->omsg.data;
2294 mDNSu8 *newptr;
2295 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2296
2297 // Put answers in the packet
2298 while (ResponseRecords && ResponseRecords->NR_AnswerTo)
2299 {
2300 rr = ResponseRecords;
2301 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2302 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2303
2304 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
2305
2306 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2307 if (!newptr && m->omsg.h.numAnswers)
2308 {
2309 break; // If packet full, send it now
2310 }
2311 if (newptr) responseptr = newptr;
2312 ResponseRecords = rr->NextResponse;
2313 rr->NextResponse = mDNSNULL;
2314 rr->NR_AnswerTo = mDNSNULL;
2315 rr->NR_AdditionalTo = mDNSNULL;
2316 rr->RequireGoodbye = mDNStrue;
2317 }
2318
2319 // Add additionals, if there's space
2320 while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2321 {
2322 rr = ResponseRecords;
2323 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2324 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2325 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2326 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2327
2328 if (newptr) responseptr = newptr;
2329 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2330 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2331 ResponseRecords = rr->NextResponse;
2332 rr->NextResponse = mDNSNULL;
2333 rr->NR_AnswerTo = mDNSNULL;
2334 rr->NR_AdditionalTo = mDNSNULL;
2335 }
2336
2337 if (m->omsg.h.numAnswers)
2338 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSfalse);
2339 }
2340 }
2341
2342 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2343 // and the client's mStatus_MemFree callback will have been invoked
2344 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2345 {
2346 LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2347 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2348 // it should go ahead and immediately dispose of this registration
2349 rr->resrec.RecordType = kDNSRecordTypeShared;
2350 rr->RequireGoodbye = mDNSfalse;
2351 rr->WakeUp.HMAC = zeroEthAddr;
2352 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; }
2353 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this
2354 }
2355
2356 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2357 // any deregistering records that remain in the m->ResourceRecords list.
2358 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2359 // which may change the record list and/or question list.
2360 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2361 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2362 {
2363 if (m->CurrentRecord)
2364 LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2365 m->CurrentRecord = m->ResourceRecords;
2366
2367 while (m->CurrentRecord)
2368 {
2369 AuthRecord *rr = m->CurrentRecord;
2370 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2371 CompleteDeregistration(m, rr); // Don't touch rr after this
2372 else
2373 m->CurrentRecord = rr->next;
2374 }
2375 }
2376
2377 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2378 {
2379 int i, val = 0;
2380 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2381 for (i=1; i<=src[0]; i++)
2382 {
2383 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2384 val = val * 10 + src[i] - '0';
2385 }
2386 if (val > 255) return(mStatus_Invalid);
2387 *dst = (mDNSu8)val;
2388 return(mStatus_NoError);
2389 }
2390
2391 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2392 {
2393 int skip = CountLabels(name) - 6;
2394 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2395 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2396 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2397 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2398 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2399 a->type = mDNSAddrType_IPv4;
2400 return(mStatus_NoError);
2401 }
2402
2403 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
2404 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
2405 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2406
2407 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2408 {
2409 int i, h, l;
2410 const domainname *n;
2411
2412 int skip = CountLabels(name) - 34;
2413 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2414
2415 n = SkipLeadingLabels(name, skip);
2416 for (i=0; i<16; i++)
2417 {
2418 if (n->c[0] != 1) return mStatus_Invalid;
2419 l = HexVal(n->c[1]);
2420 n = (const domainname *)(n->c + 2);
2421
2422 if (n->c[0] != 1) return mStatus_Invalid;
2423 h = HexVal(n->c[1]);
2424 n = (const domainname *)(n->c + 2);
2425
2426 if (l<0 || h<0) return mStatus_Invalid;
2427 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2428 }
2429
2430 a->type = mDNSAddrType_IPv6;
2431 return(mStatus_NoError);
2432 }
2433
2434 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2435 {
2436 int skip = CountLabels(name) - 2;
2437 if (skip >= 0)
2438 {
2439 const domainname *suffix = SkipLeadingLabels(name, skip);
2440 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2441 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6;
2442 }
2443 return(mDNSAddrType_None);
2444 }
2445
2446 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2447 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2448 {
2449 int i;
2450 mDNSu8 *ptr = m->omsg.data;
2451 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2452 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2453
2454 // 0x00 Destination address
2455 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2456
2457 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2458 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2459
2460 // 0x0C ARP Ethertype (0x0806)
2461 *ptr++ = 0x08; *ptr++ = 0x06;
2462
2463 // 0x0E ARP header
2464 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1
2465 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800
2466 *ptr++ = 6; // Hardware address length
2467 *ptr++ = 4; // Protocol address length
2468 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2
2469
2470 // 0x16 Sender hardware address (our MAC address)
2471 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2472
2473 // 0x1C Sender protocol address
2474 for (i=0; i<4; i++) *ptr++ = spa->b[i];
2475
2476 // 0x20 Target hardware address
2477 for (i=0; i<6; i++) *ptr++ = tha->b[i];
2478
2479 // 0x26 Target protocol address
2480 for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2481
2482 // 0x2A Total ARP Packet length 42 bytes
2483 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2484 }
2485
2486 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2487 {
2488 const mDNSu16 *ptr = data;
2489 while (length > 0) { length -= 2; sum += *ptr++; }
2490 sum = (sum & 0xFFFF) + (sum >> 16);
2491 sum = (sum & 0xFFFF) + (sum >> 16);
2492 return(sum != 0xFFFF ? sum : 0);
2493 }
2494
2495 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2496 {
2497 IPv6PseudoHeader ph;
2498 ph.src = *src;
2499 ph.dst = *dst;
2500 ph.len.b[0] = length >> 24;
2501 ph.len.b[1] = length >> 16;
2502 ph.len.b[2] = length >> 8;
2503 ph.len.b[3] = length;
2504 ph.pro.b[0] = 0;
2505 ph.pro.b[1] = 0;
2506 ph.pro.b[2] = 0;
2507 ph.pro.b[3] = protocol;
2508 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2509 }
2510
2511 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2512 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2513 {
2514 int i;
2515 mDNSOpaque16 checksum;
2516 mDNSu8 *ptr = m->omsg.data;
2517 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2518 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2519 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2520 const mDNSv6Addr mc = { { 0xFF,0x02,0x00,0x00, 0,0,0,0, 0,0,0,1, 0xFF,tpa->b[0xD],tpa->b[0xE],tpa->b[0xF] } };
2521 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2522 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2523 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2524
2525 // 0x00 Destination address
2526 for (i=0; i<6; i++) *ptr++ = dst->b[i];
2527 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2528 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2529 // link with a pointless link-layer multicast.
2530 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2531 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2532 // *ptr++ = 0x33;
2533 // *ptr++ = 0x33;
2534 // *ptr++ = 0xFF;
2535 // *ptr++ = tpa->b[0xD];
2536 // *ptr++ = tpa->b[0xE];
2537 // *ptr++ = tpa->b[0xF];
2538
2539 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2540 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2541
2542 // 0x0C IPv6 Ethertype (0x86DD)
2543 *ptr++ = 0x86; *ptr++ = 0xDD;
2544
2545 // 0x0E IPv6 header
2546 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label
2547 *ptr++ = 0x00; *ptr++ = 0x20; // Length
2548 *ptr++ = 0x3A; // Protocol == ICMPv6
2549 *ptr++ = 0xFF; // Hop Limit
2550
2551 // 0x16 Sender IPv6 address
2552 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2553
2554 // 0x26 Destination IPv6 address
2555 for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2556
2557 // 0x36 NDP header
2558 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2559 *ptr++ = 0x00; // Code
2560 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39)
2561 *ptr++ = flags;
2562 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2563
2564 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek.
2565 {
2566 // 0x3E NDP target.
2567 for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2568 // 0x4E Source Link-layer Address
2569 // <http://www.ietf.org/rfc/rfc2461.txt>
2570 // MUST NOT be included when the source IP address is the unspecified address.
2571 // Otherwise, on link layers that have addresses this option MUST be included
2572 // in multicast solicitations and SHOULD be included in unicast solicitations.
2573 if (!mDNSIPv6AddressIsZero(*spa))
2574 {
2575 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2576 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2577 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2578 }
2579 }
2580 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2581 {
2582 // 0x3E NDP target.
2583 for (i=0; i<16; i++) *ptr++ = spa->b[i];
2584 // 0x4E Target Link-layer Address
2585 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2586 *ptr++ = 0x01; // Option length 1 (in units of 8 octets)
2587 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i];
2588 }
2589
2590 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2591 m->omsg.data[0x13] = ptr - &m->omsg.data[0x36]; // Compute actual length
2592 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2593 m->omsg.data[0x38] = checksum.b[0];
2594 m->omsg.data[0x39] = checksum.b[1];
2595
2596 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2597 }
2598
2599 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2600 {
2601 mDNSu32 DNS_VERS = _DNS_SD_H;
2602 Trace->u.tracer.platf = m->mDNS_plat;
2603 Trace->u.tracer.mDNSv = DNS_VERS;
2604
2605 Trace->opt = kDNSOpt_Trace;
2606 Trace->optlen = DNSOpt_TraceData_Space - 4;
2607 }
2608
2609 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2610 {
2611 owner->u.owner.vers = 0;
2612 owner->u.owner.seq = m->SleepSeqNum;
2613 owner->u.owner.HMAC = m->PrimaryMAC;
2614 owner->u.owner.IMAC = intf->MAC;
2615 owner->u.owner.password = zeroEthAddr;
2616
2617 // Don't try to compute the optlen until *after* we've set up the data fields
2618 // Right now the DNSOpt_Owner_Space macro does not depend on the owner->u.owner being set up correctly, but in the future it might
2619 owner->opt = kDNSOpt_Owner;
2620 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2621 }
2622
2623 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2624 {
2625 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2626 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2627 }
2628
2629 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2630 {
2631 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2632 // and hence there is no need to check for Transfering state. But if we have sleep
2633 // proxies and partially sending goodbyes for some records, we will be in Transfering
2634 // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2635 // we are not awake handles both cases.
2636 if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2637 {
2638 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2639 return mDNStrue;
2640 }
2641
2642 if (m->SleepState != SleepState_Sleeping)
2643 return mDNSfalse;
2644
2645 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2646 // whether you can send goodbyes or not.
2647 if (!intf->SendGoodbyes)
2648 {
2649 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2650 return mDNSfalse;
2651 }
2652 else
2653 {
2654 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2655 return mDNStrue;
2656 }
2657 }
2658
2659 // Note about acceleration of announcements to facilitate automatic coalescing of
2660 // multiple independent threads of announcements into a single synchronized thread:
2661 // The announcements in the packet may be at different stages of maturity;
2662 // One-second interval, two-second interval, four-second interval, and so on.
2663 // After we've put in all the announcements that are due, we then consider
2664 // whether there are other nearly-due announcements that are worth accelerating.
2665 // To be eligible for acceleration, a record MUST NOT be older (further along
2666 // its timeline) than the most mature record we've already put in the packet.
2667 // In other words, younger records can have their timelines accelerated to catch up
2668 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2669 // Older records cannot have their timelines accelerated; this would just widen
2670 // the gap between them and their younger bretheren and get them even more out of sync.
2671
2672 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2673 // the record list and/or question list.
2674 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2675 mDNSlocal void SendResponses(mDNS *const m)
2676 {
2677 int pktcount = 0;
2678 AuthRecord *rr, *r2;
2679 mDNSs32 maxExistingAnnounceInterval = 0;
2680 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2681
2682 m->NextScheduledResponse = m->timenow + FutureTime;
2683
2684 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2685
2686 for (rr = m->ResourceRecords; rr; rr=rr->next)
2687 if (rr->ImmedUnicast)
2688 {
2689 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2690 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2691 v4.ip.v4 = rr->v4Requester;
2692 v6.ip.v6 = rr->v6Requester;
2693 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2694 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2695 if (rr->ImmedUnicast)
2696 {
2697 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2698 rr->ImmedUnicast = mDNSfalse;
2699 }
2700 }
2701
2702 // ***
2703 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2704 // ***
2705
2706 // Run through our list of records, and decide which ones we're going to announce on all interfaces
2707 for (rr = m->ResourceRecords; rr; rr=rr->next)
2708 {
2709 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2710 if (TimeToAnnounceThisRecord(rr, m->timenow))
2711 {
2712 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2713 {
2714 if (!rr->WakeUp.HMAC.l[0])
2715 {
2716 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces
2717 }
2718 else
2719 {
2720 mDNSBool unicastOnly;
2721 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2722 unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse;
2723 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly);
2724 for (r2 = rr; r2; r2=r2->next)
2725 if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2726 mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2727 {
2728 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2729 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2730 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2731 {
2732 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2733 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2734 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2735 }
2736 r2->LastAPTime = m->timenow;
2737 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2738 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2739 }
2740 }
2741 }
2742 else if (ResourceRecordIsValidAnswer(rr))
2743 {
2744 if (rr->AddressProxy.type)
2745 {
2746 if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2747 {
2748 rr->AnnounceCount--;
2749 rr->ThisAPInterval *= 2;
2750 rr->LastAPTime = m->timenow;
2751 if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2752 {
2753 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2754 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2755 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2756 }
2757 else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2758 {
2759 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2760 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2761 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2762 }
2763 }
2764 }
2765 else
2766 {
2767 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2768 if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2769 maxExistingAnnounceInterval = rr->ThisAPInterval;
2770 if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2771 }
2772 }
2773 }
2774 }
2775
2776 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2777 // Eligible records that are more than half-way to their announcement time are accelerated
2778 for (rr = m->ResourceRecords; rr; rr=rr->next)
2779 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2780 (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2781 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2782 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate
2783 ResourceRecordIsValidAnswer(rr)))
2784 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces
2785
2786 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2787 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2788 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2789 // then all that means is that it won't get sent -- which would not be the end of the world.
2790 for (rr = m->ResourceRecords; rr; rr=rr->next)
2791 {
2792 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2793 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records
2794 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ...
2795 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ...
2796 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ...
2797 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target
2798 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2799 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2800 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too
2801 // We also make sure we send the DeviceInfo TXT record too, if necessary
2802 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2803 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2804 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2805 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2806 {
2807 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2808 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2809 }
2810 }
2811
2812 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2813 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2814 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2815 // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2816 // -- If a record is marked to be sent on a certain interface, make sure the whole set is marked to be sent on that interface
2817 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2818 for (rr = m->ResourceRecords; rr; rr=rr->next)
2819 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2820 {
2821 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked
2822 {
2823 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2824 {
2825 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2826 (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) &&
2827 SameResourceRecordSignature(r2, rr) &&
2828 ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer)))
2829 {
2830 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2831 }
2832 }
2833 }
2834 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked
2835 {
2836 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2837 {
2838 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2839 (r2->ImmedAdditional != rr->ImmedAdditional) &&
2840 SameResourceRecordSignature(r2, rr) &&
2841 IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional))
2842 {
2843 r2->ImmedAdditional = rr->ImmedAdditional;
2844 }
2845 }
2846 }
2847 }
2848
2849 // Now set SendRNow state appropriately
2850 for (rr = m->ResourceRecords; rr; rr=rr->next)
2851 {
2852 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces
2853 {
2854 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2855 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer
2856 rr->LastMCTime = m->timenow;
2857 rr->LastMCInterface = rr->ImmedAnswer;
2858 rr->ProbeRestartCount = 0; // Reset the probe restart count
2859 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2860 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2861 {
2862 rr->AnnounceCount--;
2863 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2864 rr->ThisAPInterval *= 2;
2865 rr->LastAPTime = m->timenow;
2866 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2867 }
2868 }
2869 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface:
2870 {
2871 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface
2872 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too
2873 rr->LastMCTime = m->timenow;
2874 rr->LastMCInterface = rr->ImmedAnswer;
2875 }
2876 SetNextAnnounceProbeTime(m, rr);
2877 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2878 }
2879
2880 // ***
2881 // *** 2. Loop through interface list, sending records as appropriate
2882 // ***
2883
2884 while (intf)
2885 {
2886 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2887 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2888 int numDereg = 0;
2889 int numAnnounce = 0;
2890 int numAnswer = 0;
2891 mDNSu8 *responseptr = m->omsg.data;
2892 mDNSu8 *newptr;
2893 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2894
2895 // First Pass. Look for:
2896 // 1. Deregistering records that need to send their goodbye packet
2897 // 2. Updated records that need to retract their old data
2898 // 3. Answers and announcements we need to send
2899 for (rr = m->ResourceRecords; rr; rr=rr->next)
2900 {
2901
2902 // Skip this interface if the record InterfaceID is *Any and the record is not
2903 // appropriate for the interface type.
2904 if ((rr->SendRNow == intf->InterfaceID) &&
2905 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)))
2906 {
2907 rr->SendRNow = GetNextActiveInterfaceID(intf);
2908 }
2909 else if (rr->SendRNow == intf->InterfaceID)
2910 {
2911 RData *OldRData = rr->resrec.rdata;
2912 mDNSu16 oldrdlength = rr->resrec.rdlength;
2913 mDNSu8 active = (mDNSu8)
2914 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2915 newptr = mDNSNULL;
2916 if (rr->NewRData && active)
2917 {
2918 // See if we should send a courtesy "goodbye" for the old data before we replace it.
2919 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2920 {
2921 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2922 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2923 else continue; // If this packet is already too full to hold the goodbye for this record, skip it for now and we'll retry later
2924 }
2925 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2926 }
2927
2928 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2929 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2930 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2931 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2932 if (newptr)
2933 {
2934 responseptr = newptr;
2935 rr->RequireGoodbye = active;
2936 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2937 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2938 }
2939
2940 if (rr->NewRData && active)
2941 SetNewRData(&rr->resrec, OldRData, oldrdlength);
2942
2943 // The first time through (pktcount==0), if this record is verified unique
2944 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2945 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2946 rr->SendNSECNow = mDNSInterfaceMark;
2947
2948 if (newptr) // If succeeded in sending, advance to next interface
2949 {
2950 // If sending on all interfaces, go to next interface; else we're finished now
2951 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2952 rr->SendRNow = GetNextActiveInterfaceID(intf);
2953 else
2954 rr->SendRNow = mDNSNULL;
2955 }
2956 }
2957 }
2958
2959 // Second Pass. Add additional records, if there's space.
2960 newptr = responseptr;
2961 for (rr = m->ResourceRecords; rr; rr=rr->next)
2962 if (rr->ImmedAdditional == intf->InterfaceID)
2963 if (ResourceRecordIsValidAnswer(rr))
2964 {
2965 // If we have at least one answer already in the packet, then plan to add additionals too
2966 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2967
2968 // If we're not planning to send any additionals, but this record is a unique one, then
2969 // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2970 // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2971 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2972 {
2973 const AuthRecord *a;
2974 for (a = m->ResourceRecords; a; a=a->next)
2975 if (a->LastMCTime == m->timenow &&
2976 a->LastMCInterface == intf->InterfaceID &&
2977 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2978 }
2979 if (!SendAdditional) // If we don't want to send this after all,
2980 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field
2981 else if (newptr) // Else, try to add it if we can
2982 {
2983 // The first time through (pktcount==0), if this record is verified unique
2984 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2985 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2986 rr->SendNSECNow = mDNSInterfaceMark;
2987
2988 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2989 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it
2990 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2991 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state
2992 if (newptr)
2993 {
2994 responseptr = newptr;
2995 rr->ImmedAdditional = mDNSNULL;
2996 rr->RequireGoodbye = mDNStrue;
2997 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2998 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2999 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3000 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3001 rr->LastMCTime = m->timenow;
3002 rr->LastMCInterface = intf->InterfaceID;
3003 }
3004 }
3005 }
3006
3007 // Third Pass. Add NSEC records, if there's space.
3008 // When we're generating an NSEC record in response to a specify query for that type
3009 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3010 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3011 for (rr = m->ResourceRecords; rr; rr=rr->next)
3012 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
3013 {
3014 AuthRecord nsec;
3015 mDNSu8 *ptr;
3016 int len;
3017 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3018 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
3019 AssignDomainName(&nsec.namestorage, rr->resrec.name);
3020 ptr = nsec.rdatastorage.u.data;
3021 len = DomainNameLength(rr->resrec.name);
3022 // We have a nxt name followed by window number, window length and a window bitmap
3023 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
3024 if (nsec.resrec.rdlength <= StandardAuthRDSize)
3025 {
3026 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
3027 AssignDomainName((domainname *)ptr, rr->resrec.name);
3028 ptr += len;
3029 *ptr++ = 0; // window number
3030 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
3031 for (r2 = m->ResourceRecords; r2; r2=r2->next)
3032 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
3033 {
3034 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
3035 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
3036 }
3037 newptr = responseptr;
3038 if (!r2) // If we successfully built our NSEC record, add it to the packet now
3039 {
3040 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
3041 if (newptr) responseptr = newptr;
3042 }
3043 }
3044 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength);
3045
3046 // If we successfully put the NSEC record, clear the SendNSECNow flag
3047 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3048 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
3049 {
3050 rr->SendNSECNow = mDNSNULL;
3051 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3052 for (r2 = rr->next; r2; r2=r2->next)
3053 if (SameResourceRecordNameClassInterface(r2, rr))
3054 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
3055 r2->SendNSECNow = mDNSNULL;
3056 }
3057 }
3058
3059 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
3060 {
3061 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3062 if (OwnerRecordSpace || TraceRecordSpace)
3063 {
3064 AuthRecord opt;
3065 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3066 opt.resrec.rrclass = NormalMaxDNSMessageData;
3067 opt.resrec.rdlength = sizeof(rdataOPT);
3068 opt.resrec.rdestimate = sizeof(rdataOPT);
3069 if (OwnerRecordSpace && TraceRecordSpace)
3070 {
3071 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
3072 opt.resrec.rdestimate += sizeof(rdataOPT);
3073 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3074 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3075 }
3076 else if (OwnerRecordSpace)
3077 {
3078 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3079 }
3080 else if (TraceRecordSpace)
3081 {
3082 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3083 }
3084 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
3085 if (newptr)
3086 {
3087 responseptr = newptr;
3088 }
3089 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
3090 {
3091 LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3092 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3093 }
3094 else
3095 {
3096 LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3097 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3098 }
3099 }
3100
3101 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3102 numDereg, numDereg == 1 ? "" : "s",
3103 numAnnounce, numAnnounce == 1 ? "" : "s",
3104 numAnswer, numAnswer == 1 ? "" : "s",
3105 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
3106
3107 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSfalse);
3108 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSfalse);
3109 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3110 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
3111 // There might be more things to send on this interface, so go around one more time and try again.
3112 }
3113 else // Nothing more to send on this interface; go to next
3114 {
3115 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3116 #if MDNS_DEBUGMSGS && 0
3117 const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3118 debugf(msg, intf, next);
3119 #endif
3120 intf = next;
3121 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3122 }
3123 }
3124
3125 // ***
3126 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3127 // ***
3128
3129 if (m->CurrentRecord)
3130 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3131 m->CurrentRecord = m->ResourceRecords;
3132 while (m->CurrentRecord)
3133 {
3134 rr = m->CurrentRecord;
3135 m->CurrentRecord = rr->next;
3136
3137 if (rr->SendRNow)
3138 {
3139 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
3140 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3141 IIDPrintable(rr->SendRNow), IIDPrintable(rr->resrec.InterfaceID), rr->resrec.RecordType, ARDisplayString(m, rr));
3142 rr->SendRNow = mDNSNULL;
3143 }
3144
3145 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3146 {
3147 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client
3148
3149 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
3150 {
3151 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3152 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this
3153 }
3154 else
3155 {
3156 rr->ImmedAnswer = mDNSNULL;
3157 rr->ImmedUnicast = mDNSfalse;
3158 rr->v4Requester = zerov4Addr;
3159 rr->v6Requester = zerov6Addr;
3160 }
3161 }
3162 }
3163 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
3164 }
3165
3166 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3167 // so we want to be lazy about how frequently we do it.
3168 // 1. If a cache record is currently referenced by *no* active questions,
3169 // then we don't mind expiring it up to a minute late (who will know?)
3170 // 2. Else, if a cache record is due for some of its final expiration queries,
3171 // we'll allow them to be late by up to 2% of the TTL
3172 // 3. Else, if a cache record has completed all its final expiration queries without success,
3173 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3174 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3175 // so allow at most 1/10 second lateness
3176 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3177 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3178 #define CacheCheckGracePeriod(CR) ( \
3179 ((CR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \
3180 ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50) : \
3181 ((CR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \
3182 ((CR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0)
3183
3184 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3185
3186 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
3187 {
3188 if (m->rrcache_nextcheck[slot] - event > 0)
3189 m->rrcache_nextcheck[slot] = event;
3190 if (m->NextCacheCheck - event > 0)
3191 m->NextCacheCheck = event;
3192 }
3193
3194 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3195 // rr->TimeRcvd
3196 // rr->resrec.rroriginalttl
3197 // rr->UnansweredQueries
3198 // rr->CRActiveQuestion
3199 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
3200 {
3201 rr->NextRequiredQuery = RRExpireTime(rr);
3202
3203 // If we have an active question, then see if we want to schedule a refresher query for this record.
3204 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3205 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3206 {
3207 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3208 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3209 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3210 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
3211 }
3212 ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr));
3213 }
3214
3215 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5)
3216 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5)
3217 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5)
3218
3219 // Delay before restarting questions on a flapping interface.
3220 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3)
3221 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3222 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3223 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7))
3224
3225 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3226 {
3227 if (interval < kMinimumReconfirmTime)
3228 interval = kMinimumReconfirmTime;
3229 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below
3230 interval = 0x10000000;
3231
3232 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3233 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3234 {
3235 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3236 // For all the reconfirmations in a given batch, we want to use the same random value
3237 // so that the reconfirmation questions can be grouped into a single query packet
3238 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime);
3239 interval += m->RandomReconfirmDelay % ((interval/3) + 1);
3240 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3;
3241 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
3242 SetNextCacheCheckTimeForRecord(m, rr);
3243 }
3244 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3245 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
3246 return(mStatus_NoError);
3247 }
3248
3249 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3250 // It also appends to the list of known answer records that need to be included,
3251 // and updates the forcast for the size of the known answer section.
3252 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
3253 DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3254 {
3255 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3256 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3257 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3258 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3259 if (!newptr)
3260 {
3261 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3262 return(mDNSfalse);
3263 }
3264 else
3265 {
3266 mDNSu32 forecast = *answerforecast;
3267 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3268 CacheRecord *cr;
3269 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update
3270
3271 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // If we have a resource record in our cache,
3272 if (cr->resrec.InterfaceID == q->SendQNow && // received on this interface
3273 !(cr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type
3274 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList && // which is not already in the known answer list
3275 cr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3276 SameNameCacheRecordAnswersQuestion(cr, q) && // which answers our question
3277 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away
3278 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1)
3279 {
3280 // We don't want to include unique records in the Known Answer section. The Known Answer section
3281 // is intended to suppress floods of shared-record replies from many other devices on the network.
3282 // That concept really does not apply to unique records, and indeed if we do send a query for
3283 // which we have a unique record already in our cache, then including that unique record as a
3284 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3285
3286 *ka = cr; // Link this record into our known answer chain
3287 ka = &cr->NextInKAList;
3288 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3289 forecast += 12 + cr->resrec.rdestimate;
3290 // If we're trying to put more than one question in this packet, and it doesn't fit
3291 // then undo that last question and try again next time
3292 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3293 {
3294 query->h.numQuestions--;
3295 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3296 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3297 ka = *kalistptrptr; // Go back to where we started and retract these answer records
3298 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3299 return(mDNSfalse); // Return false, so we'll try again in the next packet
3300 }
3301 }
3302
3303 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3304 *queryptr = newptr; // Update the packet pointer
3305 *answerforecast = forecast; // Update the forecast
3306 *kalistptrptr = ka; // Update the known answer list pointer
3307 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3308
3309 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // For every resource record in our cache,
3310 if (cr->resrec.InterfaceID == q->SendQNow && // received on this interface
3311 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList && // which is not in the known answer list
3312 SameNameCacheRecordAnswersQuestion(cr, q)) // which answers our question
3313 {
3314 cr->UnansweredQueries++; // indicate that we're expecting a response
3315 cr->LastUnansweredTime = m->timenow;
3316 SetNextCacheCheckTimeForRecord(m, cr);
3317 }
3318
3319 return(mDNStrue);
3320 }
3321 }
3322
3323 // When we have a query looking for a specified name, but there appear to be no answers with
3324 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3325 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3326 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3327 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3328 // A typical reconfirmation scenario might go like this:
3329 // Depth 0: Name "myhost.local" has no address records
3330 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3331 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3332 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3333 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3334 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3335 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth)
3336 {
3337 mDNSu32 slot;
3338 const CacheGroup *cg;
3339 CacheRecord *cr;
3340 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3341 if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3342 FORALL_CACHERECORDS(slot, cg, cr)
3343 {
3344 const domainname *crtarget;
3345 if (cr->resrec.InterfaceID != InterfaceID) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3346 if (cr->resrec.rdatahash != namehash) continue; // Skip records whose rdata hash doesn't match the name hash.
3347 crtarget = GetRRDomainNameTarget(&cr->resrec);
3348 if (crtarget && SameDomainName(crtarget, name))
3349 {
3350 LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth, InterfaceID, CRDisplayString(m, cr));
3351 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3352 if (depth < 5)
3353 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1);
3354 }
3355 }
3356 }
3357
3358 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3359 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3360 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3361 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3362 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3363 {
3364 CacheGroup *const cg = CacheGroupForName(m, namehash, name);
3365 const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3366 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3367 return(cr);
3368 }
3369
3370
3371 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3372 {
3373 #ifndef SPC_DISABLED
3374 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3375 const CacheRecord *cr, *bestcr = mDNSNULL;
3376 mDNSu32 bestmetric = 1000000;
3377 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3378 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name,
3379 if (cr != c0 && cr != c1) // that's not one we've seen before,
3380 if (SameNameCacheRecordAnswersQuestion(cr, q)) // and answers our browse query,
3381 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service...
3382 {
3383 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3384 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3385 }
3386 return(bestcr);
3387 #else // SPC_DISABLED
3388 (void) m;
3389 (void) q;
3390 (void) c0;
3391 (void) c1;
3392 (void) c1;
3393 return mDNSNULL;
3394 #endif // SPC_DISABLED
3395 }
3396
3397 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3398 {
3399 const CacheRecord *swap_sps;
3400 mDNSu32 metric1, metric2;
3401
3402 if (!(*sps1) || !(*sps2)) return;
3403 metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3404 metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3405 if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3406 {
3407 swap_sps = *sps1;
3408 *sps1 = *sps2;
3409 *sps2 = swap_sps;
3410 }
3411 }
3412
3413 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3414 {
3415 CheckAndSwapSPS(&sps[0], &sps[1]);
3416 CheckAndSwapSPS(&sps[0], &sps[2]);
3417 CheckAndSwapSPS(&sps[1], &sps[2]);
3418 }
3419
3420
3421 // Finds the three best Sleep Proxies we currently have in our cache
3422 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3423 {
3424 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3425 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL);
3426 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]);
3427
3428 // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3429 // only if they have equally good metric and support features.
3430 ReorderSPSByFeature(sps);
3431 }
3432
3433 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3434 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3435 {
3436 int i;
3437 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3438 }
3439
3440 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3441 {
3442 int i;
3443 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3444 }
3445
3446 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3447 {
3448 int i;
3449 mDNSBool v4 = !intf->IPv4Available; // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3450 mDNSBool v6 = !intf->IPv6Available; // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3451 for (i=0; i<DupSuppressInfoSize; i++)
3452 if (ds[i].InterfaceID == intf->InterfaceID)
3453 {
3454 if (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3455 else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3456 if (v4 && v6) return(mDNStrue);
3457 }
3458 return(mDNSfalse);
3459 }
3460
3461 mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3462 {
3463 int i, j;
3464
3465 // See if we have this one in our list somewhere already
3466 for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3467
3468 // If not, find a slot we can re-use
3469 if (i >= DupSuppressInfoSize)
3470 {
3471 i = 0;
3472 for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3473 if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3474 i = j;
3475 }
3476
3477 // Record the info about this query we saw
3478 ds[i].Time = Time;
3479 ds[i].InterfaceID = InterfaceID;
3480 ds[i].Type = Type;
3481 }
3482
3483 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3484 {
3485 int len, i, cnt;
3486 mDNSInterfaceID InterfaceID = q->InterfaceID;
3487 domainname *d = &q->qname;
3488
3489 // We can't send magic packets without knowing which interface to send it on.
3490 if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID))
3491 {
3492 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3493 return;
3494 }
3495
3496 // Split MAC@IPAddress and pass them separately
3497 len = d->c[0];
3498 cnt = 0;
3499 for (i = 1; i < len; i++)
3500 {
3501 if (d->c[i] == '@')
3502 {
3503 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3504 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3505 if (cnt != 5)
3506 {
3507 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3508 return;
3509 }
3510 if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3511 {
3512 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3513 return;
3514 }
3515 if ((len - i) > (int)(sizeof(IPAddr) - 1))
3516 {
3517 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3518 return;
3519 }
3520 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3521 EthAddr[i - 1] = 0;
3522 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3523 IPAddr[len - i] = 0;
3524 m->mDNSStats.WakeOnResolves++;
3525 mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3526 return;
3527 }
3528 else if (d->c[i] == ':')
3529 cnt++;
3530 }
3531 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3532 }
3533
3534
3535 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3536 {
3537 // If more than 90% of the way to the query time, we should unconditionally accelerate it
3538 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3539 return(mDNStrue);
3540
3541 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3542 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3543 {
3544 // We forecast: qname (n) type (2) class (2)
3545 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3546 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3547 const CacheRecord *cr;
3548 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // If we have a resource record in our cache,
3549 if (cr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet
3550 SameNameCacheRecordAnswersQuestion(cr, q) && // which answers our question
3551 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry
3552 cr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3553 {
3554 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3555 forecast += 12 + cr->resrec.rdestimate;
3556 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3557 }
3558 return(mDNStrue);
3559 }
3560
3561 return(mDNSfalse);
3562 }
3563
3564 // How Standard Queries are generated:
3565 // 1. The Question Section contains the question
3566 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3567
3568 // How Probe Queries are generated:
3569 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3570 // if some other host is already using *any* records with this name, we want to know about it.
3571 // 2. The Authority Section contains the proposed values we intend to use for one or more
3572 // of our records with that name (analogous to the Update section of DNS Update packets)
3573 // because if some other host is probing at the same time, we each want to know what the other is
3574 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3575
3576 mDNSlocal void SendQueries(mDNS *const m)
3577 {
3578 mDNSu32 slot;
3579 CacheGroup *cg;
3580 CacheRecord *cr;
3581 AuthRecord *ar;
3582 int pktcount = 0;
3583 DNSQuestion *q;
3584 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3585 mDNSs32 maxExistingQuestionInterval = 0;
3586 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3587 CacheRecord *KnownAnswerList = mDNSNULL;
3588
3589 // 1. If time for a query, work out what we need to do
3590
3591 // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3592 // to their NextRequiredQuery to be worth batching them together with this one
3593 FORALL_CACHERECORDS(slot, cg, cr)
3594 {
3595 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3596 {
3597 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3598 {
3599 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3600 q = cr->CRActiveQuestion;
3601 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3602 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3603 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3604 if (!mDNSOpaque16IsZero(q->TargetQID))
3605 {
3606 q->LastQTime = m->timenow - q->ThisQInterval;
3607 cr->UnansweredQueries++;
3608 m->mDNSStats.CacheRefreshQueries++;
3609 }
3610 else if (q->SendQNow == mDNSNULL)
3611 {
3612 q->SendQNow = cr->resrec.InterfaceID;
3613 }
3614 else if (q->SendQNow != cr->resrec.InterfaceID)
3615 {
3616 q->SendQNow = mDNSInterfaceMark;
3617 }
3618
3619 // Indicate that this question was marked for sending
3620 // to update an existing cached answer record.
3621 // The browse throttling logic below uses this to determine
3622 // if the query should be sent.
3623 if (mDNSOpaque16IsZero(q->TargetQID))
3624 q->CachedAnswerNeedsUpdate = mDNStrue;
3625 }
3626 }
3627 }
3628
3629 // Scan our list of questions to see which:
3630 // *WideArea* queries need to be sent
3631 // *unicast* queries need to be sent
3632 // *multicast* queries we're definitely going to send
3633 if (m->CurrentQuestion)
3634 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3635 m->CurrentQuestion = m->Questions;
3636 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3637 {
3638 q = m->CurrentQuestion;
3639 if (mDNSOpaque16IsZero(q->TargetQID) && TimeToSendThisQuestion(q, m->timenow))
3640 {
3641 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3642 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces
3643 if (maxExistingQuestionInterval < q->ThisQInterval)
3644 maxExistingQuestionInterval = q->ThisQInterval;
3645 }
3646 // If m->CurrentQuestion wasn't modified out from under us, advance it now
3647 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3648 // m->CurrentQuestion point to the right question
3649 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3650 }
3651 while (m->CurrentQuestion)
3652 {
3653 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3654 m->CurrentQuestion = m->CurrentQuestion->next;
3655 }
3656 m->CurrentQuestion = mDNSNULL;
3657
3658 // Scan our list of questions
3659 // (a) to see if there are any more that are worth accelerating, and
3660 // (b) to update the state variables for *all* the questions we're going to send
3661 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3662 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3663 // next thing we do is scan the list and call SetNextQueryTime() for every question we find, so we know we end up with the right value.
3664 m->NextScheduledQuery = m->timenow + FutureTime;
3665 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3666 {
3667 if (mDNSOpaque16IsZero(q->TargetQID)
3668 && (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3669 {
3670 // If at least halfway to next query time, advance to next interval
3671 // If less than halfway to next query time, then
3672 // treat this as logically a repeat of the last transmission, without advancing the interval
3673 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3674 {
3675 // If we have reached the answer threshold for this question,
3676 // don't send it again until MaxQuestionInterval unless:
3677 // one of its cached answers needs to be refreshed,
3678 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3679 if (q->BrowseThreshold
3680 && (q->CurrentAnswers >= q->BrowseThreshold)
3681 && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3682 && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3683 {
3684 q->SendQNow = mDNSNULL;
3685 q->ThisQInterval = MaxQuestionInterval;
3686 q->LastQTime = m->timenow;
3687 q->RequestUnicast = 0;
3688 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3689 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3690 }
3691 else
3692 {
3693 // Mark this question for sending on all interfaces
3694 q->SendQNow = mDNSInterfaceMark;
3695 q->ThisQInterval *= QuestionIntervalStep;
3696 }
3697
3698 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3699 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3700
3701 if (q->ThisQInterval > MaxQuestionInterval)
3702 {
3703 q->ThisQInterval = MaxQuestionInterval;
3704 }
3705 else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID &&
3706 q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3707 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3708 {
3709 // Generally don't need to log this.
3710 // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3711 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3712 // and when there simply happen to be no instances of the service the client is looking
3713 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3714 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3715 q->qname.c, DNSTypeName(q->qtype));
3716 // Sending third query, and no answers yet; time to begin doubting the source
3717 ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0);
3718 }
3719 }
3720
3721 // Mark for sending. (If no active interfaces, then don't even try.)
3722 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3723 if (q->SendOnAll)
3724 {
3725 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3726 q->LastQTime = m->timenow;
3727 }
3728
3729 // If we recorded a duplicate suppression for this question less than half an interval ago,
3730 // then we consider it recent enough that we don't need to do an identical query ourselves.
3731 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3732
3733 q->LastQTxTime = m->timenow;
3734 q->RecentAnswerPkts = 0;
3735 if (q->RequestUnicast) q->RequestUnicast--;
3736 }
3737 // For all questions (not just the ones we're sending) check what the next scheduled event will be
3738 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3739 SetNextQueryTime(m,q);
3740 }
3741
3742 // 2. Scan our authoritative RR list to see what probes we might need to send
3743
3744 m->NextScheduledProbe = m->timenow + FutureTime;
3745
3746 if (m->CurrentRecord)
3747 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3748 m->CurrentRecord = m->ResourceRecords;
3749 while (m->CurrentRecord)
3750 {
3751 ar = m->CurrentRecord;
3752 m->CurrentRecord = ar->next;
3753 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique) // For all records that are still probing...
3754 {
3755 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3756 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3757 {
3758 SetNextAnnounceProbeTime(m, ar);
3759 }
3760 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3761 else if (ar->ProbeCount)
3762 {
3763 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3764 {
3765 // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3766 // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3767 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3768 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3769 // A similar concern may apply to the NDP Probe too. -- SC
3770 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3771 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3772 }
3773 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3774 {
3775 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3776 // IPv6 source = zero
3777 // No target hardware address
3778 // IPv6 target address is address we're probing
3779 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3780 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3781 }
3782 // Mark for sending. (If no active interfaces, then don't even try.)
3783 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3784 ar->LastAPTime = m->timenow;
3785 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3786 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3787 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3788 ar->ProbeCount = DefaultProbeCountForTypeUnique;
3789 ar->ProbeCount--;
3790 SetNextAnnounceProbeTime(m, ar);
3791 if (ar->ProbeCount == 0)
3792 {
3793 // If this is the last probe for this record, then see if we have any matching records
3794 // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3795 AuthRecord *r2;
3796 for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3797 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3798 r2->ProbeCount = 0;
3799 // ... then acknowledge this record to the client.
3800 // We do this optimistically, just as we're about to send the third probe.
3801 // This helps clients that both advertise and browse, and want to filter themselves
3802 // from the browse results list, because it helps ensure that the registration
3803 // confirmation will be delivered 1/4 second *before* the browse "add" event.
3804 // A potential downside is that we could deliver a registration confirmation and then find out
3805 // moments later that there's a name conflict, but applications have to be prepared to handle
3806 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3807 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3808 }
3809 }
3810 // else, if it has now finished probing, move it to state Verified,
3811 // and update m->NextScheduledResponse so it will be announced
3812 else
3813 {
3814 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow
3815 ar->resrec.RecordType = kDNSRecordTypeVerified;
3816 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3817 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3818 SetNextAnnounceProbeTime(m, ar);
3819 }
3820 }
3821 }
3822 m->CurrentRecord = m->DuplicateRecords;
3823 while (m->CurrentRecord)
3824 {
3825 ar = m->CurrentRecord;
3826 m->CurrentRecord = ar->next;
3827 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3828 AcknowledgeRecord(m, ar);
3829 }
3830
3831 // 3. Now we know which queries and probes we're sending,
3832 // go through our interface list sending the appropriate queries on each interface
3833 while (intf)
3834 {
3835 int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3836 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3837 mDNSu8 *queryptr = m->omsg.data;
3838 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class
3839
3840 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3841 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet");
3842 if (!KnownAnswerList)
3843 {
3844 // Start a new known-answer list
3845 CacheRecord **kalistptr = &KnownAnswerList;
3846 mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3847
3848 // Put query questions in this packet
3849 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3850 {
3851 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3852 {
3853 mDNSBool Suppress = mDNSfalse;
3854 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3855 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ",
3856 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3857
3858 // If interface is P2P type, verify that query should be sent over it.
3859 if (!mDNSPlatformValidQuestionForInterface(q, intf))
3860 {
3861 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3862 }
3863 // If we're suppressing this question, or we successfully put it, update its SendQNow state
3864 else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3865 BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3866 {
3867 if (Suppress)
3868 m->mDNSStats.DupQuerySuppressions++;
3869
3870 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3871 if (q->WakeOnResolveCount)
3872 {
3873 mDNSSendWakeOnResolve(m, q);
3874 q->WakeOnResolveCount--;
3875 }
3876
3877 // use background traffic class if any included question requires it
3878 if (q->UseBackgroundTraffic)
3879 {
3880 useBackgroundTrafficClass = mDNStrue;
3881 }
3882 }
3883 }
3884 }
3885
3886 // Put probe questions in this packet
3887 for (ar = m->ResourceRecords; ar; ar=ar->next)
3888 {
3889 if (ar->SendRNow != intf->InterfaceID)
3890 continue;
3891
3892 // If interface is a P2P variant, verify that the probe should be sent over it.
3893 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID))
3894 {
3895 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3896 ar->IncludeInProbe = mDNSfalse;
3897 }
3898 else
3899 {
3900 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3901 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3902 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3903 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3904 mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3905 mDNSBool putProbe = mDNStrue;
3906 mDNSu16 qclass = ar->resrec.rrclass | ucbit;
3907
3908 {// Determine if this probe question is already in packet's dns message
3909 const mDNSu8 *questionptr = m->omsg.data;
3910 DNSQuestion question;
3911 mDNSu16 n;
3912 for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++)
3913 {
3914 questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question);
3915 if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) &&
3916 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name))
3917 {
3918 putProbe = mDNSfalse; // set to false if already in message
3919 break;
3920 }
3921 }
3922 }
3923
3924 if (putProbe)
3925 {
3926 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass);
3927 if (newptr)
3928 {
3929 queryptr = newptr;
3930 answerforecast = forecast;
3931 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3932 ar->IncludeInProbe = mDNStrue;
3933 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3934 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast);
3935 }
3936 }
3937 else
3938 {
3939 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3940 ar->IncludeInProbe = mDNStrue;
3941 }
3942 }
3943 }
3944 }
3945
3946 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3947 while (KnownAnswerList)
3948 {
3949 CacheRecord *ka = KnownAnswerList;
3950 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3951 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3952 m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3953 if (newptr)
3954 {
3955 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d",
3956 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3957 queryptr = newptr;
3958 KnownAnswerList = ka->NextInKAList;
3959 ka->NextInKAList = mDNSNULL;
3960 }
3961 else
3962 {
3963 // If we ran out of space and we have more than one question in the packet, that's an error --
3964 // we shouldn't have put more than one question if there was a risk of us running out of space.
3965 if (m->omsg.h.numQuestions > 1)
3966 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3967 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3968 break;
3969 }
3970 }
3971
3972 for (ar = m->ResourceRecords; ar; ar=ar->next)
3973 {
3974 if (ar->IncludeInProbe)
3975 {
3976 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3977 ar->IncludeInProbe = mDNSfalse;
3978 if (newptr) queryptr = newptr;
3979 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3980 }
3981 }
3982
3983 if (queryptr > m->omsg.data)
3984 {
3985 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3986 if (OwnerRecordSpace || TraceRecordSpace)
3987 {
3988 AuthRecord opt;
3989 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3990 opt.resrec.rrclass = NormalMaxDNSMessageData;
3991 opt.resrec.rdlength = sizeof(rdataOPT);
3992 opt.resrec.rdestimate = sizeof(rdataOPT);
3993 if (OwnerRecordSpace && TraceRecordSpace)
3994 {
3995 opt.resrec.rdlength += sizeof(rdataOPT); // Two options in this OPT record
3996 opt.resrec.rdestimate += sizeof(rdataOPT);
3997 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3998 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3999 }
4000 else if (OwnerRecordSpace)
4001 {
4002 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4003 }
4004 else if (TraceRecordSpace)
4005 {
4006 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
4007 }
4008 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
4009 &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4010 if (!queryptr)
4011 {
4012 LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
4013 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4014 }
4015 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
4016 {
4017 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
4018 LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
4019 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
4020 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4021 }
4022 }
4023
4024 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
4025 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
4026 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4027 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
4028 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
4029 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", IIDPrintable(intf->InterfaceID), intf->ifname);
4030 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4031 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4032 if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
4033 if (++pktcount >= 1000)
4034 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
4035 // There might be more records left in the known answer list, or more questions to send
4036 // on this interface, so go around one more time and try again.
4037 }
4038 else // Nothing more to send on this interface; go to next
4039 {
4040 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
4041 #if MDNS_DEBUGMSGS && 0
4042 const char *const msg = next ? "SendQueries: Nothing more on %p; moving to %p" : "SendQueries: Nothing more on %p";
4043 debugf(msg, intf, next);
4044 #endif
4045 intf = next;
4046 }
4047 }
4048
4049 // 4. Final housekeeping
4050
4051 // 4a. Debugging check: Make sure we announced all our records
4052 for (ar = m->ResourceRecords; ar; ar=ar->next)
4053 if (ar->SendRNow)
4054 {
4055 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
4056 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4057 IIDPrintable(ar->SendRNow), IIDPrintable(ar->resrec.InterfaceID), ARDisplayString(m, ar));
4058 ar->SendRNow = mDNSNULL;
4059 }
4060
4061 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4062 // that their interface which went away might come back again, the logic will want to send queries
4063 // for those records, but we can't because their interface isn't here any more, so to keep the
4064 // state machine ticking over we just pretend we did so.
4065 // If the interface does not come back in time, the cache record will expire naturally
4066 FORALL_CACHERECORDS(slot, cg, cr)
4067 {
4068 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
4069 {
4070 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
4071 {
4072 cr->UnansweredQueries++;
4073 cr->CRActiveQuestion->SendQNow = mDNSNULL;
4074 SetNextCacheCheckTimeForRecord(m, cr);
4075 }
4076 }
4077 }
4078
4079 // 4c. Debugging check: Make sure we sent all our planned questions
4080 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4081 // we legitimately couldn't send because the interface is no longer available
4082 for (q = m->Questions; q; q=q->next)
4083 {
4084 if (q->SendQNow)
4085 {
4086 DNSQuestion *x;
4087 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion
4088 // There will not be an active interface for questions applied to mDNSInterface_BLE
4089 // so don't log the warning in that case.
4090 if (q->InterfaceID != mDNSInterface_BLE)
4091 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4092 IIDPrintable(q->SendQNow), x ? "new" : "old", IIDPrintable(q->InterfaceID), q->qname.c, DNSTypeName(q->qtype));
4093 q->SendQNow = mDNSNULL;
4094 }
4095 q->CachedAnswerNeedsUpdate = mDNSfalse;
4096 }
4097 }
4098
4099 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly)
4100 {
4101 int i, j;
4102
4103 mDNSu8 *ptr = m->omsg.data;
4104 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
4105 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
4106
4107 // 0x00 Destination address
4108 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4109
4110 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4111 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
4112
4113 // 0x0C Ethertype (0x0842)
4114 *ptr++ = 0x08;
4115 *ptr++ = 0x42;
4116
4117 // 0x0E Wakeup sync sequence
4118 for (i=0; i<6; i++) *ptr++ = 0xFF;
4119
4120 // 0x14 Wakeup data
4121 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4122
4123 // 0x74 Password
4124 for (i=0; i<6; i++) *ptr++ = password->b[i];
4125
4126 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4127
4128 if (!unicastOnly)
4129 {
4130 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4131 // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4132 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4133 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4134 // So, we send one of each, unicast first, then broadcast second.
4135 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
4136 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4137 }
4138 }
4139
4140 // ***************************************************************************
4141 #if COMPILER_LIKES_PRAGMA_MARK
4142 #pragma mark -
4143 #pragma mark - RR List Management & Task Management
4144 #endif
4145
4146 // Whenever a question is answered, reset its state so that we don't query
4147 // the network repeatedly. This happens first time when we answer the question and
4148 // and later when we refresh the cache.
4149 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
4150 {
4151 q->LastQTime = m->timenow;
4152 q->LastQTxTime = m->timenow;
4153 q->RecentAnswerPkts = 0;
4154 q->ThisQInterval = MaxQuestionInterval;
4155 q->RequestUnicast = 0;
4156 // Reset unansweredQueries so that we don't penalize this server later when we
4157 // start sending queries when the cache expires.
4158 q->unansweredQueries = 0;
4159 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4160 }
4161
4162 mDNSlocal void AdjustUnansweredQueries(mDNS *const m, CacheRecord *const rr)
4163 {
4164 const mDNSs32 expireTime = RRExpireTime(rr);
4165 const mDNSu32 interval = TicksTTL(rr) / 20; // Calculate 5% of the cache record's TTL.
4166 mDNSu32 rem;
4167
4168 // If the record is expired or UnansweredQueries is already at the max, then return early.
4169 if (((m->timenow - expireTime) >= 0) || (rr->UnansweredQueries >= MaxUnansweredQueries)) return;
4170
4171 if (interval == 0)
4172 {
4173 LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr), CRDisplayString(m, rr));
4174 return;
4175 }
4176
4177 // Calculate the number of whole 5% TTL intervals between now and expiration time.
4178 rem = ((mDNSu32)(expireTime - m->timenow)) / interval;
4179
4180 // Calculate the expected number of remaining refresher queries.
4181 // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4182 if (rem > MaxUnansweredQueries) rem = MaxUnansweredQueries;
4183
4184 // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4185 // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4186 // refresher queries would have been sent if the cache record did have an active question. The cache record's
4187 // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4188 // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4189 // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4190 // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4191 // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4192 // Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4193 if ((MaxUnansweredQueries - rr->UnansweredQueries) > (mDNSs32)rem)
4194 {
4195 if (rem == 0) rem++;
4196 rr->UnansweredQueries = (mDNSu8)(MaxUnansweredQueries - rem);
4197 }
4198 }
4199
4200 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4201 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4202 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4203 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4204 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
4205 {
4206 DNSQuestion *const q = m->CurrentQuestion;
4207 const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
4208
4209 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4210 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", MortalityDisplayString(rr->resrec.mortality),
4211 rr->resrec.rroriginalttl, CRDisplayString(m, rr));
4212
4213 // When the response for the question was validated, the entire rrset was validated. If we deliver
4214 // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
4215 // in the future, we will do the revalidation again.
4216 //
4217 // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
4218 // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
4219 // negative response which can happen e.g., when disconnecting from network that leads to a negative response
4220 // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
4221 // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
4222 // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
4223 // a real negative response, we would reset the state here and validate the results at the end of this function.
4224 // or the real response again if we purge the cache.
4225 if (q->ValidationRequired && ((AddRecord == QC_rmv) ||
4226 (rr->resrec.RecordType == kDNSRecordTypePacketNegative && (AddRecord == QC_add))))
4227 {
4228 q->ValidationStatus = 0;
4229 q->ValidationState = DNSSECValRequired;
4230 }
4231
4232 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4233 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4234 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4235 // we check to see if that query already has a unique local answer.
4236 if (q->LOAddressAnswers)
4237 {
4238 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4239 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
4240 q->LOAddressAnswers);
4241 return;
4242 }
4243
4244 if (q->Suppressed && (AddRecord != QC_suppressed))
4245 {
4246 // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4247 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4248 // that are timing out, which we know are answered with negative cache record when timing out.
4249 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
4250 return;
4251 }
4252
4253 // Set the record to immortal if appropriate
4254 if (AddRecord == QC_add && Question_uDNS(q) && rr->resrec.RecordType != kDNSRecordTypePacketNegative &&
4255 q->allowExpired != AllowExpired_None && rr->resrec.mortality == Mortality_Mortal ) rr->resrec.mortality = Mortality_Immortal; // Update a non-expired cache record to immortal if appropriate
4256
4257 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4258 if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname)
4259 {
4260 const domainname * queryName;
4261 mDNSu32 responseLatencyMs;
4262 mDNSBool isForCellular;
4263
4264 queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname;
4265 isForCellular = (q->qDNSServer && q->qDNSServer->isCell);
4266 if (!q->metrics.answered)
4267 {
4268 if (q->metrics.querySendCount > 0)
4269 {
4270 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
4271 }
4272 else
4273 {
4274 responseLatencyMs = 0;
4275 }
4276
4277 MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, q->metrics.querySendCount, q->metrics.expiredAnswerState, q->metrics.dnsOverTCPState, responseLatencyMs, isForCellular);
4278 q->metrics.answered = mDNStrue;
4279 }
4280 }
4281 #endif
4282 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4283 // may be called twice, once when the record is received, and again when it's time to notify local clients.
4284 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4285
4286 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost)
4287 {
4288 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4289 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
4290 if (!rr->CRActiveQuestion)
4291 {
4292 m->rrcache_active++; // If not previously active, increment rrcache_active count
4293 AdjustUnansweredQueries(m, rr); // Adjust UnansweredQueries in case the record missed out on refresher queries
4294 }
4295 rr->CRActiveQuestion = q; // We know q is non-null
4296 SetNextCacheCheckTimeForRecord(m, rr);
4297 }
4298
4299 // If this is:
4300 // (a) a no-cache add, where we've already done at least one 'QM' query, or
4301 // (b) a normal add, where we have at least one unique-type answer,
4302 // then there's no need to keep polling the network.
4303 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4304 // We do this for mDNS questions and uDNS one-shot questions, but not for
4305 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4306 if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
4307 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
4308 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4309 {
4310 ResetQuestionState(m, q);
4311 }
4312
4313 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us
4314
4315 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4316 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4317 if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return;
4318 #endif
4319
4320 #ifdef USE_LIBIDN
4321 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) // If negative answer, check if we need to try Punycode conversion
4322 {
4323 domainname newname;
4324 if (PerformNextPunycodeConversion(q, &newname)) // Itertative Punycode conversion succeeded, so reissue question with new name
4325 {
4326 UDPSocket *const sock = q->LocalSocket; // Save old socket and transaction ID
4327 const mDNSOpaque16 id = q->TargetQID;
4328 q->LocalSocket = mDNSNULL;
4329 mDNS_StopQuery_internal(m, q); // Stop old query
4330 AssignDomainName(&q->qname, &newname); // Update qname
4331 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
4332 mDNS_StartQuery_internal(m, q); // Start new query
4333
4334 if (sock) // Transplant saved socket, if appropriate
4335 {
4336 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
4337 else { q->LocalSocket = sock; q->TargetQID = id; }
4338 }
4339 return; // All done for now; wait until we get the next answer
4340 }
4341 }
4342 #endif // USE_LIBIDN
4343
4344 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4345 // for the purpose of retrying search domains/timeout OR the question is suppressed
4346 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4347 if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4348
4349 // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4350 if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4351 {
4352 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4353 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4354 {
4355 CacheRecord neg;
4356 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4357 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4358 }
4359 else
4360 {
4361 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4362 if (DNS64ShouldAnswerQuestion(q, &rr->resrec))
4363 {
4364 DNS64AnswerCurrentQuestion(m, &rr->resrec, AddRecord);
4365 }
4366 else
4367 #endif
4368 {
4369 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4370 }
4371 }
4372 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4373 }
4374 // Note: Proceed with caution after this point because client callback function
4375 // invoked above is allowed to do anything, such as starting/stopping queries
4376 // (including this one itself, or the next or previous query in the linked list),
4377 // registering/deregistering records, starting/stopping NAT traversals, etc.
4378
4379 // If this is an "Add" operation and this question needs validation, validate the response.
4380 // In the case of negative responses, extra care should be taken. Negative cache records are
4381 // used for many purposes. For example,
4382 //
4383 // 1) Suppressing questions (SuppressUnusable)
4384 // 2) Timeout questions
4385 // 3) The name does not exist
4386 // 4) No DNS servers are available and we need a quick response for the application
4387 //
4388 // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4389 // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4390 // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4391 // signature for (4) and hence the explicit check for q->qDNSServer.
4392 //
4393 if (m->CurrentQuestion == q && (AddRecord == QC_add) && !q->ValidatingResponse && q->ValidationRequired &&
4394 q->ValidationState == DNSSECValRequired && q->qDNSServer)
4395 {
4396 q->ValidationState = DNSSECValInProgress;
4397 // Treat it as callback call as that's what dnssec code expects
4398 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
4399 VerifySignature(m, mDNSNULL, q);
4400 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
4401 return;
4402 }
4403
4404 if ((m->CurrentQuestion == q) && !ValidatingQuestion(q))
4405 {
4406 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4407 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4408 // first before following it
4409 if (followcname) AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
4410
4411 // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4412 if (rr->resrec.mortality == Mortality_Ghost && !q->firstExpiredQname.c[0] && (q->allowExpired == AllowExpired_AllowExpiredAnswers) && rr->resrec.RecordType != kDNSRecordTypePacketNegative)
4413 {
4414 debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m,rr), q);
4415 // Note: question->qname is already changed at this point if following a CNAME
4416 AssignDomainName(&q->firstExpiredQname, rr->resrec.name); // Update firstExpiredQname
4417 }
4418 }
4419 }
4420
4421 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *cr)
4422 {
4423 cr->DelayDelivery = 0;
4424 if (m->CurrentQuestion)
4425 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4426 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4427 m->CurrentQuestion = m->Questions;
4428 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4429 {
4430 DNSQuestion *q = m->CurrentQuestion;
4431 if (CacheRecordAnswersQuestion(cr, q))
4432 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4433 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4434 m->CurrentQuestion = q->next;
4435 }
4436 m->CurrentQuestion = mDNSNULL;
4437 }
4438
4439 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
4440 {
4441 const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second
4442 const mDNSs32 start = m->timenow - 0x10000000;
4443 mDNSs32 delay = start;
4444 CacheGroup *cg = CacheGroupForName(m, namehash, name);
4445 const CacheRecord *rr;
4446
4447 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4448 {
4449 if (threshold - RRExpireTime(rr) >= 0) // If we have records about to expire within a second
4450 {
4451 if (delay - RRExpireTime(rr) < 0) // then delay until after they've been deleted
4452 delay = RRExpireTime(rr);
4453 }
4454 }
4455 if (delay - start > 0)
4456 return(NonZeroTime(delay));
4457 else
4458 return(0);
4459 }
4460
4461 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4462 // If new questions are created as a result of invoking client callbacks, they will be added to
4463 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4464 // rr is a new CacheRecord just received into our cache
4465 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4466 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4467 // which may change the record list and/or question list.
4468 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4469 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *cr)
4470 {
4471 DNSQuestion *q;
4472
4473 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4474 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4475 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4476 {
4477 if (CacheRecordAnswersQuestion(cr, q))
4478 {
4479 // If this question is one that's actively sending queries, and it's received ten answers within one
4480 // second of sending the last query packet, then that indicates some radical network topology change,
4481 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4482 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4483 // because we will anyway send another query within a few seconds. The first reset query is sent out
4484 // randomized over the next four seconds to reduce possible synchronization between machines.
4485 if (q->LastAnswerPktNum != m->PktNum)
4486 {
4487 q->LastAnswerPktNum = m->PktNum;
4488 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4489 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4490 {
4491 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4492 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4493 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4494 q->ThisQInterval = InitialQuestionInterval;
4495 SetNextQueryTime(m,q);
4496 }
4497 }
4498 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr, cr->resrec.name->c,
4499 DNSTypeName(cr->resrec.rrtype), cr->resrec.rroriginalttl, cr->resrec.rDNSServer ?
4500 &cr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(cr->resrec.rDNSServer ?
4501 cr->resrec.rDNSServer->port : zeroIPPort), q);
4502 q->CurrentAnswers++;
4503
4504 q->unansweredQueries = 0;
4505 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4506 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4507 if (q->CurrentAnswers > 4000)
4508 {
4509 static int msgcount = 0;
4510 if (msgcount++ < 10)
4511 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4512 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4513 cr->resrec.rroriginalttl = 0;
4514 cr->UnansweredQueries = MaxUnansweredQueries;
4515 }
4516 }
4517 }
4518
4519 if (!cr->DelayDelivery)
4520 {
4521 if (m->CurrentQuestion)
4522 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4523 m->CurrentQuestion = m->Questions;
4524 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4525 {
4526 q = m->CurrentQuestion;
4527 if (CacheRecordAnswersQuestion(cr, q))
4528 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4529 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4530 m->CurrentQuestion = q->next;
4531 }
4532 m->CurrentQuestion = mDNSNULL;
4533 }
4534
4535 SetNextCacheCheckTimeForRecord(m, cr);
4536 }
4537
4538 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4539 // If new questions are created as a result of invoking client callbacks, they will be added to
4540 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4541 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4542 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4543 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4544 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4545 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4546 // which may change the record list and/or question list.
4547 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4548 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *cr)
4549 {
4550 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4551 if (m->CurrentQuestion)
4552 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4553 m->CurrentQuestion = m->Questions;
4554 // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4555 // since we're not caching the record and we'll get no opportunity to do this later
4556 while (m->CurrentQuestion)
4557 {
4558 DNSQuestion *q = m->CurrentQuestion;
4559 if (CacheRecordAnswersQuestion(cr, q))
4560 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_addnocache); // QC_addnocache means "don't expect remove events for this"
4561 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4562 m->CurrentQuestion = q->next;
4563 }
4564 m->CurrentQuestion = mDNSNULL;
4565 }
4566
4567 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4568 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4569 // If new questions are created as a result of invoking client callbacks, they will be added to
4570 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4571 // cr is an existing cache CacheRecord that just expired and is being deleted
4572 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4573 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4574 // which may change the record list and/or question list.
4575 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4576 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *cr)
4577 {
4578 if (m->CurrentQuestion)
4579 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4580 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4581 m->CurrentQuestion = m->Questions;
4582
4583 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4584 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4585 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4586 {
4587 DNSQuestion *q = m->CurrentQuestion;
4588 // When a question enters suppressed state, we generate RMV events and generate a negative
4589 // response. A cache may be present that answers this question e.g., cache entry generated
4590 // before the question became suppressed. We need to skip the suppressed questions here as
4591 // the RMV event has already been generated.
4592 if (!q->Suppressed && CacheRecordAnswersQuestion(cr, q) &&
4593 (q->allowExpired == AllowExpired_None || cr->resrec.mortality == Mortality_Mortal))
4594 {
4595 verbosedebugf("CacheRecordRmv %p %s", cr, CRDisplayString(m, cr));
4596 q->FlappingInterface1 = mDNSNULL;
4597 q->FlappingInterface2 = mDNSNULL;
4598
4599 if (q->CurrentAnswers == 0)
4600 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4601 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4602 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4603 else
4604 {
4605 q->CurrentAnswers--;
4606 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4607 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4608 }
4609
4610 // If we have dropped below the answer threshold for this mDNS question,
4611 // restart the queries at InitialQuestionInterval.
4612 if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4613 {
4614 q->ThisQInterval = InitialQuestionInterval;
4615 q->LastQTime = m->timenow - q->ThisQInterval;
4616 SetNextQueryTime(m,q);
4617 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4618 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4619 }
4620 if (cr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4621 {
4622 if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID))
4623 {
4624 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4625 q->qname.c, DNSTypeName(q->qtype));
4626 ReconfirmAntecedents(m, &q->qname, q->qnamehash, cr->resrec.InterfaceID, 0);
4627 }
4628 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
4629 }
4630 }
4631 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4632 m->CurrentQuestion = q->next;
4633 }
4634 m->CurrentQuestion = mDNSNULL;
4635 }
4636
4637 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4638 {
4639 #if MDNS_MALLOC_DEBUGGING >= 1
4640 unsigned int i;
4641 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4642 #endif
4643 e->next = m->rrcache_free;
4644 m->rrcache_free = e;
4645 m->rrcache_totalused--;
4646 }
4647
4648 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4649 {
4650 CacheEntity *e = (CacheEntity *)(*cp);
4651 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4652 if ((*cp)->rrcache_tail != &(*cp)->members)
4653 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4654 //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4655 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4656 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4657 (*cp)->name = mDNSNULL;
4658 *cp = (*cp)->next; // Cut record from list
4659 ReleaseCacheEntity(m, e);
4660 }
4661
4662 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4663 {
4664 while (*rp)
4665 {
4666 CacheRecord *rr = *rp;
4667 *rp = (*rp)->next; // Cut record from list
4668 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4669 {
4670 mDNSPlatformMemFree(rr->resrec.rdata);
4671 rr->resrec.rdata = mDNSNULL;
4672 }
4673 // NSEC or SOA records that are not added to the CacheGroup do not share the name
4674 // of the CacheGroup.
4675 if (rr->resrec.name)
4676 {
4677 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4678 mDNSPlatformMemFree((void *)rr->resrec.name);
4679 rr->resrec.name = mDNSNULL;
4680 }
4681 // Don't count the NSEC3 records used by anonymous browse/reg
4682 if (!rr->resrec.InterfaceID)
4683 {
4684 m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4685 if (DNSSECRecordType(rr->resrec.rrtype))
4686 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
4687 }
4688 ReleaseCacheEntity(m, (CacheEntity *)rr);
4689 }
4690 }
4691
4692 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4693 {
4694 CacheGroup *cg;
4695
4696 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4697 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4698 r->resrec.rdata = mDNSNULL;
4699
4700 cg = CacheGroupForRecord(m, &r->resrec);
4701
4702 if (!cg)
4703 {
4704 // It is okay to have this printed for NSEC/NSEC3s
4705 LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4706 }
4707 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4708 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4709 // (which is handled below) and in that case it should be freed here.
4710 if (r->resrec.name && cg && r->resrec.name != cg->name)
4711 {
4712 debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4713 mDNSPlatformMemFree((void *)r->resrec.name);
4714 }
4715 r->resrec.name = mDNSNULL;
4716
4717 if (!r->resrec.InterfaceID)
4718 {
4719 m->rrcache_totalused_unicast -= r->resrec.rdlength;
4720 if (DNSSECRecordType(r->resrec.rrtype))
4721 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, r->resrec.rdlength);
4722 }
4723
4724 ReleaseAdditionalCacheRecords(m, &r->nsec);
4725 ReleaseAdditionalCacheRecords(m, &r->soa);
4726
4727 ReleaseCacheEntity(m, (CacheEntity *)r);
4728 }
4729
4730 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4731 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4732 // callbacks for old records are delivered before callbacks for newer records.
4733 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4734 {
4735 CacheRecord **rp = &cg->members;
4736
4737 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4738 m->lock_rrcache = 1;
4739
4740 while (*rp)
4741 {
4742 CacheRecord *const rr = *rp;
4743 mDNSBool recordReleased = mDNSfalse;
4744 mDNSs32 event = RRExpireTime(rr);
4745 if (m->timenow - event >= 0) // If expired, delete it
4746 {
4747 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away
4748 {
4749 DNSQuestion *q = rr->CRActiveQuestion;
4750 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4751 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4752 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4753 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4754 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4755 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4756 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4757 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4758 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4759 if (((mDNSOpaque16IsZero(q->TargetQID) && (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) ||
4760 (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived)) && ActiveQuestion(q))
4761 {
4762 q->ThisQInterval = InitialQuestionInterval;
4763 q->LastQTime = m->timenow - q->ThisQInterval;
4764 SetNextQueryTime(m, q);
4765 }
4766 CacheRecordRmv(m, rr);
4767 m->rrcache_active--;
4768 }
4769
4770 event += MAX_GHOST_TIME; // Adjust so we can check for a ghost expiration
4771 if (rr->resrec.mortality == Mortality_Mortal || // Normal expired mortal record that needs released
4772 (rr->resrec.mortality == Mortality_Ghost && m->timenow - event >= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago
4773 { // Release as normal
4774 *rp = rr->next; // Cut it from the list before ReleaseCacheRecord
4775 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4776 MortalityDisplayString(rr->resrec.mortality),
4777 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4778 ReleaseCacheRecord(m, rr);
4779 recordReleased = mDNStrue;
4780 }
4781 else // An immortal record needs to become a ghost when it expires
4782 { // Don't release this entry
4783 if (rr->resrec.mortality == Mortality_Immortal)
4784 {
4785 rr->resrec.mortality = Mortality_Ghost; // Expired immortal records become ghosts
4786 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4787 MortalityDisplayString(rr->resrec.mortality),
4788 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4789 }
4790 }
4791 }
4792 else // else, not expired; see if we need to query
4793 {
4794 // If waiting to delay delivery, do nothing until then
4795 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4796 event = rr->DelayDelivery;
4797 else
4798 {
4799 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4800 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4801 {
4802 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query
4803 event = NextCacheCheckEvent(rr); // then just record when we want the next query
4804 else // else trigger our question to go out now
4805 {
4806 // Set NextScheduledQuery to timenow so that SendQueries() will run.
4807 // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4808 m->NextScheduledQuery = m->timenow;
4809 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4810 // which will correctly update m->NextCacheCheck for us.
4811 event = m->timenow + FutureTime;
4812 }
4813 }
4814 }
4815 }
4816
4817 if (!recordReleased) // Schedule if we did not release the record
4818 {
4819 verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4820 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4821 if (m->rrcache_nextcheck[slot] - event > 0)
4822 m->rrcache_nextcheck[slot] = event;
4823 rp = &rr->next;
4824 }
4825 }
4826 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4827 cg->rrcache_tail = rp;
4828 m->lock_rrcache = 0;
4829 }
4830
4831 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4832 //
4833 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4834 // returns true if there is an answer.
4835 //
4836 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4837 // returns true to indicate the same.
4838 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4839 {
4840 AuthRecord *lr;
4841 AuthGroup *ag;
4842
4843 if (m->CurrentRecord)
4844 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4845
4846 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4847 if (ag)
4848 {
4849 m->CurrentRecord = ag->members;
4850 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4851 {
4852 AuthRecord *rr = m->CurrentRecord;
4853 m->CurrentRecord = rr->next;
4854 //
4855 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4856 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4857 //
4858 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4859 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4860 // we handle both mDNSInterface_Any and scoped questions.
4861
4862 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE)))
4863 if (LocalOnlyRecordAnswersQuestion(rr, q))
4864 {
4865 if (checkOnly)
4866 {
4867 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4868 ARDisplayString(m, rr));
4869 m->CurrentRecord = mDNSNULL;
4870 return mDNStrue;
4871 }
4872 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4873 if (m->CurrentQuestion != q)
4874 break; // If callback deleted q, then we're finished here
4875 }
4876 }
4877 }
4878 m->CurrentRecord = mDNSNULL;
4879
4880 if (m->CurrentQuestion != q)
4881 {
4882 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4883 return mDNStrue;
4884 }
4885
4886 if (q->LOAddressAnswers)
4887 {
4888 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4889 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4890 return mDNStrue;
4891 }
4892
4893 // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4894 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4895 // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4896 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4897 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4898 if (ag)
4899 {
4900 lr = ag->NewLocalOnlyRecords;
4901 while (lr)
4902 {
4903 if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4904 {
4905 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4906 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4907 return mDNStrue;
4908 }
4909 lr = lr->next;
4910 }
4911 }
4912 return mDNSfalse;
4913 }
4914
4915 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4916 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4917 // DNS requests.
4918 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4919 {
4920 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4921 // just deactivate the DNSQuestion.
4922 if (q->ReturnIntermed)
4923 {
4924 GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed);
4925 }
4926 else
4927 {
4928 q->ThisQInterval = 0;
4929 }
4930 }
4931
4932 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4933 {
4934 mDNSBool ShouldQueryImmediately = mDNStrue;
4935 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer
4936 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4937 if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q);
4938 #endif
4939 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
4940
4941 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4942
4943 if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg);
4944 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4945 m->NewQuestions = q->next;
4946 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4947 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4948 //
4949 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4950 // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4951 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4952 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4953 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4954 // advanced it), that means the question was deleted, so we no longer need to worry about answering
4955 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4956 // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4957 //
4958 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and
4959 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4960 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4961 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4962
4963 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4964 // This should be safe, because calling the client's question callback may cause the
4965 // question list to be modified, but should not ever cause the rrcache list to be modified.
4966 // If the client's question callback deletes the question, then m->CurrentQuestion will
4967 // be advanced, and we'll exit out of the loop
4968 m->lock_rrcache = 1;
4969 if (m->CurrentQuestion) {
4970 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
4971 "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME " (" PUB_S ")",
4972 m->CurrentQuestion->request_id, mDNSVal16(m->CurrentQuestion->TargetQID),
4973 DM_NAME_PARAM(m->CurrentQuestion->qname.c), DNSTypeName(m->CurrentQuestion->qtype));
4974 }
4975
4976 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
4977
4978 if (q->NoAnswer == NoAnswer_Fail)
4979 {
4980 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
4981 "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME " (" PUB_S ")",
4982 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype));
4983
4984 MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
4985 q->NoAnswer = NoAnswer_Normal; // Temporarily turn off answer suppression
4986 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
4987 // Don't touch the question if it has been stopped already
4988 if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail; // Restore NoAnswer state
4989 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
4990 }
4991
4992 if (m->CurrentQuestion != q)
4993 {
4994 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4995 goto exit;
4996 }
4997
4998 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4999 // or P2P record, then we are done.
5000 if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
5001 goto exit;
5002
5003 // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5004 // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5005 // the question out.
5006 if (q->Suppressed)
5007 {
5008 AnswerSuppressedQuestion(m, q);
5009 }
5010 else if (!q->ValidatingResponse)
5011 {
5012 CacheRecord *cr;
5013 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5014 if (SameNameCacheRecordAnswersQuestion(cr, q))
5015 {
5016 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5017 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - cr->TimeRcvd)) / mDNSPlatformOneSecond;
5018 mDNSBool IsExpired = (cr->resrec.rroriginalttl <= SecsSinceRcvd);
5019 if (IsExpired && q->allowExpired != AllowExpired_AllowExpiredAnswers) continue; // Go to next one in loop
5020
5021 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5022 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5023 if ((cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
5024 ShouldQueryImmediately = mDNSfalse;
5025 q->CurrentAnswers++;
5026 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
5027 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
5028 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5029 if (q->metrics.expiredAnswerState == ExpiredAnswer_Allowed) q->metrics.expiredAnswerState = IsExpired ? ExpiredAnswer_AnsweredWithExpired : ExpiredAnswer_AnsweredWithCache;
5030 #endif
5031 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
5032 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5033 }
5034 else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(cr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
5035 ShouldQueryImmediately = mDNSfalse;
5036 }
5037 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5038 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5039 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
5040
5041 q->InitialCacheMiss = mDNStrue; // Initial cache check is done, so mark as a miss from now on
5042 if (q->allowExpired == AllowExpired_AllowExpiredAnswers)
5043 {
5044 q->allowExpired = AllowExpired_MakeAnswersImmortal; // After looking through the cache for an answer, demote to make immortal
5045 if (q->firstExpiredQname.c[0]) // If an original query name was saved on an expired answer, start it over in case it is updated
5046 {
5047 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5048 "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME " for allowExpiredAnswers question",
5049 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->firstExpiredQname.c));
5050 mDNS_StopQuery_internal(m, q); // Stop old query
5051 AssignDomainName(&q->qname, &q->firstExpiredQname); // Update qname
5052 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash
5053 mDNS_StartQuery_internal(m, q); // start new query
5054 q->CNAMEReferrals = 0; // Reset referral count
5055 q->firstExpiredQname.c[0] = 0; // Erase the domain name
5056 }
5057 }
5058
5059 // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5060 // Hence we don't execute the following block of code for those cases.
5061 if (ShouldQueryImmediately && ActiveQuestion(q))
5062 {
5063 debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->request_id, mDNSVal16(q->TargetQID), q->qname.c, DNSTypeName(q->qtype));
5064 q->ThisQInterval = InitialQuestionInterval;
5065 q->LastQTime = m->timenow - q->ThisQInterval;
5066 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries
5067 {
5068 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5069 if (!m->RandomQueryDelay)
5070 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
5071 q->LastQTime += m->RandomQueryDelay;
5072 }
5073 }
5074
5075 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5076 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5077 // answers for this question until *after* its scheduled transmission time, in which case
5078 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5079 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5080 SetNextQueryTime(m,q);
5081
5082 exit:
5083 m->CurrentQuestion = mDNSNULL;
5084 m->lock_rrcache = 0;
5085 }
5086
5087 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5088 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
5089 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
5090 {
5091 AuthGroup *ag;
5092 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer
5093 mDNSBool retEv = mDNSfalse;
5094 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any)
5095
5096 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5097
5098 if (m->CurrentQuestion)
5099 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5100 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5101 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted
5102
5103 if (m->CurrentRecord)
5104 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5105
5106 // 1. First walk the LocalOnly records answering the LocalOnly question
5107 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5108 // walk the ResourceRecords list delivering the answers
5109 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5110 if (ag)
5111 {
5112 m->CurrentRecord = ag->members;
5113 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
5114 {
5115 AuthRecord *rr = m->CurrentRecord;
5116 m->CurrentRecord = rr->next;
5117 if (LocalOnlyRecordAnswersQuestion(rr, q))
5118 {
5119 retEv = mDNStrue;
5120 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
5121 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5122 }
5123 }
5124 }
5125
5126 if (m->CurrentQuestion == q)
5127 {
5128 m->CurrentRecord = m->ResourceRecords;
5129
5130 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
5131 {
5132 AuthRecord *ar = m->CurrentRecord;
5133 m->CurrentRecord = ar->next;
5134 if (AuthRecordAnswersQuestion(ar, q))
5135 {
5136 retEv = mDNStrue;
5137 AnswerLocalQuestionWithLocalAuthRecord(m, ar, QC_add);
5138 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
5139 }
5140 }
5141 }
5142
5143 // The local host is the authoritative source for LocalOnly questions
5144 // so if no records exist and client requested intermediates, then generate a negative response
5145 if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed)
5146 GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse);
5147
5148 m->CurrentQuestion = mDNSNULL;
5149 m->CurrentRecord = mDNSNULL;
5150 }
5151
5152 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
5153 {
5154 CacheEntity *e = mDNSNULL;
5155
5156 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
5157 m->lock_rrcache = 1;
5158
5159 // If we have no free records, ask the client layer to give us some more memory
5160 if (!m->rrcache_free && m->MainCallback)
5161 {
5162 if (m->rrcache_totalused != m->rrcache_size)
5163 {
5164 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5165 "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5166 m->rrcache_totalused, m->rrcache_size);
5167 }
5168
5169 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5170 // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5171 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5172 // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5173 // and recycle them, instead of allocating more memory.
5174 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
5175 {
5176 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
5177 "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5178 m->rrcache_size, m->rrcache_active);
5179 }
5180 else
5181 {
5182 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
5183 m->MainCallback(m, mStatus_GrowCache);
5184 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
5185 }
5186 }
5187
5188 // If we still have no free records, recycle all the records we can.
5189 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5190 if (!m->rrcache_free)
5191 {
5192 mDNSu32 oldtotalused = m->rrcache_totalused;
5193 mDNSu32 slot;
5194 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5195 {
5196 CacheGroup **cp = &m->rrcache_hash[slot];
5197 while (*cp)
5198 {
5199 CacheRecord **rp = &(*cp)->members;
5200 while (*rp)
5201 {
5202 // Records that answer still-active questions are not candidates for recycling
5203 // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5204 if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
5205 rp=&(*rp)->next;
5206 else
5207 {
5208 CacheRecord *rr = *rp;
5209 *rp = (*rp)->next; // Cut record from list
5210 ReleaseCacheRecord(m, rr);
5211 }
5212 }
5213 if ((*cp)->rrcache_tail != rp)
5214 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
5215 (*cp)->rrcache_tail = rp;
5216 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
5217 else ReleaseCacheGroup(m, cp);
5218 }
5219 }
5220 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5221 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
5222 }
5223
5224 if (m->rrcache_free) // If there are records in the free list, take one
5225 {
5226 e = m->rrcache_free;
5227 m->rrcache_free = e->next;
5228 if (++m->rrcache_totalused >= m->rrcache_report)
5229 {
5230 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "RR Cache now using %u objects", m->rrcache_totalused);
5231 if (m->rrcache_report < 100) m->rrcache_report += 10;
5232 else if (m->rrcache_report < 1000) m->rrcache_report += 100;
5233 else m->rrcache_report += 1000;
5234 }
5235 mDNSPlatformMemZero(e, sizeof(*e));
5236 }
5237
5238 m->lock_rrcache = 0;
5239
5240 return(e);
5241 }
5242
5243 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
5244 {
5245 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
5246 if (r)
5247 {
5248 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage
5249 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage
5250 {
5251 r->resrec.rdata = (RData*) mDNSPlatformMemAllocateClear(sizeofRDataHeader + RDLength);
5252 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
5253 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
5254 }
5255 }
5256 return(r);
5257 }
5258
5259 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
5260 {
5261 mDNSu16 namelen = DomainNameLength(rr->name);
5262 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
5263 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
5264 cg->next = m->rrcache_hash[slot];
5265 cg->namehash = rr->namehash;
5266 cg->members = mDNSNULL;
5267 cg->rrcache_tail = &cg->members;
5268 if (namelen > sizeof(cg->namestorage))
5269 cg->name = (domainname *) mDNSPlatformMemAllocate(namelen);
5270 else
5271 cg->name = (domainname*)cg->namestorage;
5272 if (!cg->name)
5273 {
5274 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
5275 ReleaseCacheEntity(m, (CacheEntity*)cg);
5276 return(mDNSNULL);
5277 }
5278 AssignDomainName(cg->name, rr->name);
5279
5280 if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
5281 m->rrcache_hash[slot] = cg;
5282 if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
5283
5284 return(cg);
5285 }
5286
5287 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
5288 {
5289 mDNS_CheckLock(m);
5290
5291 // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5292 // a positive answer using an expired record (e.g. from an interface that has gone away).
5293 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5294 // summary deletion without giving the proper callback to any questions that are monitoring it.
5295 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5296 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60;
5297 rr->UnansweredQueries = MaxUnansweredQueries;
5298 rr->resrec.rroriginalttl = 0;
5299 SetNextCacheCheckTimeForRecord(m, rr);
5300 }
5301
5302 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
5303 {
5304 mDNSs32 time;
5305 mDNSPlatformLock(m);
5306 if (m->mDNS_busy)
5307 {
5308 LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5309 if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
5310 }
5311
5312 if (m->timenow) time = m->timenow;
5313 else time = mDNS_TimeNow_NoLock(m);
5314 mDNSPlatformUnlock(m);
5315 return(time);
5316 }
5317
5318 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5319 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5320 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5321 #define SetSPSProxyListChanged(X) do { \
5322 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5323 m->SPSProxyListChanged = (X); } while(0)
5324
5325 // Called from mDNS_Execute() to expire stale proxy records
5326 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
5327 {
5328 m->CurrentRecord = list;
5329 while (m->CurrentRecord)
5330 {
5331 AuthRecord *rr = m->CurrentRecord;
5332 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
5333 {
5334 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5335 // so we need to cease proxying for *all* records we may have, expired or not.
5336 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS
5337 {
5338 if (m->NextScheduledSPS - rr->TimeExpire > 0)
5339 m->NextScheduledSPS = rr->TimeExpire;
5340 }
5341 else // else proxy record expired, so remove it
5342 {
5343 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5344 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
5345 SetSPSProxyListChanged(rr->resrec.InterfaceID);
5346 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5347 // Don't touch rr after this -- memory may have been free'd
5348 }
5349 }
5350 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5351 // new records could have been added to the end of the list as a result of that call.
5352 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5353 m->CurrentRecord = rr->next;
5354 }
5355 }
5356
5357 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5358 {
5359 while (m->CurrentRecord)
5360 {
5361 AuthRecord *rr = m->CurrentRecord;
5362 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5363 {
5364 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5365 rr->resrec.RecordType = kDNSRecordTypeShared;
5366 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv);
5367 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5368 {
5369 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5370 rr->AnsweredLocalQ = mDNSfalse;
5371 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5372 // For LocalOnly records, we don't do that and hence we need to do that here.
5373 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5374 }
5375 }
5376 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now
5377 m->CurrentRecord = rr->next;
5378 }
5379 }
5380
5381 mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID)
5382 {
5383 if (m->CurrentQuestion)
5384 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5385 DNSTypeName(m->CurrentQuestion->qtype));
5386 m->CurrentQuestion = questions;
5387 while (m->CurrentQuestion)
5388 {
5389 DNSQuestion *const q = m->CurrentQuestion;
5390 if (q->StopTime)
5391 {
5392 if (!q->TimeoutQuestion)
5393 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5394
5395 if (m->timenow - q->StopTime >= 0)
5396 {
5397 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5398 q->LOAddressAnswers = 0; // unset since timing out the question
5399 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse);
5400 if (m->CurrentQuestion == q) q->StopTime = 0;
5401 }
5402 else
5403 {
5404 if (m->NextScheduledStopTime - q->StopTime > 0)
5405 m->NextScheduledStopTime = q->StopTime;
5406 }
5407 }
5408 // If m->CurrentQuestion wasn't modified out from under us, advance it now
5409 // We can't do this at the start of the loop because GenerateNegativeResponse
5410 // depends on having m->CurrentQuestion point to the right question
5411 if (m->CurrentQuestion == q)
5412 m->CurrentQuestion = q->next;
5413 }
5414 m->CurrentQuestion = mDNSNULL;
5415 }
5416
5417 mDNSlocal void TimeoutQuestions(mDNS *const m)
5418 {
5419 m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future
5420 TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any);
5421 TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly);
5422 }
5423
5424 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5425 {
5426 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5427 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5428 while (rrPtr)
5429 {
5430 rrNext = rrPtr->next;
5431 mDNSPlatformMemFree(rrPtr);
5432 rrPtr = rrNext;
5433 }
5434 m->SPSRRSet = mDNSNULL;
5435 }
5436
5437 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5438 {
5439 mDNS_Lock(m); // Must grab lock before trying to read m->timenow
5440
5441 if (m->timenow - m->NextScheduledEvent >= 0)
5442 {
5443 int i;
5444 AuthRecord *head, *tail;
5445 mDNSu32 slot;
5446 AuthGroup *ag;
5447
5448 verbosedebugf("mDNS_Execute");
5449
5450 if (m->CurrentQuestion)
5451 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5452 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5453
5454 if (m->CurrentRecord)
5455 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5456
5457 // 1. If we're past the probe suppression time, we can clear it
5458 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5459
5460 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5461 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5462
5463 // 3. Purge our cache of stale old records
5464 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5465 {
5466 mDNSu32 numchecked = 0;
5467 m->NextCacheCheck = m->timenow + FutureTime;
5468 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5469 {
5470 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5471 {
5472 CacheGroup **cp = &m->rrcache_hash[slot];
5473 m->rrcache_nextcheck[slot] = m->timenow + FutureTime;
5474 while (*cp)
5475 {
5476 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5477 numchecked++;
5478 CheckCacheExpiration(m, slot, *cp);
5479 if ((*cp)->members) cp=&(*cp)->next;
5480 else ReleaseCacheGroup(m, cp);
5481 }
5482 }
5483 // Even if we didn't need to actually check this slot yet, still need to
5484 // factor its nextcheck time into our overall NextCacheCheck value
5485 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5486 m->NextCacheCheck = m->rrcache_nextcheck[slot];
5487 }
5488 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5489 }
5490
5491 if (m->timenow - m->NextScheduledSPS >= 0)
5492 {
5493 m->NextScheduledSPS = m->timenow + FutureTime;
5494 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords
5495 CheckProxyRecords(m, m->ResourceRecords);
5496 }
5497
5498 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now
5499
5500 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5501 // as records could have expired during that check
5502 if (m->timenow - m->NextScheduledKA >= 0)
5503 {
5504 m->NextScheduledKA = m->timenow + FutureTime;
5505 mDNS_SendKeepalives(m);
5506 }
5507
5508 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5509 if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0))
5510 {
5511 // Schedule immediate network change processing to leave the multicast group
5512 // since the delay time has expired since the previous active registration or query.
5513 m->NetworkChanged = m->timenow;
5514 m->NextBonjourDisableTime = 0;
5515 m->BonjourEnabled = 0;
5516
5517 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5518 }
5519 #endif
5520
5521 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5522 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5523 {
5524 m->AnnounceOwner = 0;
5525 }
5526
5527 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5528 {
5529 m->DelaySleep = 0;
5530 if (m->SleepState == SleepState_Transferring)
5531 {
5532 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5533 BeginSleepProcessing(m);
5534 }
5535 }
5536
5537 // 4. See if we can answer any of our new local questions from the cache
5538 for (i=0; m->NewQuestions && i<1000; i++)
5539 {
5540 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5541 AnswerNewQuestion(m);
5542 }
5543 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5544
5545 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5546 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5547 for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5548 {
5549 m->LocalRemoveEvents = mDNSfalse;
5550 m->CurrentRecord = m->ResourceRecords;
5551 CheckRmvEventsForLocalRecords(m);
5552 // Walk the LocalOnly records and deliver the RMV events
5553 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5554 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5555 {
5556 m->CurrentRecord = ag->members;
5557 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5558 }
5559 }
5560
5561 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5562
5563 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5564 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5565
5566 head = tail = mDNSNULL;
5567 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5568 {
5569 AuthRecord *rr = m->NewLocalRecords;
5570 m->NewLocalRecords = m->NewLocalRecords->next;
5571 if (LocalRecordReady(rr))
5572 {
5573 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5574 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5575 }
5576 else if (!rr->next)
5577 {
5578 // If we have just one record that is not ready, we don't have to unlink and
5579 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5580 // terminate and set the NewLocalRecords to rr.
5581 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5582 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5583 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5584
5585 head = rr;
5586 }
5587 else
5588 {
5589 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records
5590 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5591 // if this is the first record we are skipping, move to the end of the list.
5592 // if we have already skipped records before, append it at the end.
5593 while (*p && *p != rr) p=&(*p)->next;
5594 if (*p) *p = rr->next; // Cut this record from the list
5595 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5596 if (!head)
5597 {
5598 while (*p) p=&(*p)->next;
5599 *p = rr;
5600 head = tail = rr;
5601 }
5602 else
5603 {
5604 tail->next = rr;
5605 tail = rr;
5606 }
5607 rr->next = mDNSNULL;
5608 }
5609 }
5610 m->NewLocalRecords = head;
5611 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5612
5613 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5614
5615 // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5616 // to our local questions
5617 if (m->NewLocalOnlyRecords)
5618 {
5619 m->NewLocalOnlyRecords = mDNSfalse;
5620 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5621 {
5622 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5623 {
5624 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5625 {
5626 AuthRecord *rr = ag->NewLocalOnlyRecords;
5627 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5628 // LocalOnly records should always be ready as they never probe
5629 if (LocalRecordReady(rr))
5630 {
5631 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5632 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5633 }
5634 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5635 }
5636 // We limit about 100 per AuthGroup that can be serviced at a time
5637 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5638 }
5639 }
5640 }
5641
5642 // 5. See what packets we need to send
5643 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5644 DiscardDeregistrations(m);
5645 if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5646 {
5647 // If the platform code is ready, and we're not suppressing packet generation right now
5648 // then send our responses, probes, and questions.
5649 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5650 // We send queries next, because there might be final-stage probes that complete their probing here, causing
5651 // them to advance to announcing state, and we want those to be included in any announcements we send out.
5652 // Finally, we send responses, including the previously mentioned records that just completed probing.
5653 m->SuppressSending = 0;
5654
5655 // 6. Send Query packets. This may cause some probing records to advance to announcing state
5656 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5657 if (m->timenow - m->NextScheduledQuery >= 0)
5658 {
5659 DNSQuestion *q;
5660 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5661 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5662 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5663 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5664 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5665 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5666 }
5667 if (m->timenow - m->NextScheduledProbe >= 0)
5668 {
5669 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5670 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5671 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5672 }
5673
5674 // 7. Send Response packets, including probing records just advanced to announcing state
5675 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5676 if (m->timenow - m->NextScheduledResponse >= 0)
5677 {
5678 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5679 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5680 }
5681 }
5682
5683 // Clear RandomDelay values, ready to pick a new different value next time
5684 m->RandomQueryDelay = 0;
5685 m->RandomReconfirmDelay = 0;
5686
5687 // See if any questions (or local-only questions) have timed out
5688 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5689 #ifndef UNICAST_DISABLED
5690 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5691 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5692 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5693 #endif
5694 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5695 extern void serviceBLE();
5696 if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE();
5697 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5698 }
5699
5700 // Note about multi-threaded systems:
5701 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5702 // performing mDNS API operations that change our next scheduled event time.
5703 //
5704 // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5705 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5706 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5707 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5708 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5709 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5710 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5711 // without blocking. This avoids the race condition between the signal from the other thread arriving
5712 // just *before* or just *after* the main thread enters the blocking primitive.
5713 //
5714 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5715 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5716 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5717 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5718 // by the time it gets to the timer callback function).
5719
5720 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5721 return(m->NextScheduledEvent);
5722 }
5723
5724 #ifndef UNICAST_DISABLED
5725 mDNSlocal void SuspendLLQs(mDNS *m)
5726 {
5727 DNSQuestion *q;
5728 for (q = m->Questions; q; q = q->next)
5729 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5730 { q->ReqLease = 0; sendLLQRefresh(m, q); }
5731 }
5732 #endif // UNICAST_DISABLED
5733
5734 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5735 {
5736 AuthRecord *rr;
5737 AuthGroup *ag;
5738
5739 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5740 if (ag)
5741 {
5742 for (rr = ag->members; rr; rr=rr->next)
5743 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5744 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5745 {
5746 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5747 return mDNStrue;
5748 }
5749 }
5750 return mDNSfalse;
5751 }
5752
5753 // ActivateUnicastQuery() is called from three places:
5754 // 1. When a new question is created
5755 // 2. On wake from sleep
5756 // 3. When the DNS configuration changes
5757 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5758 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5759 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5760 {
5761 if (!question->DuplicateOf)
5762 {
5763 debugf("ActivateUnicastQuery: %##s %s%s",
5764 question->qname.c, DNSTypeName(question->qtype), ScheduleImmediately ? " ScheduleImmediately" : "");
5765 question->CNAMEReferrals = 0;
5766 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5767 if (question->LongLived)
5768 {
5769 question->state = LLQ_Init;
5770 question->id = zeroOpaque64;
5771 question->servPort = zeroIPPort;
5772 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5773 }
5774 // If the question has local answers, then we don't want answers from outside
5775 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5776 {
5777 question->ThisQInterval = InitialQuestionInterval;
5778 question->LastQTime = m->timenow - question->ThisQInterval;
5779 SetNextQueryTime(m, question);
5780 }
5781 }
5782 }
5783
5784 // Caller should hold the lock
5785 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5786 CallbackBeforeStartQuery BeforeStartCallback, void *context)
5787 {
5788 DNSQuestion *q;
5789 DNSQuestion *restart = mDNSNULL;
5790
5791 mDNS_CheckLock(m);
5792
5793 // 1. Flush the cache records
5794 if (flushCacheRecords) flushCacheRecords(m);
5795
5796 // 2. Even though we may have purged the cache records above, before it can generate RMV event
5797 // we are going to stop the question. Hence we need to deliver the RMV event before we
5798 // stop the question.
5799 //
5800 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5801 // application callback can potentially stop the current question (detected by CurrentQuestion) or
5802 // *any* other question which could be the next one that we may process here. RestartQuestion
5803 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5804 // if the "next" question is stopped while the CurrentQuestion is stopped
5805
5806 if (m->RestartQuestion)
5807 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5808 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5809
5810 m->RestartQuestion = m->Questions;
5811 while (m->RestartQuestion)
5812 {
5813 q = m->RestartQuestion;
5814 m->RestartQuestion = q->next;
5815 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5816 // question) through their "nta" pointer. Normally when the original query stops, it stops the
5817 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5818 // question followed by the original query that refers to this GetZoneData question, we will end up
5819 // freeing the GetZoneData question and then start the "freed" question at the end.
5820
5821 if (IsGetZoneDataQuestion(q))
5822 {
5823 DNSQuestion *refq = q->next;
5824 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5825 // debug stuff, we just try to find the referencing question and don't do much with it
5826 while (refq)
5827 {
5828 if (q == &refq->nta->question)
5829 {
5830 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5831 }
5832 refq = refq->next;
5833 }
5834 continue;
5835 }
5836
5837 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5838 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5839
5840 // If the search domains did not change, then we restart all the queries. Otherwise, only
5841 // for queries for which we "might" have appended search domains ("might" because we may
5842 // find results before we apply search domains even though AppendSearchDomains is set to 1)
5843 if (!SearchDomainsChanged || q->AppendSearchDomains)
5844 {
5845 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5846 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5847 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5848 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5849 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5850 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5851 // for the original query using these cache entries as ADDs were never delivered using these cache
5852 // entries and hence this order is needed.
5853
5854 // If the query is suppressed, the RMV events won't be delivered
5855 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5856
5857 // Suppressed status does not affect questions that are answered using local records
5858 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5859
5860 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q,
5861 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains);
5862 mDNS_StopQuery_internal(m, q);
5863 if (q->ResetHandler) q->ResetHandler(q);
5864 q->next = restart;
5865 restart = q;
5866 }
5867 }
5868
5869 // 3. Callback before we start the query
5870 if (BeforeStartCallback) BeforeStartCallback(m, context);
5871
5872 // 4. Restart all the stopped queries
5873 while (restart)
5874 {
5875 q = restart;
5876 restart = restart->next;
5877 q->next = mDNSNULL;
5878 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5879 mDNS_StartQuery_internal(m, q);
5880 }
5881 }
5882
5883 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5884 {
5885 DNSQuestion *q;
5886
5887 #ifndef UNICAST_DISABLED
5888 // Retrigger all our uDNS questions
5889 if (m->CurrentQuestion)
5890 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5891 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5892 m->CurrentQuestion = m->Questions;
5893 while (m->CurrentQuestion)
5894 {
5895 q = m->CurrentQuestion;
5896 m->CurrentQuestion = m->CurrentQuestion->next;
5897 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
5898 }
5899 #endif
5900
5901 // Retrigger all our mDNS questions
5902 for (q = m->Questions; q; q=q->next) // Scan our list of questions
5903 mDNSCoreRestartQuestion(m, q);
5904 }
5905
5906 // restart question if it's multicast and currently active
5907 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5908 {
5909 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5910 {
5911 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
5912 q->RequestUnicast = kDefaultRequestUnicastCount;
5913 q->LastQTime = m->timenow - q->ThisQInterval;
5914 q->RecentAnswerPkts = 0;
5915 ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5916 m->NextScheduledQuery = m->timenow;
5917 }
5918 }
5919
5920 // restart the probe/announce cycle for multicast record
5921 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5922 {
5923 if (!AuthRecord_uDNS(rr))
5924 {
5925 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5926 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5927
5928 if (mDNS_KeepaliveRecord(&rr->resrec))
5929 {
5930 rr->AnnounceCount = 0; // Do not announce keepalive records
5931 }
5932 else
5933 {
5934 // announceCount < 0 indicates default announce count should be used
5935 if (announceCount < 0)
5936 announceCount = InitialAnnounceCount;
5937 if (rr->AnnounceCount < (mDNSu8)announceCount)
5938 rr->AnnounceCount = (mDNSu8)announceCount;
5939 }
5940
5941 rr->SendNSECNow = mDNSNULL;
5942 InitializeLastAPTime(m, rr);
5943 }
5944 }
5945
5946 // ***************************************************************************
5947 #if COMPILER_LIKES_PRAGMA_MARK
5948 #pragma mark -
5949 #pragma mark - Power Management (Sleep/Wake)
5950 #endif
5951
5952 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
5953 {
5954 #ifndef IDLESLEEPCONTROL_DISABLED
5955 mDNSBool allowSleep = mDNStrue;
5956 char reason[128];
5957
5958 reason[0] = 0;
5959
5960 if (m->SystemSleepOnlyIfWakeOnLAN)
5961 {
5962 // Don't sleep if we are a proxy for any services
5963 if (m->ProxyRecords)
5964 {
5965 allowSleep = mDNSfalse;
5966 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
5967 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
5968 }
5969
5970 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
5971 {
5972 // Scan the list of active interfaces
5973 NetworkInterfaceInfo *intf;
5974 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5975 {
5976 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
5977 {
5978 // Disallow sleep if this interface doesn't support NetWake
5979 if (!intf->NetWake)
5980 {
5981 allowSleep = mDNSfalse;
5982 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5983 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
5984 break;
5985 }
5986
5987 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5988 // that will be offloaded. If not, we should prevent sleep.
5989 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5990 #if APPLE_OSX_mDNSResponder
5991 if (!SupportsInNICProxy(intf))
5992 #endif
5993 {
5994 // Disallow sleep if there is no sleep proxy server
5995 const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
5996 if ( cr == mDNSNULL)
5997 {
5998 allowSleep = mDNSfalse;
5999 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
6000 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
6001 break;
6002 }
6003 else if (m->SPSType != 0)
6004 {
6005 mDNSu32 mymetric = LocalSPSMetric(m);
6006 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
6007 if (metric >= mymetric)
6008 {
6009 allowSleep = mDNSfalse;
6010 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
6011 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
6012 break;
6013 }
6014 }
6015 }
6016 }
6017 }
6018 }
6019 }
6020
6021 // Call the platform code to enable/disable sleep
6022 mDNSPlatformSetAllowSleep(allowSleep, reason);
6023 #else
6024 (void) m;
6025 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6026 }
6027
6028 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
6029 {
6030 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6031 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6032 // to send.
6033 if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
6034 m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
6035 {
6036 return mDNSfalse;
6037 }
6038
6039 // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6040 // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6041 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6042 // updateid and we should have returned from above.
6043 //
6044 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6045 // platform function to extract the value from "intf" every time.
6046
6047 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6048 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6049 return mDNStrue;
6050
6051 return mDNSfalse;
6052 }
6053
6054 mDNSexport void UpdateRMAC(mDNS *const m, void *context)
6055 {
6056 IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
6057 m->CurrentRecord = m->ResourceRecords;
6058
6059 if (!addrmap)
6060 {
6061 LogMsg("UpdateRMAC: Address mapping is NULL");
6062 return;
6063 }
6064
6065 while (m->CurrentRecord)
6066 {
6067 AuthRecord *rr = m->CurrentRecord;
6068 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6069 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
6070 {
6071 mDNSAddr raddr;
6072 getKeepaliveRaddr(m, rr, &raddr);
6073 if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
6074 {
6075 // Update the MAC address only if it is not a zero MAC address
6076 mDNSEthAddr macAddr;
6077 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
6078 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
6079 {
6080 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
6081 }
6082 }
6083 }
6084 m->CurrentRecord = rr->next;
6085 }
6086
6087 if (addrmap)
6088 mDNSPlatformMemFree(addrmap);
6089
6090 }
6091
6092 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
6093 {
6094 mDNSu16 newrdlength;
6095 mDNSAddr laddr = zeroAddr;
6096 mDNSAddr raddr = zeroAddr;
6097 mDNSEthAddr eth = zeroEthAddr;
6098 mDNSIPPort lport = zeroIPPort;
6099 mDNSIPPort rport = zeroIPPort;
6100 mDNSu32 timeout = 0;
6101 mDNSu32 seq = 0;
6102 mDNSu32 ack = 0;
6103 mDNSu16 win = 0;
6104 UTF8str255 txt;
6105 int rdsize;
6106 RData *newrd;
6107 mDNSTCPInfo mti;
6108 mStatus ret;
6109
6110 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered
6111 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6112 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
6113 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
6114 {
6115 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
6116 return mStatus_UnknownErr;
6117 }
6118
6119 if (updateMac)
6120 {
6121 if (laddr.type == mDNSAddrType_IPv4)
6122 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%s", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ethAddr);
6123 else
6124 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%s", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ethAddr);
6125
6126 }
6127 else
6128 {
6129 // If this keepalive packet would be sent on a different interface than the current one that we are processing
6130 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6131 // this DNS NULL record, it does not send any keepalives as it does not have all the information
6132 mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
6133 ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti);
6134 if (ret != mStatus_NoError)
6135 {
6136 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
6137 return ret;
6138 }
6139 if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
6140 {
6141 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID);
6142 return mStatus_BadParamErr;
6143 }
6144
6145 if (laddr.type == mDNSAddrType_IPv4)
6146 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), &eth, mti.seq, mti.ack, mti.window);
6147 else
6148 newrdlength = mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), &eth, mti.seq, mti.ack, mti.window);
6149 }
6150
6151 // Did we insert a null byte at the end ?
6152 if (newrdlength == (sizeof(txt.c) - 1))
6153 {
6154 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
6155 return mStatus_NoMemoryErr;
6156 }
6157
6158 // Include the length for the null byte at the end
6159 txt.c[0] = newrdlength + 1;
6160 // Account for the first length byte and the null byte at the end
6161 newrdlength += 2;
6162
6163 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
6164 newrd = (RData *) mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
6165 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
6166
6167 newrd->MaxRDLength = (mDNSu16) rdsize;
6168 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
6169
6170 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6171 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6172 // If the resource record has data that we allocated in a previous pass (to update MAC address),
6173 // free that memory here before copying in the new data.
6174 if ( rr->resrec.rdata != &rr->rdatastorage)
6175 {
6176 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
6177 mDNSPlatformMemFree(rr->resrec.rdata);
6178 }
6179 SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata
6180
6181 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
6182 return mStatus_NoError;
6183 }
6184
6185 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
6186 {
6187 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
6188 const int sps = intf->NextSPSAttempt / 3;
6189 AuthRecord *rr;
6190 mDNSOpaque16 msgid;
6191 mDNSu32 scopeid;
6192
6193 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6194 if (!intf->SPSAddr[sps].type)
6195 {
6196 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6197 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6198 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6199 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
6200 goto exit;
6201 }
6202
6203 // Mark our mDNS records (not unicast records) for transfer to SPS
6204 if (mDNSOpaque16IsZero(id))
6205 {
6206 // We may have to register this record over multiple interfaces and we don't want to
6207 // overwrite the id. We send the registration over interface X with id "IDX" and before
6208 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6209 // for "IDX". Hence, we want to use the same ID across all interfaces.
6210 //
6211 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6212 // option check below will set the same ID across the records from the same owner. Records
6213 // with different owner option gets different ID.
6214 msgid = mDNS_NewMessageID(m);
6215 for (rr = m->ResourceRecords; rr; rr=rr->next)
6216 {
6217 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
6218 {
6219 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6220 {
6221 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6222 {
6223 rr->SendRNow = mDNSInterfaceMark; // mark it now
6224 // When we are registering on the first interface, rr->updateid is zero in which case
6225 // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6226 // At the end, all the updates sent across all the interfaces with the same ID.
6227 if (mDNSOpaque16IsZero(rr->updateid))
6228 rr->updateid = msgid;
6229 else
6230 msgid = rr->updateid;
6231 }
6232 }
6233 }
6234 }
6235 }
6236 else
6237 msgid = id;
6238
6239 while (1)
6240 {
6241 mDNSu8 *p = m->omsg.data;
6242 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6243 // For now we follow that same logic for SPS registrations too.
6244 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6245 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6246 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
6247
6248 for (rr = m->ResourceRecords; rr; rr=rr->next)
6249 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
6250 {
6251 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6252 {
6253 mDNSu8 *newptr;
6254 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
6255
6256 // If we can't update the keepalive record, don't send it
6257 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
6258 {
6259 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
6260 {
6261 bit_clr_opaque64(rr->updateIntID, scopeid);
6262 }
6263 rr->SendRNow = mDNSNULL;
6264 continue;
6265 }
6266
6267 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
6268 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
6269 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
6270 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
6271 if (!newptr)
6272 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
6273 else
6274 {
6275 LogSPS("SendSPSRegistration put %s 0x%x 0x%x (updateid %d) %s", intf->ifname, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(m->omsg.h.id), ARDisplayString(m, rr));
6276 rr->SendRNow = mDNSNULL;
6277 rr->ThisAPInterval = mDNSPlatformOneSecond;
6278 rr->LastAPTime = m->timenow;
6279 // should be initialized above
6280 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
6281 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6282 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
6283 p = newptr;
6284 }
6285 }
6286 }
6287
6288 if (!m->omsg.h.mDNS_numUpdates) break;
6289 else
6290 {
6291 AuthRecord opt;
6292 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
6293 opt.resrec.rrclass = NormalMaxDNSMessageData;
6294 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record
6295 opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
6296 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
6297 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4;
6298 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
6299 if (!owner->HMAC.l[0]) // If no owner data,
6300 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information
6301 else // otherwise, use the owner data we were given
6302 {
6303 opt.resrec.rdata->u.opt[1].u.owner = *owner;
6304 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner;
6305 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
6306 }
6307 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
6308 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6309 if (!p)
6310 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
6311 else
6312 {
6313 mStatus err;
6314
6315 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
6316 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
6317 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss
6318 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSfalse);
6319 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
6320 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
6321 {
6322 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
6323 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
6324 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
6325 return;
6326 }
6327 }
6328 }
6329 }
6330
6331 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime
6332
6333 exit:
6334 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
6335 }
6336
6337 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
6338 {
6339 AuthRecord *ar;
6340 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
6341 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
6342 return mDNStrue;
6343 }
6344
6345 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6346 {
6347 AuthRecord *newRR = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(*newRR));
6348 if (newRR == mDNSNULL)
6349 {
6350 LogSPS("%s : could not allocate memory for new resource record", __func__);
6351 return;
6352 }
6353
6354 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6355 rr->resrec.rroriginalttl, rr->resrec.RecordType,
6356 rr->ARType, mDNSNULL, mDNSNULL);
6357
6358 AssignDomainName(&newRR->namestorage, &rr->namestorage);
6359 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6360 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6361 newRR->resrec.rrclass = rr->resrec.rrclass;
6362
6363 if (rr->resrec.rrtype == kDNSType_A)
6364 {
6365 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4;
6366 }
6367 else if (rr->resrec.rrtype == kDNSType_AAAA)
6368 {
6369 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6370 }
6371 SetNewRData(&newRR->resrec, mDNSNULL, 0);
6372
6373 // Insert the new node at the head of the list.
6374 newRR->next = m->SPSRRSet;
6375 m->SPSRRSet = newRR;
6376 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6377 }
6378
6379 // Some records are interface specific and some are not. The ones that are supposed to be registered
6380 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6381 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6382 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6383 // registration on all the interfaces
6384 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6385 {
6386 AuthRecord *ar;
6387 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6388
6389 *WakeOnlyService = mDNSfalse;
6390
6391 // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6392 // make sure that the old sleep proxy records are removed.
6393 mDNSCoreFreeProxyRR(m);
6394
6395 // For records that are registered only on a specific interface, mark only that bit as it will
6396 // never be registered on any other interface. For others, it should be sent on all interfaces.
6397 for (ar = m->ResourceRecords; ar; ar=ar->next)
6398 {
6399 ar->updateIntID = zeroOpaque64;
6400 ar->updateid = zeroID;
6401 if (AuthRecord_uDNS(ar))
6402 {
6403 continue;
6404 }
6405 if (ar->AuthFlags & AuthFlagsWakeOnly)
6406 {
6407 if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6408 {
6409 ar->ImmedAnswer = mDNSInterfaceMark;
6410 *WakeOnlyService = mDNStrue;
6411 continue;
6412 }
6413 }
6414 if (!ar->resrec.InterfaceID)
6415 {
6416 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6417 ar->updateIntID = updateIntID;
6418 }
6419 else
6420 {
6421 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6422 // exactly this.
6423 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6424 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6425 {
6426 bit_set_opaque64(ar->updateIntID, scopeid);
6427 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6428 ar->updateIntID.l[0], ARDisplayString(m, ar));
6429 }
6430 else
6431 {
6432 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6433 }
6434 }
6435 // Store the A and AAAA records that we registered with the sleep proxy.
6436 // We will use this to prevent spurious name conflicts that may occur when we wake up
6437 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6438 {
6439 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6440 }
6441 }
6442 }
6443
6444 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6445 {
6446 AuthRecord *ar;
6447 OwnerOptData owner = zeroOwner;
6448
6449 SendSPSRegistrationForOwner(m, intf, id, &owner);
6450
6451 for (ar = m->ResourceRecords; ar; ar=ar->next)
6452 {
6453 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6454 {
6455 owner = ar->WakeUp;
6456 SendSPSRegistrationForOwner(m, intf, id, &owner);
6457 }
6458 }
6459 }
6460
6461 // RetrySPSRegistrations is called from SendResponses, with the lock held
6462 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6463 {
6464 AuthRecord *rr;
6465 NetworkInterfaceInfo *intf;
6466
6467 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6468 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6469 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6470 intf->NextSPSAttemptTime++;
6471
6472 // Retry any record registrations that are due
6473 for (rr = m->ResourceRecords; rr; rr=rr->next)
6474 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6475 {
6476 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6477 {
6478 // If we still have registrations pending on this interface, send it now
6479 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6480 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6481 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6482 {
6483 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6484 SendSPSRegistration(m, intf, rr->updateid);
6485 }
6486 }
6487 }
6488
6489 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6490 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6491 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6492 intf->NextSPSAttempt++;
6493 }
6494
6495 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6496 {
6497 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6498 int sps = (int)(question - intf->NetWakeResolve);
6499 (void)m; // Unused
6500 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6501
6502 if (!AddRecord) return; // Don't care about REMOVE events
6503 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs
6504
6505 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6506
6507 if (answer->rrtype == kDNSType_SRV)
6508 {
6509 // 1. Got the SRV record; now look up the target host's IP address
6510 mDNS_StopQuery(m, question);
6511 intf->SPSPort[sps] = answer->rdata->u.srv.port;
6512 AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6513 question->qtype = kDNSType_A;
6514 mDNS_StartQuery(m, question);
6515 }
6516 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6517 {
6518 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6519 mDNS_StopQuery(m, question);
6520 question->ThisQInterval = -1;
6521 intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6522 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6523 mDNS_Lock(m);
6524 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6525 mDNS_Unlock(m);
6526 }
6527 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6528 {
6529 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6530 mDNS_StopQuery(m, question);
6531 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6532 question->qtype = kDNSType_AAAA;
6533 mDNS_StartQuery(m, question);
6534 }
6535 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6536 {
6537 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6538 mDNS_StopQuery(m, question);
6539 question->ThisQInterval = -1;
6540 intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6541 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6542 mDNS_Lock(m);
6543 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now
6544 mDNS_Unlock(m);
6545 }
6546 }
6547
6548 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6549 {
6550 AuthRecord *rr;
6551 for (rr = m->ResourceRecords; rr; rr=rr->next)
6552 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6553 return mDNStrue;
6554 return mDNSfalse;
6555 }
6556
6557 #define WAKE_ONLY_SERVICE 1
6558 #define AC_ONLY_SERVICE 2
6559
6560 #ifdef APPLE_OSX_mDNSResponder
6561 mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6562 {
6563 AuthRecord *rr;
6564 *servicePresent = mDNSfalse;
6565
6566 // Mark all the records we need to deregister and send them
6567 for (rr = m->ResourceRecords; rr; rr=rr->next)
6568 {
6569 // If the service type is wake only service and the auth flags match and requires a goodbye
6570 // OR if the service type is AC only and it is not a keepalive record,
6571 // mark the records we need to deregister and send them
6572 if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6573 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6574 (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6575 {
6576 rr->ImmedAnswer = mDNSInterfaceMark;
6577 *servicePresent = mDNStrue;
6578 }
6579 }
6580 }
6581 #endif
6582
6583 #ifdef APPLE_OSX_mDNSResponder
6584 // This function is used only in the case of local NIC proxy. For external
6585 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6586 // walk the resource records.
6587 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6588 {
6589 return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6590 }
6591 #endif // APPLE_OSX_mDNSResponder
6592
6593
6594 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6595 {
6596 AuthRecord *rr;
6597 m->SleepState = SleepState_Sleeping;
6598
6599 // If AllInterfaces is not set, the caller has already marked it appropriately
6600 // on which interfaces this should be sent.
6601 if (AllInterfaces)
6602 {
6603 NetworkInterfaceInfo *intf;
6604 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6605 {
6606 intf->SendGoodbyes = 1;
6607 }
6608 }
6609 if (unicast)
6610 {
6611 #ifndef UNICAST_DISABLED
6612 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records
6613 #endif /* UNICAST_DISABLED */
6614 }
6615
6616 // Mark all the records we need to deregister and send them
6617 for (rr = m->ResourceRecords; rr; rr=rr->next)
6618 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6619 rr->ImmedAnswer = mDNSInterfaceMark;
6620 SendResponses(m);
6621 }
6622
6623 /*
6624 * This function attempts to detect if multiple interfaces are on the same subnet.
6625 * It makes this determination based only on the IPv4 Addresses and subnet masks.
6626 * IPv6 link local addresses that are configured by default on all interfaces make
6627 * it hard to make this determination
6628 *
6629 * The 'real' fix for this would be to send out multicast packets over one interface
6630 * and conclude that multiple interfaces are on the same subnet only if these packets
6631 * are seen on other interfaces on the same system
6632 */
6633 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6634 {
6635 NetworkInterfaceInfo *intf;
6636 NetworkInterfaceInfo *newIntf;
6637 mDNSu32 i;
6638
6639 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6640 {
6641 if ((newIntf->InterfaceID != intfid) ||
6642 (newIntf->ip.type != mDNSAddrType_IPv4))
6643 {
6644 continue;
6645 }
6646 for ( i = 0; i < count; i++)
6647 {
6648 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6649 {
6650 if ((intf->InterfaceID != regID[i]) ||
6651 (intf->ip.type != mDNSAddrType_IPv4))
6652 {
6653 continue;
6654 }
6655 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6656 {
6657 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6658 return (mDNStrue);
6659 }
6660 }
6661 }
6662 }
6663 return (mDNSfalse);
6664 }
6665
6666 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6667 {
6668 // Loop through the keepalive records and callback with an error
6669 m->CurrentRecord = m->ResourceRecords;
6670 while (m->CurrentRecord)
6671 {
6672 AuthRecord *const rr = m->CurrentRecord;
6673 if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6674 {
6675 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6676 if (rr->RecordCallback)
6677 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6678 }
6679 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6680 m->CurrentRecord = rr->next;
6681 }
6682 }
6683
6684 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6685 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6686 {
6687 mDNSBool SendGoodbyes = mDNStrue;
6688 mDNSBool WakeOnlyService = mDNSfalse;
6689 mDNSBool invokeKACallback = mDNStrue;
6690 const CacheRecord *sps[3] = { mDNSNULL };
6691 mDNSOpaque64 updateIntID = zeroOpaque64;
6692 mDNSInterfaceID registeredIntfIDS[128] = { 0 };
6693 mDNSu32 registeredCount = 0;
6694 int skippedRegistrations = 0;
6695
6696 m->NextScheduledSPRetry = m->timenow;
6697
6698 // Clear out the SCDynamic entry that stores the external SPS information
6699 mDNSPlatformClearSPSData();
6700
6701 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6702 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6703 else // If we have at least one advertised service
6704 {
6705 NetworkInterfaceInfo *intf;
6706 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6707 {
6708 mDNSBool skipFullSleepProxyRegistration = mDNSfalse;
6709 // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6710 intf->SendGoodbyes = 0;
6711
6712 // If it is not multicast capable, we could not have possibly discovered sleep proxy
6713 // servers.
6714 if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6715 {
6716 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6717 continue;
6718 }
6719
6720 // If we are not capable of WOMP, then don't register with sleep proxy.
6721 //
6722 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6723 // We might find sleep proxy servers in the cache and start a resolve on them.
6724 // But then if the interface goes away, we won't stop these questions because
6725 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6726 // to stop both the browse and resolve questions.
6727 if (!intf->NetWake)
6728 {
6729 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6730 intf->SendGoodbyes = 1;
6731 skippedRegistrations++;
6732 continue;
6733 }
6734
6735 // Check if we have already registered with a sleep proxy for this subnet.
6736 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6737 // to the interface.
6738 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6739 {
6740 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname);
6741 skipFullSleepProxyRegistration = mDNStrue;
6742 }
6743
6744 #if APPLE_OSX_mDNSResponder
6745 if (SupportsInNICProxy(intf))
6746 {
6747 mDNSBool keepaliveOnly = mDNSfalse;
6748 const mStatus err = ActivateLocalProxy(intf, skipFullSleepProxyRegistration, &keepaliveOnly);
6749 if (!skipFullSleepProxyRegistration && !err)
6750 {
6751 SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6752
6753 // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6754 SendGoodbyes = (keepaliveOnly) ? mDNStrue: mDNSfalse;
6755 invokeKACallback = mDNSfalse;
6756 LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6757 // This will leave m->SleepState set to SleepState_Transferring,
6758 // which is okay because with no outstanding resolves, or updates in flight,
6759 // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6760
6761 // Setting this flag activates the SleepLimit which delays sleep by 5 seconds and
6762 // will allow the system to deregister any BTMM records.
6763 m->NextScheduledSPRetry = m->timenow + (5 * mDNSPlatformOneSecond);
6764 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6765 registeredCount++;
6766 }
6767 continue;
6768 }
6769 #endif // APPLE_OSX_mDNSResponder
6770 if (!skipFullSleepProxyRegistration)
6771 {
6772 #if APPLE_OSX_mDNSResponder
6773 // If on battery, do not attempt to offload to external sleep proxies
6774 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6775 {
6776 LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6777 return;
6778 }
6779 #endif // APPLE_OSX_mDNSResponder
6780 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6781 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6782 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6783 else
6784 {
6785 int i;
6786 mDNSu32 scopeid;
6787 SendGoodbyes = mDNSfalse;
6788 intf->NextSPSAttempt = 0;
6789 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6790
6791 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6792 // Now we know for sure that we have to wait for registration to complete on this interface.
6793 if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6794 bit_set_opaque64(updateIntID, scopeid);
6795
6796 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6797 for (i=0; i<3; i++)
6798 {
6799 #if ForceAlerts
6800 if (intf->SPSAddr[i].type)
6801 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6802 if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6803 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6804 #endif
6805 intf->SPSAddr[i].type = mDNSAddrType_None;
6806 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6807 intf->NetWakeResolve[i].ThisQInterval = -1;
6808 if (sps[i])
6809 {
6810 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6811 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6812 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6813 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6814
6815 // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6816 registeredIntfIDS[registeredCount] = intf->InterfaceID;
6817 registeredCount++;
6818 }
6819 }
6820 }
6821 }
6822 }
6823 }
6824
6825 // If we have at least one interface on which we are registering with an external sleep proxy,
6826 // initialize all the records appropriately.
6827 if (!mDNSOpaque64IsZero(&updateIntID))
6828 SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6829
6830 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6831 // the records to a sleep proxy.
6832 if (invokeKACallback)
6833 {
6834 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6835 DoKeepaliveCallbacks(m);
6836 }
6837
6838 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6839 // interfaces and also deregister unicast registrations.
6840 //
6841 // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6842 // for both multicast and unicast.
6843 //
6844 // - If we skipped registrations on some interfaces, then we have already marked
6845 // them appropriately above. We don't need to send goodbyes for unicast as
6846 // we have registered with at least one sleep proxy.
6847 //
6848 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6849 //
6850 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6851 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6852 // at WakeOnlyServices first.
6853 if (SendGoodbyes)
6854 {
6855 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6856 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6857 }
6858 else if (skippedRegistrations)
6859 {
6860 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6861 SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6862 }
6863 else if (WakeOnlyService)
6864 {
6865 // If we saw WakeOnly service above, send the goodbyes now.
6866 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6867 SendResponses(m);
6868 }
6869 }
6870
6871 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6872 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6873 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6874 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6875 {
6876 AuthRecord *rr;
6877
6878 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_INFO,
6879 PUB_S " (old state %d) at %d", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6880
6881 if (sleep && !m->SleepState) // Going to sleep
6882 {
6883 mDNS_Lock(m);
6884 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6885 if (m->SPSSocket)
6886 {
6887 mDNSu8 oldstate = m->SPSState;
6888 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6889 m->SPSState = 2;
6890 #ifndef SPC_DISABLED
6891 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6892 #else
6893 (void)oldstate;
6894 #endif
6895 mDNS_ReclaimLockAfterCallback();
6896 }
6897 #ifdef _LEGACY_NAT_TRAVERSAL_
6898 if (m->SSDPSocket)
6899 {
6900 mDNSPlatformUDPClose(m->SSDPSocket);
6901 m->SSDPSocket = mDNSNULL;
6902 }
6903 #endif
6904 m->SleepState = SleepState_Transferring;
6905 if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6906 {
6907 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6908 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
6909 "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6910 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6911 }
6912 else
6913 {
6914 m->DelaySleep = 0;
6915 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6916 m->mDNSStats.Sleeps++;
6917 BeginSleepProcessing(m);
6918 }
6919
6920 #ifndef UNICAST_DISABLED
6921 SuspendLLQs(m);
6922 #endif
6923 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S ") seq %d",
6924 m->SleepState,
6925 m->SleepState == SleepState_Transferring ? "Transferring" :
6926 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum);
6927 mDNS_Unlock(m);
6928 }
6929 else if (!sleep) // Waking up
6930 {
6931 mDNSu32 slot;
6932 CacheGroup *cg;
6933 CacheRecord *cr;
6934 NetworkInterfaceInfo *intf;
6935 mDNSs32 currtime, diff;
6936
6937 mDNS_Lock(m);
6938 // Reset SleepLimit back to 0 now that we're awake again.
6939 m->SleepLimit = 0;
6940
6941 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6942 if (m->SleepState != SleepState_Awake)
6943 {
6944 m->SleepState = SleepState_Awake;
6945 m->SleepSeqNum++;
6946 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6947 // then we enforce a minimum delay of five seconds before we begin sleep processing.
6948 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6949 // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6950 m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep);
6951 }
6952
6953 if (m->SPSState == 3)
6954 {
6955 m->SPSState = 0;
6956 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
6957 }
6958 m->mDNSStats.Wakes++;
6959 // ... and the same for NextSPSAttempt
6960 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
6961
6962 // Restart unicast and multicast queries
6963 mDNSCoreRestartQueries(m);
6964
6965 // and reactivtate service registrations
6966 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6967 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
6968 "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
6969
6970 // 2. Re-validate our cache records
6971 currtime = mDNSPlatformUTC();
6972
6973 diff = currtime - m->TimeSlept;
6974 FORALL_CACHERECORDS(slot, cg, cr)
6975 {
6976 // Temporary fix: For unicast cache records, look at how much time we slept.
6977 // Adjust the RecvTime by the amount of time we slept so that we age the
6978 // cache record appropriately. If it is expired already, purge. If there
6979 // is a network change that happens after the wakeup, we might purge the
6980 // cache anyways and this helps only in the case where there are no network
6981 // changes across sleep/wakeup transition.
6982 //
6983 // Note: If there is a network/DNS server change that already happened and
6984 // these cache entries are already refreshed and we are getting a delayed
6985 // wake up notification, we might adjust the TimeRcvd based on the time slept
6986 // now which can cause the cache to purge pre-maturely. As this is not a very
6987 // common case, this should happen rarely.
6988 if (!cr->resrec.InterfaceID)
6989 {
6990 if (diff > 0)
6991 {
6992 mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
6993 const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
6994
6995 // -if we have slept longer than the remaining TTL, purge and start fresh.
6996 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6997 // a sufficiently big value which could cause the value to go into the future
6998 // because of the signed comparison of time. For this to happen, we should have been
6999 // sleeping really long (~24 days). For now, we want to be conservative and flush even
7000 // if we have slept for more than two days.
7001
7002 if (diff >= remain || diff > (2 * 24 * 3600))
7003 {
7004 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7005 "mDNSCoreMachineSleep: " PRI_S ": Purging cache entry SleptTime %d, Remaining TTL %d",
7006 CRDisplayString(m, cr), diff, remain);
7007 mDNS_PurgeCacheResourceRecord(m, cr);
7008 continue;
7009 }
7010 cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
7011 if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
7012 {
7013 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7014 "mDNSCoreMachineSleep: " PRI_S ": Purging after adjusting the remaining TTL %d by %d seconds",
7015 CRDisplayString(m, cr), remain, diff);
7016 mDNS_PurgeCacheResourceRecord(m, cr);
7017 }
7018 else
7019 {
7020 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7021 "mDNSCoreMachineSleep: " PRI_S ": Adjusted the remain ttl %u by %d seconds",
7022 CRDisplayString(m, cr), remain, diff);
7023 }
7024 }
7025 }
7026 else
7027 {
7028 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
7029 }
7030 }
7031
7032 // 3. Retrigger probing and announcing for all our authoritative records
7033 for (rr = m->ResourceRecords; rr; rr=rr->next)
7034 {
7035 if (AuthRecord_uDNS(rr))
7036 {
7037 ActivateUnicastRegistration(m, rr);
7038 }
7039 else
7040 {
7041 mDNSCoreRestartRegistration(m, rr, -1);
7042 }
7043 }
7044
7045 // 4. Refresh NAT mappings
7046 // We don't want to have to assume that all hardware can necessarily keep accurate
7047 // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7048 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7049 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7050 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7051 // than five seconds from now.
7052 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7053 RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
7054 mDNS_Unlock(m);
7055 }
7056 }
7057
7058 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
7059 {
7060 DNSQuestion *q;
7061 AuthRecord *rr;
7062 NetworkInterfaceInfo *intf;
7063
7064 mDNS_Lock(m);
7065
7066 if (m->DelaySleep) goto notready;
7067
7068 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7069 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
7070
7071 m->NextScheduledSPRetry = now + 0x40000000UL;
7072
7073 // See if we might need to retransmit any lost Sleep Proxy Registrations
7074 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7075 if (intf->NextSPSAttempt >= 0)
7076 {
7077 if (now - intf->NextSPSAttemptTime >= 0)
7078 {
7079 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7080 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
7081 SendSPSRegistration(m, intf, zeroID);
7082 // Don't need to "goto notready" here, because if we do still have record registrations
7083 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7084 }
7085 else
7086 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
7087 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
7088 }
7089
7090 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7091 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7092 {
7093 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
7094 if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
7095 {
7096 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7097 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
7098 goto spsnotready;
7099 }
7100 }
7101
7102 // Scan list of registered records
7103 for (rr = m->ResourceRecords; rr; rr = rr->next)
7104 if (!AuthRecord_uDNS(rr))
7105 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7106 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS updateIntID 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; }
7107
7108 // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7109 for (q = m->Questions; q; q = q->next)
7110 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
7111 {
7112 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7113 goto notready;
7114 }
7115
7116 // Scan list of registered records
7117 for (rr = m->ResourceRecords; rr; rr = rr->next)
7118 if (AuthRecord_uDNS(rr))
7119 {
7120 if (rr->state == regState_Refresh && rr->tcp)
7121 { LogSPS("mDNSCoreReadyForSleep: waiting for Record updateIntID 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto notready; }
7122 }
7123
7124 mDNS_Unlock(m);
7125 return mDNStrue;
7126
7127 spsnotready:
7128
7129 // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7130 // and allow up to ten seconds more to complete wide-area deregistration instead
7131 if (now - m->SleepLimit >= 0)
7132 {
7133 LogMsg("Failed to register with SPS, now sending goodbyes");
7134
7135 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7136 if (intf->NetWakeBrowse.ThisQInterval >= 0)
7137 {
7138 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7139 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
7140 mDNS_DeactivateNetWake_internal(m, intf);
7141 }
7142
7143 for (rr = m->ResourceRecords; rr; rr = rr->next)
7144 if (!AuthRecord_uDNS(rr))
7145 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7146 {
7147 LogSPS("ReadyForSleep clearing updateIntID 0x%x 0x%x (updateid %d) for %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
7148 rr->updateIntID = zeroOpaque64;
7149 }
7150
7151 // We'd really like to allow up to ten seconds more here,
7152 // but if we don't respond to the sleep notification within 30 seconds
7153 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7154 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7155 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7156 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7157 m->SleepLimit = now + mDNSPlatformOneSecond * 1;
7158
7159 SendSleepGoodbyes(m, mDNStrue, mDNStrue);
7160 }
7161
7162 notready:
7163 mDNS_Unlock(m);
7164 return mDNSfalse;
7165 }
7166
7167 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
7168 {
7169 AuthRecord *ar;
7170
7171 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7172 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7173 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7174 // and if that happens we don't want to just give up and go back to sleep and never try again.
7175 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes
7176
7177 NATTraversalInfo *nat;
7178 for (nat = m->NATTraversals; nat; nat=nat->next)
7179 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
7180 {
7181 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time
7182 if (e - t > 0) e = t;
7183 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7184 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
7185 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
7186 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
7187 nat->retryInterval / mDNSPlatformOneSecond,
7188 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
7189 (t - now) / mDNSPlatformOneSecond);
7190 }
7191
7192 // This loop checks both the time we need to renew wide-area registrations,
7193 // and the time we need to renew Sleep Proxy registrations
7194 for (ar = m->ResourceRecords; ar; ar = ar->next)
7195 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
7196 {
7197 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time
7198 if (e - t > 0) e = t;
7199 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7200 ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
7201 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
7202 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
7203 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
7204 }
7205
7206 return(e - now);
7207 }
7208
7209 // ***************************************************************************
7210 #if COMPILER_LIKES_PRAGMA_MARK
7211 #pragma mark -
7212 #pragma mark - Packet Reception Functions
7213 #endif
7214
7215 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7216
7217 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
7218 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
7219 {
7220 mDNSu8 *responseptr = response->data;
7221 const mDNSu8 *const limit = response->data + sizeof(response->data);
7222 const mDNSu8 *ptr = query->data;
7223 AuthRecord *rr;
7224 mDNSu32 maxttl = (!InterfaceID) ? mDNSMaximumUnicastTTLSeconds : mDNSMaximumMulticastTTLSeconds;
7225 int i;
7226
7227 // Initialize the response fields so we can answer the questions
7228 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
7229
7230 // ***
7231 // *** 1. Write out the list of questions we are actually going to answer with this packet
7232 // ***
7233 if (LegacyQuery)
7234 {
7235 maxttl = kStaticCacheTTL;
7236 for (i=0; i<query->h.numQuestions; i++) // For each question...
7237 {
7238 DNSQuestion q;
7239 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question...
7240 if (!ptr) return(mDNSNULL);
7241
7242 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers
7243 {
7244 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question
7245 { // then put the question in the question section
7246 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
7247 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
7248 break; // break out of the ResponseRecords loop, and go on to the next question
7249 }
7250 }
7251 }
7252
7253 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
7254 }
7255
7256 // ***
7257 // *** 2. Write Answers
7258 // ***
7259 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7260 if (rr->NR_AnswerTo)
7261 {
7262 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
7263 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7264 if (p) responseptr = p;
7265 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
7266 }
7267
7268 // ***
7269 // *** 3. Write Additionals
7270 // ***
7271 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7272 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
7273 {
7274 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
7275 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7276 if (p) responseptr = p;
7277 else debugf("GenerateUnicastResponse: No more space for additionals");
7278 }
7279
7280 return(responseptr);
7281 }
7282
7283 // AuthRecord *our is our Resource Record
7284 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7285 // Returns 0 if there is no conflict
7286 // Returns +1 if there was a conflict and we won
7287 // Returns -1 if there was a conflict and we lost and have to rename
7288 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
7289 {
7290 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
7291 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
7292 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7293 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7294
7295 #if defined(__clang_analyzer__)
7296 // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7297 // There are no clear indications from the analyzer of the cause of the supposed problem.
7298 mDNSPlatformMemZero(ourdata, 1);
7299 mDNSPlatformMemZero(pktdata, 1);
7300 #endif
7301 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
7302 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
7303 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
7304 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict
7305
7306 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost
7307 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won
7308 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost
7309 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won
7310
7311 LogMsg("CompareRData ERROR: Invalid state");
7312 return(-1);
7313 }
7314
7315 mDNSlocal mDNSBool PacketRecordMatches(const AuthRecord *const rr, const CacheRecord *const pktrr, const AuthRecord *const master)
7316 {
7317 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7318 {
7319 const AuthRecord *r2 = rr;
7320 while (r2->DependentOn) r2 = r2->DependentOn;
7321 if (r2 == master) return(mDNStrue);
7322 }
7323 return(mDNSfalse);
7324 }
7325
7326 // See if we have an authoritative record that's identical to this packet record,
7327 // whose canonical DependentOn record is the specified master record.
7328 // The DependentOn pointer is typically used for the TXT record of service registrations
7329 // It indicates that there is no inherent conflict detection for the TXT record
7330 // -- it depends on the SRV record to resolve name conflicts
7331 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7332 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7333 // If the record has no DependentOn, then just return that record's pointer
7334 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7335 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
7336 {
7337 const AuthRecord *r1;
7338 for (r1 = m->ResourceRecords; r1; r1=r1->next)
7339 {
7340 if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7341 }
7342 for (r1 = m->DuplicateRecords; r1; r1=r1->next)
7343 {
7344 if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7345 }
7346 return(mDNSfalse);
7347 }
7348
7349 // Find the canonical RRSet pointer for this RR received in a packet.
7350 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7351 // pointers (if any) to make sure we return the canonical member of this name/type/class
7352 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7353 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
7354 {
7355 const AuthRecord *rr;
7356 for (rr = m->ResourceRecords; rr; rr=rr->next)
7357 {
7358 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7359 {
7360 return(rr->RRSet ? rr->RRSet : rr);
7361 }
7362 }
7363 return(mDNSNULL);
7364 }
7365
7366 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7367 // as one of our records (our) but different rdata.
7368 // 1. If our record is not a type that's supposed to be unique, we don't care.
7369 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7370 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7371 // points to our record, ignore this conflict (e.g. the packet record matches one of our
7372 // TXT records, and that record is marked as dependent on 'our', its SRV record).
7373 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7374 // are members of the same RRSet, then this is not a conflict.
7375 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7376 {
7377 // If not supposed to be unique, not a conflict
7378 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7379
7380 // If a dependent record, not a conflict
7381 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7382 else
7383 {
7384 // If the pktrr matches a member of ourset, not a conflict
7385 const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7386 const AuthRecord *pktset = FindRRSet(m, pktrr);
7387 if (pktset == ourset) return(mDNSfalse);
7388
7389 // For records we're proxying, where we don't know the full
7390 // relationship between the records, having any matching record
7391 // in our AuthRecords list is sufficient evidence of non-conflict
7392 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7393 }
7394
7395 // Okay, this is a conflict
7396 return(mDNStrue);
7397 }
7398
7399 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7400 // the record list and/or question list.
7401 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7402 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7403 DNSQuestion *q, AuthRecord *our)
7404 {
7405 int i;
7406 const mDNSu8 *ptr = LocateAuthorities(query, end);
7407 mDNSBool FoundUpdate = mDNSfalse;
7408
7409 for (i = 0; i < query->h.numAuthorities; i++)
7410 {
7411 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7412 if (!ptr) break;
7413 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && CacheRecordAnswersQuestion(&m->rec.r, q))
7414 {
7415 FoundUpdate = mDNStrue;
7416 if (PacketRRConflict(m, our, &m->rec.r))
7417 {
7418 int result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7419 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype;
7420 if (!result) result = CompareRData(our, &m->rec.r);
7421 if (result)
7422 {
7423 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7424 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7425 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7426 }
7427 // If we lost the tie-break for simultaneous probes, we don't immediately give up, because we might be seeing stale packets on the network.
7428 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7429 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7430 if (result < 0)
7431 {
7432 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7433 our->ProbeCount = DefaultProbeCountForTypeUnique;
7434 our->AnnounceCount = InitialAnnounceCount;
7435 InitializeLastAPTime(m, our);
7436 goto exit;
7437 }
7438 }
7439 #if 0
7440 else
7441 {
7442 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7443 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7444 }
7445 #endif
7446 }
7447 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7448 }
7449 if (!FoundUpdate)
7450 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7451 exit:
7452 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7453 }
7454
7455 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7456 {
7457 CacheGroup *cg = CacheGroupForRecord(m, pktrr);
7458 CacheRecord *rr;
7459 mDNSBool match;
7460 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7461 {
7462 if (!pktrr->InterfaceID)
7463 {
7464 const mDNSu32 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7465 const mDNSu32 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7466 match = (id1 == id2);
7467 }
7468 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7469
7470 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7471 }
7472 return(rr);
7473 }
7474 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7475 {
7476 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7477 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
7478 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7479 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7480 }
7481
7482 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7483 {
7484 if (m->CurrentRecord)
7485 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7486 m->CurrentRecord = thelist;
7487
7488 // Normally, the RDATA of the keepalive record will be different each time and hence we always
7489 // clean up the keepalive record.
7490 while (m->CurrentRecord)
7491 {
7492 AuthRecord *const rr = m->CurrentRecord;
7493 if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7494 {
7495 if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7496 {
7497 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7498 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7499 DeregisterProxyRecord(m, rr);
7500 }
7501 }
7502 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7503 // new records could have been added to the end of the list as a result of that call.
7504 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7505 m->CurrentRecord = rr->next;
7506 }
7507 }
7508
7509 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7510 // to check our lists and discard any stale duplicates of this record we already have
7511 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7512 {
7513 if (m->CurrentRecord)
7514 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7515 m->CurrentRecord = thelist;
7516 while (m->CurrentRecord)
7517 {
7518 AuthRecord *const rr = m->CurrentRecord;
7519 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7520 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7521 {
7522 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7523 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7524 DeregisterProxyRecord(m, rr);
7525 }
7526 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7527 // new records could have been added to the end of the list as a result of that call.
7528 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7529 m->CurrentRecord = rr->next;
7530 }
7531 }
7532
7533 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7534 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7535 {
7536 if (m->CurrentRecord)
7537 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7538 m->CurrentRecord = thelist;
7539 while (m->CurrentRecord)
7540 {
7541 AuthRecord *const rr = m->CurrentRecord;
7542 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7543 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7544 {
7545 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7546 {
7547 // We don't do this here because we know that the host is waking up at this point, so we don't send
7548 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7549 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7550 #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7551 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7552 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7553 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7554 #endif
7555 }
7556 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7557 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7558 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7559 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7560 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7561 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7562 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7563 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7564 }
7565 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7566 // new records could have been added to the end of the list as a result of that call.
7567 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7568 m->CurrentRecord = rr->next;
7569 }
7570 }
7571
7572 // ProcessQuery examines a received query to see if we have any answers to give
7573 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7574 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7575 mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7576 {
7577 const mDNSBool FromLocalSubnet = mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7578 AuthRecord *ResponseRecords = mDNSNULL;
7579 AuthRecord **nrp = &ResponseRecords;
7580
7581 #if POOF_ENABLED
7582 mDNSBool notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID); // We don't run the POOF algorithm on D2D interfaces.
7583 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated
7584 CacheRecord **eap = &ExpectedAnswers;
7585 #endif // POOF_ENABLED
7586
7587 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet
7588 DNSQuestion **dqp = &DupQuestions;
7589 mDNSs32 delayresponse = 0;
7590 mDNSBool SendLegacyResponse = mDNSfalse;
7591 const mDNSu8 *ptr;
7592 mDNSu8 *responseptr = mDNSNULL;
7593 AuthRecord *rr;
7594 int i;
7595 CacheRecord *McastNSEC3Records = mDNSNULL;
7596
7597 // ***
7598 // *** 1. Look in Additional Section for an OPT record
7599 // ***
7600 ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7601 if (ptr)
7602 {
7603 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7604 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7605 {
7606 const rdataOPT *opt;
7607 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7608 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7609 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7610 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7611 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7612 {
7613 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7614 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7615 }
7616 }
7617 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7618 }
7619
7620 //
7621 // Look in Authority Section for NSEC3 record
7622 //
7623
7624 mDNSParseNSEC3Records(m, query, end, InterfaceID, &McastNSEC3Records);
7625
7626 // ***
7627 // *** 2. Parse Question Section and mark potential answers
7628 // ***
7629 ptr = query->data;
7630 for (i=0; i<query->h.numQuestions; i++) // For each question...
7631 {
7632 mDNSBool QuestionNeedsMulticastResponse;
7633 int NumAnswersForThisQuestion = 0;
7634 AuthRecord *NSECAnswer = mDNSNULL;
7635 DNSQuestion pktq, *q;
7636 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7637 if (!ptr) goto exit;
7638
7639 // The only queries that *need* a multicast response are:
7640 // * Queries sent via multicast
7641 // * from port 5353
7642 // * that don't have the kDNSQClass_UnicastResponse bit set
7643 // These queries need multicast responses because other clients will:
7644 // * suppress their own identical questions when they see these questions, and
7645 // * expire their cache records if they don't see the expected responses
7646 // For other queries, we may still choose to send the occasional multicast response anyway,
7647 // to keep our neighbours caches warm, and for ongoing conflict detection.
7648 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7649
7650 if (pktq.qclass & kDNSQClass_UnicastResponse)
7651 m->mDNSStats.UnicastBitInQueries++;
7652 else
7653 m->mDNSStats.NormalQueries++;
7654
7655 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7656 pktq.qclass &= ~kDNSQClass_UnicastResponse;
7657
7658 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7659 // can result in user callbacks which may change the record list and/or question list.
7660 // Also note: we just mark potential answer records here, without trying to build the
7661 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7662 // from that list while we're in the middle of trying to build it.
7663 if (m->CurrentRecord)
7664 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7665 m->CurrentRecord = m->ResourceRecords;
7666 while (m->CurrentRecord)
7667 {
7668 rr = m->CurrentRecord;
7669 m->CurrentRecord = rr->next;
7670 if (AnyTypeRecordAnswersQuestion(rr, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7671 {
7672 m->mDNSStats.MatchingAnswersForQueries++;
7673 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7674 {
7675 if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7676 ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7677 else if (ResourceRecordIsValidAnswer(rr))
7678 {
7679 NumAnswersForThisQuestion++;
7680
7681 // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7682 // unicast answer back to the source, because timeliness in answering probes is important.
7683
7684 // Notes:
7685 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7686 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7687 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7688 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7689 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7690 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7691 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7692 {
7693 // We only mark this question for sending if it is at least one second since the last time we multicast it
7694 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7695 // This is to guard against the case where someone blasts us with queries as fast as they can.
7696 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond ||
7697 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7698 rr->NR_AnswerTo = NR_AnswerMulticast;
7699 }
7700 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7701 }
7702 }
7703 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7704 {
7705 // If we don't have any answers for this question, but we do own another record with the same name,
7706 // then we'll want to mark it to generate an NSEC record on this interface
7707 if (!NSECAnswer) NSECAnswer = rr;
7708 }
7709 }
7710 }
7711
7712 if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7713 {
7714 NumAnswersForThisQuestion++;
7715 NSECAnswer->SendNSECNow = InterfaceID;
7716 m->NextScheduledResponse = m->timenow;
7717 }
7718
7719 // If we couldn't answer this question, someone else might be able to,
7720 // so use random delay on response to reduce collisions
7721 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7722
7723 if (query->h.flags.b[0] & kDNSFlag0_TC)
7724 m->mDNSStats.KnownAnswerMultiplePkts++;
7725 // We only do the following accelerated cache expiration and duplicate question suppression processing
7726 // for non-truncated multicast queries with multicast responses.
7727 // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7728 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7729 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7730 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7731 {
7732 #if POOF_ENABLED
7733 if (notD2D)
7734 {
7735 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname);
7736 CacheRecord *cr;
7737
7738 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7739 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7740 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7741 {
7742 if (SameNameCacheRecordAnswersQuestion(cr, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7743 {
7744 if (!cr->NextInKAList && eap != &cr->NextInKAList)
7745 {
7746 *eap = cr;
7747 eap = &cr->NextInKAList;
7748 }
7749 }
7750 }
7751 }
7752 #endif // POOF_ENABLED
7753
7754 // Check if this question is the same as any of mine.
7755 // We only do this for non-truncated queries. Right now it would be too complicated to try
7756 // to keep track of duplicate suppression state between multiple packets, especially when we
7757 // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7758 for (q = m->Questions; q; q=q->next)
7759 {
7760 if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7761 {
7762 if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7763 {
7764 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7765 {
7766 if (q->qtype == pktq.qtype &&
7767 q->qclass == pktq.qclass &&
7768 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7769 { *dqp = q; dqp = &q->NextInDQList; }
7770 }
7771 }
7772 }
7773 }
7774 }
7775 }
7776
7777 // ***
7778 // *** 3. Now we can safely build the list of marked answers
7779 // ***
7780 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers
7781 if (rr->NR_AnswerTo) // If we marked the record...
7782 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list
7783
7784 // ***
7785 // *** 4. Add additional records
7786 // ***
7787 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7788
7789 // ***
7790 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7791 // ***
7792 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section...
7793 {
7794 // Get the record...
7795 CacheRecord *ourcacherr;
7796 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7797 if (!ptr) goto exit;
7798 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7799 {
7800 // See if this Known-Answer suppresses any of our currently planned answers
7801 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7802 {
7803 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7804 {
7805 m->mDNSStats.KnownAnswerSuppressions++;
7806 rr->NR_AnswerTo = mDNSNULL;
7807 rr->NR_AdditionalTo = mDNSNULL;
7808 }
7809 }
7810
7811 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7812 for (rr=m->ResourceRecords; rr; rr=rr->next)
7813 {
7814 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7815 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7816 {
7817 if (srcaddr->type == mDNSAddrType_IPv4)
7818 {
7819 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7820 }
7821 else if (srcaddr->type == mDNSAddrType_IPv6)
7822 {
7823 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7824 }
7825 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7826 {
7827 m->mDNSStats.KnownAnswerSuppressions++;
7828 rr->ImmedAnswer = mDNSNULL;
7829 rr->ImmedUnicast = mDNSfalse;
7830 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7831 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7832 #endif
7833 }
7834 }
7835 }
7836
7837 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7838
7839 #if POOF_ENABLED
7840 if (notD2D)
7841 {
7842 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7843 // any records that are suppressed by the Known Answer list in this packet.
7844 eap = &ExpectedAnswers;
7845 while (*eap)
7846 {
7847 CacheRecord *cr = *eap;
7848 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7849 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7850 else eap = &cr->NextInKAList;
7851 }
7852 }
7853 #endif // POOF_ENABLED
7854
7855 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7856 if (!ourcacherr)
7857 {
7858 dqp = &DupQuestions;
7859 while (*dqp)
7860 {
7861 DNSQuestion *q = *dqp;
7862 if (CacheRecordAnswersQuestion(&m->rec.r, q))
7863 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7864 else dqp = &q->NextInDQList;
7865 }
7866 }
7867 }
7868 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
7869 }
7870
7871 // ***
7872 // *** 6. Cancel any additionals that were added because of now-deleted records
7873 // ***
7874 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7875 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7876 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7877
7878 // ***
7879 // *** 7. Mark the send flags on the records we plan to send
7880 // ***
7881 for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7882 {
7883 if (rr->NR_AnswerTo)
7884 {
7885 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response
7886 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response)
7887
7888 // If it's been one TTL/4 since we multicast this, then send a multicast response
7889 // for conflict detection, etc.
7890 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4)
7891 {
7892 SendMulticastResponse = mDNStrue;
7893 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7894 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7895 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7896 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7897 {
7898 m->mDNSStats.UnicastDemotedToMulticast++;
7899 rr->NR_AnswerTo = NR_AnswerMulticast;
7900 }
7901 }
7902
7903 // If the client insists on a multicast response, then we'd better send one
7904 if (rr->NR_AnswerTo == NR_AnswerMulticast)
7905 {
7906 m->mDNSStats.MulticastResponses++;
7907 SendMulticastResponse = mDNStrue;
7908 }
7909 else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7910 {
7911 m->mDNSStats.UnicastResponses++;
7912 SendUnicastResponse = mDNStrue;
7913 }
7914 else if (rr->NR_AnswerTo)
7915 {
7916 SendLegacyResponse = mDNStrue;
7917 }
7918
7919 if (SendMulticastResponse || SendUnicastResponse)
7920 {
7921 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7922 rr->ImmedAnswerMarkTime = m->timenow;
7923 #endif
7924 m->NextScheduledResponse = m->timenow;
7925 // If we're already planning to send this on another interface, just send it on all interfaces
7926 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7927 rr->ImmedAnswer = mDNSInterfaceMark;
7928 else
7929 {
7930 rr->ImmedAnswer = InterfaceID; // Record interface to send it on
7931 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7932 if (srcaddr->type == mDNSAddrType_IPv4)
7933 {
7934 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7935 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
7936 }
7937 else if (srcaddr->type == mDNSAddrType_IPv6)
7938 {
7939 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
7940 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
7941 }
7942 }
7943 }
7944 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7945 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7946 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7947 // else, for a simple unique record reply, we can reply immediately; no need for delay
7948 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms
7949 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms
7950 }
7951 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
7952 {
7953 // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7954 // If two clients on different interfaces do queries that invoke the same optional additional answer,
7955 // then the earlier client is out of luck
7956 rr->ImmedAdditional = InterfaceID;
7957 // No need to set m->NextScheduledResponse here
7958 // We'll send these additional records when we send them, or not, as the case may be
7959 }
7960 }
7961
7962 // ***
7963 // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7964 // ***
7965 if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
7966 {
7967 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7968 mDNSs32 oldss = m->SuppressSending;
7969 if (oldss && delayresponse)
7970 LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
7971 #endif
7972 // Pick a random delay:
7973 // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7974 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7975 // This is an integer value, with resolution determined by the platform clock rate.
7976 // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7977 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7978 // The +49 before dividing is to ensure we round up, not down, to ensure that even
7979 // on platforms where the native clock rate is less than fifty ticks per second,
7980 // we still guarantee that the final calculated delay is at least one platform tick.
7981 // We want to make sure we don't ever allow the delay to be zero ticks,
7982 // because if that happens we'll fail the Bonjour Conformance Test.
7983 // Our final computed delay is 20-120ms for normal delayed replies,
7984 // or 400-500ms in the case of multi-packet known-answer lists.
7985 m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
7986 if (m->SuppressSending == 0) m->SuppressSending = 1;
7987 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7988 if (oldss && delayresponse)
7989 LogMsg("Set SuppressSending to %5ld", m->SuppressSending - m->timenow);
7990 #endif
7991 }
7992
7993 // ***
7994 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7995 // ***
7996 if (SendLegacyResponse)
7997 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
7998
7999 exit:
8000 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8001
8002 // ***
8003 // *** 10. Finally, clear our link chains ready for use next time
8004 // ***
8005 while (ResponseRecords)
8006 {
8007 rr = ResponseRecords;
8008 ResponseRecords = rr->NextResponse;
8009 rr->NextResponse = mDNSNULL;
8010 rr->NR_AnswerTo = mDNSNULL;
8011 rr->NR_AdditionalTo = mDNSNULL;
8012 }
8013
8014 #if POOF_ENABLED
8015 while (ExpectedAnswers && notD2D)
8016 {
8017 CacheRecord *cr = ExpectedAnswers;
8018 ExpectedAnswers = cr->NextInKAList;
8019 cr->NextInKAList = mDNSNULL;
8020
8021 // For non-truncated queries, we can definitively say that we should expect
8022 // to be seeing a response for any records still left in the ExpectedAnswers list
8023 if (!(query->h.flags.b[0] & kDNSFlag0_TC))
8024 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4)
8025 {
8026 cr->UnansweredQueries++;
8027 cr->LastUnansweredTime = m->timenow;
8028 if (cr->UnansweredQueries > 1)
8029 debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr));
8030 SetNextCacheCheckTimeForRecord(m, cr);
8031 }
8032
8033 // If we've seen multiple unanswered queries for this record,
8034 // then mark it to expire in five seconds if we don't get a response by then.
8035 if (cr->UnansweredQueries >= MaxUnansweredQueries)
8036 {
8037 // Only show debugging message if this record was not about to expire anyway
8038 if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond)
8039 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8040 cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr));
8041
8042 m->mDNSStats.PoofCacheDeletions++;
8043 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8044 }
8045 }
8046 #endif // POOF_ENABLED
8047
8048 while (DupQuestions)
8049 {
8050 DNSQuestion *q = DupQuestions;
8051 DupQuestions = q->NextInDQList;
8052 q->NextInDQList = mDNSNULL;
8053 RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
8054 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
8055 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
8056 }
8057
8058 if (McastNSEC3Records)
8059 {
8060 debugf("ProcessQuery: McastNSEC3Records not used");
8061 FreeNSECRecords(m, McastNSEC3Records);
8062 }
8063
8064 return(responseptr);
8065 }
8066
8067 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
8068 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8069 const mDNSInterfaceID InterfaceID)
8070 {
8071 mDNSu8 *responseend = mDNSNULL;
8072 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
8073 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8074
8075 if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr)))
8076 {
8077 const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID";
8078 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8079 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8080 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8081 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8082 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8083 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8084 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data, reason);
8085 return;
8086 }
8087
8088 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8089 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8090 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8091 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
8092 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
8093 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
8094 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
8095
8096 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
8097 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
8098
8099 if (responseend) // If responseend is non-null, that means we built a unicast response packet
8100 {
8101 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8102 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s",
8103 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s",
8104 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
8105 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
8106 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSfalse);
8107 }
8108 }
8109
8110 #if 0
8111 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
8112 {
8113 DNSServer *s;
8114 (void)m; // Unused
8115 (void)srcaddr; // Unused
8116 for (s = m->DNSServers; s; s = s->next)
8117 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
8118 return(mDNSfalse);
8119 }
8120 #endif
8121
8122 struct UDPSocket_struct
8123 {
8124 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8125 };
8126
8127 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp, DNSQuestion ** suspiciousQ)
8128 {
8129 DNSQuestion *q;
8130 for (q = m->Questions; q; q=q->next)
8131 {
8132 if (!tcp && !q->LocalSocket) continue;
8133 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) &&
8134 q->qtype == question->qtype &&
8135 q->qclass == question->qclass &&
8136 q->qnamehash == question->qnamehash &&
8137 SameDomainName(&q->qname, &question->qname))
8138 {
8139 if (mDNSSameOpaque16(q->TargetQID, id)) return(q);
8140 else
8141 {
8142 // Everything but the QIDs match up, should we be suspicious?
8143 if (!tcp && suspiciousQ)
8144 {
8145 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
8146 if (mDNSSameOpaque16(q->LastTargetQID, id)) // Only be suspicious if this is also not the "last" used QID (on a DNS server set change)
8147 {
8148 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, "Ignored but not suspicious LastTargetQID %d TargetQID %d", mDNSVal16(q->LastTargetQID), mDNSVal16(q->TargetQID));
8149 }
8150 else
8151 #endif
8152 *suspiciousQ = q;
8153 }
8154 return(mDNSNULL);
8155 }
8156 }
8157 }
8158 return(mDNSNULL);
8159 }
8160
8161 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8162 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8163 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
8164 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
8165 {
8166 DNSQuestion *q;
8167 (void)id;
8168
8169 for (q = m->Questions; q; q=q->next)
8170 {
8171 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
8172 {
8173 if (!mDNSOpaque16IsZero(q->TargetQID))
8174 {
8175 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
8176
8177 if (mDNSSameOpaque16(q->TargetQID, id))
8178 {
8179 mDNSIPPort srcp;
8180 if (!tcp)
8181 {
8182 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort;
8183 }
8184 else
8185 {
8186 srcp = q->tcpSrcPort;
8187 }
8188 if (mDNSSameIPPort(srcp, port)) return(q);
8189
8190 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue);
8191 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8192 // if (TrustedSource(m, srcaddr)) return(mDNStrue);
8193 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8194 q->qname.c, DNSTypeName(q->qtype), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
8195 return(mDNSNULL);
8196 }
8197 }
8198 else
8199 {
8200 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
8201 return(q);
8202 }
8203 }
8204 }
8205 return(mDNSNULL);
8206 }
8207
8208 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8209 // Currently this applies only to rdata types containing more than one domainname,
8210 // or types where the domainname is not the last item in the structure.
8211 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
8212 {
8213 switch (rr->rrtype)
8214 {
8215 case kDNSType_SOA: return sizeof(rdataSOA);
8216 case kDNSType_RP: return sizeof(rdataRP);
8217 case kDNSType_PX: return sizeof(rdataPX);
8218 default: return rr->rdlength;
8219 }
8220 }
8221
8222 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
8223 {
8224 CacheRecord *rr = mDNSNULL;
8225 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
8226
8227 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
8228
8229 //if (RDLength > InlineCacheRDSize)
8230 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8231
8232 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
8233 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg
8234 if (!rr) NoCacheAnswer(m, &m->rec.r);
8235 else
8236 {
8237 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer
8238 *rr = m->rec.r; // Block copy the CacheRecord object
8239 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment
8240 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header
8241 rr->resrec.mortality = Mortality_Mortal;
8242
8243 rr->DelayDelivery = delay;
8244
8245 // If this is an oversized record with external storage allocated, copy rdata to external storage
8246 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
8247 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8248 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
8249 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8250 if (RDLength > InlineCacheRDSize)
8251 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
8252
8253 rr->next = mDNSNULL; // Clear 'next' pointer
8254 rr->nsec = mDNSNULL;
8255 rr->soa = mDNSNULL;
8256
8257 if (sourceAddress)
8258 rr->sourceAddress = *sourceAddress;
8259
8260 if (!rr->resrec.InterfaceID)
8261 {
8262 m->rrcache_totalused_unicast += rr->resrec.rdlength;
8263 if (DNSSECRecordType(rr->resrec.rrtype))
8264 BumpDNSSECStats(m, kStatsActionIncrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
8265 }
8266
8267 if (Add)
8268 {
8269 *(cg->rrcache_tail) = rr; // Append this record to tail of cache slot list
8270 cg->rrcache_tail = &(rr->next); // Advance tail pointer
8271 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8272 }
8273 else
8274 {
8275 // Can't use the "cg->name" if we are not adding to the cache as the
8276 // CacheGroup may be released anytime if it is empty
8277 domainname *name = (domainname *) mDNSPlatformMemAllocate(DomainNameLength(cg->name));
8278 if (name)
8279 {
8280 AssignDomainName(name, cg->name);
8281 rr->resrec.name = name;
8282 }
8283 else
8284 {
8285 ReleaseCacheRecord(m, rr);
8286 NoCacheAnswer(m, &m->rec.r);
8287 rr = mDNSNULL;
8288 }
8289 }
8290 }
8291 return(rr);
8292 }
8293
8294 mDNSlocal void RefreshCacheRecordCacheGroupOrder(CacheGroup *cg, CacheRecord *cr)
8295 { // Move the cache record to the tail of the cache group to maintain a fresh ordering
8296 if (cg->rrcache_tail != &cr->next) // If not already at the tail
8297 {
8298 CacheRecord **rp;
8299 for (rp = &cg->members; *rp; rp = &(*rp)->next)
8300 {
8301 if (*rp == cr) // This item points to this record
8302 {
8303 *rp = cr->next; // Remove this record
8304 break;
8305 }
8306 }
8307 cr->next = mDNSNULL; // This record is now last
8308 *(cg->rrcache_tail) = cr; // Append this record to tail of cache group
8309 cg->rrcache_tail = &(cr->next); // Advance tail pointer
8310 }
8311 }
8312
8313 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8314 {
8315 rr->TimeRcvd = m->timenow;
8316 rr->resrec.rroriginalttl = ttl;
8317 rr->UnansweredQueries = 0;
8318 if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal;
8319 SetNextCacheCheckTimeForRecord(m, rr);
8320 }
8321
8322 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8323 {
8324 CacheRecord *rr;
8325 CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname);
8326 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8327 if (rr->CRActiveQuestion == q)
8328 {
8329 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8330 RefreshCacheRecord(m, rr, lease);
8331 }
8332 }
8333
8334 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl) // TTL in seconds
8335 {
8336 if (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8337 else if (LLQType == uDNS_LLQ_Events)
8338 {
8339 // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8340 if (ttl == 0xFFFFFFFF) ttl = 0;
8341 else ttl = kLLQ_DefLease;
8342 }
8343 else // else not LLQ (standard uDNS response)
8344 {
8345 // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8346 // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8347 if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8348
8349 ttl = RRAdjustTTL(ttl);
8350
8351 // For mDNS, TTL zero means "delete this record"
8352 // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8353 // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8354 // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8355 // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8356 // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8357 // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8358 // (with the current code) result in the server having even less than three seconds to respond
8359 // before we deleted the record and reported a "remove" event to any active questions.
8360 // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8361 // then things really break (e.g. we end up making a negative cache entry).
8362 // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8363 if (ttl < 15) ttl = 15;
8364 }
8365
8366 return ttl;
8367 }
8368
8369 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8370 // in m->rec.
8371 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist, DNSQuestion *q, mDNSBool *nseclist)
8372 {
8373 CacheRecord *const newcr = &m->rec.r;
8374 ResourceRecord *rr = &newcr->resrec;
8375 const CacheRecord *cr;
8376
8377 *nseclist = mDNSfalse;
8378 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8379 {
8380 domainname *target = GetRRDomainNameTarget(&cr->resrec);
8381 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8382 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8383 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8384 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8385 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8386
8387 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8388 {
8389 LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8390 return (mDNStrue);
8391 }
8392 }
8393
8394 // Either the question requires validation or we are validating a response with DNSSEC in which case
8395 // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8396 // we receive NSECs for our query which does not match the qname and we need to cache in that case
8397 // too. nseclist is set if they have to be cached as part of the negative cache record.
8398 if (q && DNSSECQuestion(q))
8399 {
8400 mDNSBool same = SameDomainName(&q->qname, rr->name);
8401 if (same && (q->qtype == rr->rrtype || rr->rrtype == kDNSType_CNAME))
8402 {
8403 LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q->qtype),
8404 CRDisplayString(m, newcr));
8405 return mDNStrue;
8406 }
8407 // We cache RRSIGS if it covers the question type or NSEC. If it covers a NSEC,
8408 // "nseclist" is set
8409 if (rr->rrtype == kDNSType_RRSIG)
8410 {
8411 RDataBody2 *const rdb = (RDataBody2 *)newcr->smallrdatastorage.data;
8412 rdataRRSig *rrsig = &rdb->rrsig;
8413 mDNSu16 typeCovered = swap16(rrsig->typeCovered);
8414
8415 // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8416 // would match the qtype and they are cached normally as they are not used to prove the
8417 // non-existence of any name. In that case, it is like any other normal dnssec validation
8418 // and hence nseclist should not be set.
8419
8420 if (same && ((typeCovered == q->qtype) || (typeCovered == kDNSType_CNAME)))
8421 {
8422 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m, newcr),
8423 DNSTypeName(q->qtype));
8424 return mDNStrue;
8425 }
8426 else if (typeCovered == kDNSType_NSEC || typeCovered == kDNSType_NSEC3)
8427 {
8428 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m, newcr), DNSTypeName(typeCovered));
8429 *nseclist = mDNStrue;
8430 return mDNStrue;
8431 }
8432 else if (typeCovered == kDNSType_SOA)
8433 {
8434 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m, newcr));
8435 *nseclist = mDNStrue;
8436 return mDNStrue;
8437 }
8438 else return mDNSfalse;
8439 }
8440 if (rr->rrtype == kDNSType_NSEC)
8441 {
8442 if (!UNICAST_NSEC(rr))
8443 {
8444 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m, newcr));
8445 return mDNSfalse;
8446 }
8447 LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m, newcr));
8448 *nseclist = mDNStrue;
8449 return mDNStrue;
8450 }
8451 if (rr->rrtype == kDNSType_SOA)
8452 {
8453 LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m, newcr));
8454 *nseclist = mDNStrue;
8455 return mDNStrue;
8456 }
8457 else if (rr->rrtype == kDNSType_NSEC3)
8458 {
8459 LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m, newcr));
8460 *nseclist = mDNStrue;
8461 return mDNStrue;
8462 }
8463 }
8464 return mDNSfalse;
8465 }
8466
8467 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords)
8468 {
8469 CacheRecord *rp, *next;
8470
8471 for (rp = NSECRecords; rp; rp = next)
8472 {
8473 next = rp->next;
8474 ReleaseCacheRecord(m, rp);
8475 }
8476 }
8477
8478 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8479 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8480 mDNSlocal void mDNSCoreReceiveNoDNSSECAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8481 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID)
8482 {
8483 int i;
8484 const mDNSu8 *ptr = response->data;
8485
8486 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8487 {
8488 DNSQuestion pktq;
8489 DNSQuestion *qptr = mDNSNULL;
8490 ptr = getQuestion(response, ptr, end, InterfaceID, &pktq);
8491 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &pktq, !dstaddr, mDNSNULL)) &&
8492 qptr->ValidatingResponse)
8493 {
8494 DNSQuestion *next, *q;
8495
8496 if (qptr->DuplicateOf)
8497 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr->qname.c, DNSTypeName(qptr->qtype));
8498
8499 // Be careful to call the callback for duplicate questions first and then the original
8500 // question. If we called the callback on the original question, it could stop and
8501 // a duplicate question would become the original question.
8502 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls
8503 for (q = qptr->next ; q && q != m->NewQuestions; q = next)
8504 {
8505 next = q->next;
8506 if (q->DuplicateOf == qptr)
8507 {
8508 if (q->ValidatingResponse)
8509 LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q->qname.c, DNSTypeName(q->qtype));
8510 else
8511 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q->qname.c, DNSTypeName(q->qtype));
8512 if (q->QuestionCallback)
8513 q->QuestionCallback(m, q, mDNSNULL, QC_nodnssec);
8514 }
8515 }
8516 if (qptr->QuestionCallback)
8517 qptr->QuestionCallback(m, qptr, mDNSNULL, QC_nodnssec);
8518 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
8519 }
8520 }
8521 }
8522
8523 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8524 mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, uDNS_LLQType LLQType, mDNSu8 rcode, CacheRecord *NSECRecords)
8525 {
8526 int i;
8527 const mDNSu8 *ptr = response->data;
8528 CacheRecord *SOARecord = mDNSNULL;
8529
8530 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8531 {
8532 DNSQuestion q;
8533 DNSQuestion *qptr = mDNSNULL;
8534 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8535 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr, mDNSNULL)))
8536 {
8537 CacheRecord *cr, *neg = mDNSNULL;
8538 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8539 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8540 {
8541 if (SameNameCacheRecordAnswersQuestion(cr, qptr))
8542 {
8543 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8544 if (RRExpireTime(cr) - m->timenow > 0) break;
8545 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8546 if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = cr;
8547 }
8548 }
8549 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8550 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8551 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8552 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8553 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8554 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8555 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8556 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8557 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8558 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8559 //
8560 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8561 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8562 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8563 // case without creating the negative cache entries, we generate a negative response and let the layer above us
8564 // do the appropriate thing. This negative response is also needed for appending new search domains.
8565 if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8566 {
8567 if (!cr)
8568 {
8569 const mDNSBool noData = ((response->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr) ? mDNStrue : mDNSfalse;
8570 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8571 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME " (" PUB_S ")",
8572 q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(q.qname.c), DNSTypeName(q.qtype));
8573 m->CurrentQuestion = qptr;
8574 // We are not creating a cache record in this case, we need to pass back
8575 // the error we got so that the proxy code can return the right one to
8576 // the application
8577 if (qptr->ProxyQuestion)
8578 qptr->responseFlags = response->h.flags;
8579 GenerateNegativeResponseEx(m, mDNSInterface_Any, QC_forceresponse, noData);
8580 m->CurrentQuestion = mDNSNULL;
8581 }
8582 else
8583 {
8584 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8585 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME " (" PUB_S ")",
8586 q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(q.qname.c), DNSTypeName(q.qtype));
8587 }
8588 }
8589 else
8590 {
8591 if (!cr)
8592 {
8593 // We start off assuming a negative caching TTL of 60 seconds
8594 // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8595 mDNSu32 negttl = 60;
8596 int repeat = 0;
8597 const domainname *name = &q.qname;
8598 mDNSu32 hash = q.qnamehash;
8599
8600 // Special case for our special Microsoft Active Directory "local SOA" check.
8601 // Some cheap home gateways don't include an SOA record in the authority section when
8602 // they send negative responses, so we don't know how long to cache the negative result.
8603 // Because we don't want to keep hitting the root name servers with our query to find
8604 // if we're on a network using Microsoft Active Directory using "local" as a private
8605 // internal top-level domain, we make sure to cache the negative result for at least one day.
8606 if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8607
8608 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8609 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8610 {
8611 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8612 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8613 {
8614 CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec);
8615 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8616 mDNSu32 ttl_s = soa->min;
8617 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8618 // for the SOA record for ".", where the record is reported as non-cacheable
8619 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8620 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8621 ttl_s = m->rec.r.resrec.rroriginalttl;
8622 if (negttl < ttl_s) negttl = ttl_s;
8623
8624 // Create the SOA record as we may have to return this to the questions
8625 // that we are acting as a proxy for currently or in the future.
8626 SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL);
8627
8628 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8629 // with an Authority Section SOA record for d.com, then this is a hint that the authority
8630 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8631 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8632 //
8633 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8634 // along with the negative cache record. For simplicity, we don't create the additional records.
8635 if (!qptr->ProxyQuestion && q.qtype == kDNSType_SOA)
8636 {
8637 int qcount = CountLabels(&q.qname);
8638 int scount = CountLabels(m->rec.r.resrec.name);
8639 if (qcount - 1 > scount)
8640 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8641 repeat = qcount - 1 - scount;
8642 }
8643 }
8644 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8645 }
8646
8647 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8648 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8649 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8650 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8651 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8652 // so that we back off our polling rate and don't keep hitting the server continually.
8653 if (neg)
8654 {
8655 if (negttl < neg->resrec.rroriginalttl * 2)
8656 negttl = neg->resrec.rroriginalttl * 2;
8657 if (negttl > 3600)
8658 negttl = 3600;
8659 }
8660
8661 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary
8662
8663 // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8664 if (neg)
8665 {
8666 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8667 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S,
8668 q.request_id, mDNSVal16(q.TargetQID), neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8669 RefreshCacheRecord(m, neg, negttl);
8670 // When we created the cache for the first time and answered the question, the question's
8671 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8672 // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8673 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8674 // we should reset its question interval here to MaxQuestionInterval.
8675 ResetQuestionState(m, qptr);
8676 if (DNSSECQuestion(qptr))
8677 neg->CRDNSSECQuestion = 1;
8678 // Update the NSEC records again.
8679 // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8680 if (NSECRecords)
8681 {
8682 if (!AddNSECSForCacheRecord(m, NSECRecords, neg, rcode))
8683 {
8684 // We might just have an SOA record for zones that are not signed and hence don't log
8685 // this as an error
8686 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
8687 "[R%u->Q%d] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr " PRI_S" during refresh",
8688 q.request_id, mDNSVal16(q.TargetQID), CRDisplayString(m, neg));
8689 FreeNSECRecords(m, NSECRecords);
8690 neg->CRDNSSECQuestion = 0;
8691 }
8692 NSECRecords = mDNSNULL;
8693 }
8694 if (SOARecord)
8695 {
8696 if (neg->soa)
8697 ReleaseCacheRecord(m, neg->soa);
8698 neg->soa = SOARecord;
8699 SOARecord = mDNSNULL;
8700 }
8701 }
8702 else while (1)
8703 {
8704 CacheRecord *negcr;
8705 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8706 MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8707 m->rec.r.responseFlags = response->h.flags;
8708 // We create SOA records above which might create new cache groups. Earlier
8709 // in the function we looked up the cache group for the name and it could have
8710 // been NULL. If we pass NULL cg to new cache entries that we create below,
8711 // it will create additional cache groups for the same name. To avoid that,
8712 // look up the cache group again to re-initialize cg again.
8713 cg = CacheGroupForName(m, hash, name);
8714 if (NSECRecords && DNSSECQuestion(qptr))
8715 {
8716 // Create the cache entry with delay and then add the NSEC records
8717 // to it and add it immediately.
8718 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8719 if (negcr)
8720 {
8721 negcr->CRDNSSECQuestion = 0;
8722 if (!AddNSECSForCacheRecord(m, NSECRecords, negcr, rcode))
8723 {
8724 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
8725 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr " PRI_S,
8726 q.request_id, mDNSVal16(q.TargetQID), CRDisplayString(m, negcr));
8727 FreeNSECRecords(m, NSECRecords);
8728 }
8729 else
8730 {
8731 negcr->CRDNSSECQuestion = 1;
8732 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8733 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for " PRI_S,
8734 q.request_id, mDNSVal16(q.TargetQID), CRDisplayString(m, negcr));
8735 }
8736 NSECRecords = mDNSNULL;
8737 negcr->DelayDelivery = 0;
8738 CacheRecordDeferredAdd(m, negcr);
8739 }
8740 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8741 break;
8742 }
8743 else
8744 {
8745 // Need to add with a delay so that we can tag the SOA record
8746 negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8747 if (negcr)
8748 {
8749 negcr->CRDNSSECQuestion = 0;
8750 if (DNSSECQuestion(qptr))
8751 negcr->CRDNSSECQuestion = 1;
8752 negcr->DelayDelivery = 0;
8753
8754 if (SOARecord)
8755 {
8756 if (negcr->soa)
8757 ReleaseCacheRecord(m, negcr->soa);
8758 negcr->soa = SOARecord;
8759 SOARecord = mDNSNULL;
8760 }
8761 CacheRecordDeferredAdd(m, negcr);
8762 }
8763 }
8764 m->rec.r.responseFlags = zeroID;
8765 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8766 if (!repeat) break;
8767 repeat--;
8768 name = (const domainname *)(name->c + 1 + name->c[0]);
8769 hash = DomainNameHashValue(name);
8770 }
8771 }
8772 }
8773 }
8774 }
8775 if (NSECRecords)
8776 {
8777 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used");
8778 FreeNSECRecords(m, NSECRecords);
8779 }
8780 if (SOARecord)
8781 {
8782 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8783 ReleaseCacheRecord(m, SOARecord);
8784 }
8785 }
8786
8787 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8788 {
8789 AuthRecord *rrPtr = mDNSNULL;
8790 if (!m->SPSRRSet) return;
8791 LogSPS("Stored Proxy records :");
8792 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8793 {
8794 LogSPS("%s", ARDisplayString(m, rrPtr));
8795 }
8796 }
8797
8798 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8799 {
8800 AuthRecord *rrPtr = mDNSNULL;
8801
8802 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8803 {
8804 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8805 {
8806 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8807 return mDNStrue;
8808 }
8809 }
8810 mDNSCorePrintStoredProxyRecords(m);
8811 return mDNSfalse;
8812 }
8813
8814 mDNSexport CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8815 const mDNSu32 slot, CacheGroup *cg, DNSQuestion *unicastQuestion, CacheRecord ***cfp, CacheRecord **NSECCachePtr,
8816 mDNSInterfaceID InterfaceID)
8817 {
8818 CacheRecord *cr;
8819 CacheRecord **cflocal = *cfp;
8820
8821 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8822 {
8823 mDNSBool match;
8824 // Resource record received via unicast, the resGroupID should match ?
8825 if (!InterfaceID)
8826 {
8827 const mDNSu32 id1 = (cr->resrec.rDNSServer ? cr->resrec.rDNSServer->resGroupID : 0);
8828 const mDNSu32 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8829 match = (id1 == id2);
8830 }
8831 else
8832 match = (cr->resrec.InterfaceID == InterfaceID);
8833 // If we found this exact resource record, refresh its TTL
8834 if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &cr->resrec))
8835 {
8836 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8837 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8838 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8839
8840 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8841 {
8842 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8843 if (cr->NextInCFList == mDNSNULL && *cfp != &cr->NextInCFList && LLQType != uDNS_LLQ_Events)
8844 {
8845 *cflocal = cr;
8846 cflocal = &cr->NextInCFList;
8847 *cflocal = (CacheRecord*)1;
8848 *cfp = &cr->NextInCFList;
8849 }
8850
8851 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8852 if (!(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8853 {
8854 DNSQuestion *q;
8855 for (q = m->Questions; q; q=q->next)
8856 {
8857 if (CacheRecordAnswersQuestion(cr, q))
8858 q->UniqueAnswers++;
8859 }
8860 cr->resrec.RecordType = m->rec.r.resrec.RecordType;
8861 }
8862 }
8863
8864 if (!SameRDataBody(&m->rec.r.resrec, &cr->resrec.rdata->u, SameDomainNameCS))
8865 {
8866 // If the rdata of the packet record differs in name capitalization from the record in our cache
8867 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8868 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8869 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8870 cr->resrec.rroriginalttl = 0;
8871 cr->TimeRcvd = m->timenow;
8872 cr->UnansweredQueries = MaxUnansweredQueries;
8873 SetNextCacheCheckTimeForRecord(m, cr);
8874 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S, CRDisplayString(m, cr));
8875 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S, CRDisplayString(m, &m->rec.r));
8876 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8877 NextCacheCheckEvent(cr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8878 // DO NOT break out here -- we want to continue as if we never found it
8879 }
8880 else if (m->rec.r.resrec.rroriginalttl > 0)
8881 {
8882 DNSQuestion *q;
8883
8884 m->mDNSStats.CacheRefreshed++;
8885
8886 if (cr->resrec.mortality == Mortality_Ghost && unicastQuestion && (unicastQuestion->allowExpired != AllowExpired_AllowExpiredAnswers) && !cr->DelayDelivery)
8887 {
8888 cr->DelayDelivery = NonZeroTime(m->timenow);
8889 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(cr), CRDisplayString(m, cr));
8890 }
8891
8892 if (cr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, cr));
8893 RefreshCacheRecord(m, cr, m->rec.r.resrec.rroriginalttl);
8894 // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop.
8895 // It is safe to call because the else-if body will unconditionally break out of the for-loop now that it has found the entry to update.
8896 RefreshCacheRecordCacheGroupOrder(cg, cr);
8897 cr->responseFlags = response->h.flags;
8898
8899 // If we may have NSEC records returned with the answer (which we don't know yet as it
8900 // has not been processed), we need to cache them along with the first cache
8901 // record in the list that answers the question so that it can be used for validation
8902 // later. The "type" check below is to make sure that we cache on the cache record
8903 // that would answer the question. It is possible that we might cache additional things
8904 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8905 // the record that answers the question.
8906 if (response->h.numAnswers && unicastQuestion && unicastQuestion->qtype == cr->resrec.rrtype
8907 && !(*NSECCachePtr))
8908 {
8909 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S, CRDisplayString(m, cr));
8910 *NSECCachePtr = cr;
8911 }
8912 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8913 // polling the network once we get a valid response back. For the first time when a new
8914 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8915 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8916 // configuration changed, without flushing the cache, we reset the question interval here.
8917 // Currently, we do this for for both multicast and unicast questions as long as the record
8918 // type is unique. For unicast, resource record is always unique and for multicast it is
8919 // true for records like A etc. but not for PTR.
8920 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8921 {
8922 for (q = m->Questions; q; q=q->next)
8923 {
8924 if (!q->DuplicateOf && !q->LongLived &&
8925 ActiveQuestion(q) && CacheRecordAnswersQuestion(cr, q))
8926 {
8927 ResetQuestionState(m, q);
8928 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8929 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8930 }
8931 }
8932 }
8933 break; // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above)
8934 }
8935 else
8936 {
8937 // If the packet TTL is zero, that means we're deleting this record.
8938 // To give other hosts on the network a chance to protest, we push the deletion
8939 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8940 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8941 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8942 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8943 // If the record is already going to expire in less than one second anyway, we leave it alone --
8944 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8945 debugf("DE for %s", CRDisplayString(m, cr));
8946 if (RRExpireTime(cr) - m->timenow > mDNSPlatformOneSecond)
8947 {
8948 cr->resrec.rroriginalttl = 1;
8949 cr->TimeRcvd = m->timenow;
8950 cr->UnansweredQueries = MaxUnansweredQueries;
8951 SetNextCacheCheckTimeForRecord(m, cr);
8952 }
8953 break;
8954 }
8955 }
8956 }
8957 return cr;
8958 }
8959
8960 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8961 const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records)
8962 {
8963 const mDNSu8 *ptr;
8964 CacheRecord *rr;
8965 int i;
8966
8967 if (!response->h.numAuthorities)
8968 return;
8969 ptr = LocateAuthorities(response, end);
8970 if (!ptr)
8971 {
8972 LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8973 return;
8974 }
8975 for (i = 0; i < response->h.numAuthorities && ptr && ptr < end; i++)
8976 {
8977 CacheGroup *cg;
8978
8979 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8980 if (!ptr || m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative || m->rec.r.resrec.rrtype != kDNSType_NSEC3)
8981 {
8982 debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr, CRDisplayString(m, &m->rec.r));
8983 m->rec.r.resrec.RecordType = 0;
8984 continue;
8985 }
8986 cg = CacheGroupForRecord(m, &m->rec.r.resrec);
8987 // Create the cache entry but don't add it to the cache it. We need
8988 // to cache this along with the main cache record.
8989 rr = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cg, 0, mDNSfalse, mDNSNULL);
8990 if (rr)
8991 {
8992 debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m, rr));
8993 *NSEC3Records = rr;
8994 NSEC3Records = &rr->next;
8995 }
8996 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8997 }
8998 }
8999
9000 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
9001 {
9002 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
9003 }
9004
9005 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
9006 // the record list and/or question list.
9007 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
9008 // InterfaceID non-NULL tells us the interface this multicast response was received on
9009 // InterfaceID NULL tells us this was a unicast response
9010 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
9011 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
9012 const DNSMessage *const response, const mDNSu8 *end,
9013 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
9014 const mDNSInterfaceID InterfaceID)
9015 {
9016 int i;
9017 const mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
9018 mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
9019 DNSQuestion *llqMatch = mDNSNULL;
9020 DNSQuestion *unicastQuestion = mDNSNULL;
9021 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
9022
9023 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
9024 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
9025 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
9026 CacheRecord *CacheFlushRecords = (CacheRecord*)1;
9027 CacheRecord **cfp = &CacheFlushRecords;
9028 CacheRecord *NSECRecords = mDNSNULL;
9029 CacheRecord *NSECCachePtr = mDNSNULL;
9030 CacheRecord **nsecp = &NSECRecords;
9031 CacheRecord *McastNSEC3Records = mDNSNULL;
9032 mDNSBool nseclist;
9033 mDNSu8 rcode = '\0';
9034 mDNSBool rrsigsCreated = mDNSfalse;
9035 mDNSBool DNSSECQuestion = mDNSfalse;
9036 NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
9037 mDNSBool recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
9038
9039 // All records in a DNS response packet are treated as equally valid statements of truth. If we want
9040 // to guard against spoof responses, then the only credible protection against that is cryptographic
9041 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
9042 int firstauthority = response->h.numAnswers;
9043 int firstadditional = firstauthority + response->h.numAuthorities;
9044 int totalrecords = firstadditional + response->h.numAdditionals;
9045 const mDNSu8 *ptr = response->data;
9046 DNSServer *uDNSServer = mDNSNULL;
9047
9048 debugf("Received Response from %#-15a addressed to %#-15a on %p with "
9049 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
9050 srcaddr, dstaddr, InterfaceID,
9051 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,",
9052 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
9053 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
9054 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType);
9055
9056 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9057 if (mDNSSameIPPort(srcport, UnicastDNSPort))
9058 {
9059 MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response));
9060 }
9061 #endif
9062
9063 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
9064 // When a DNS client receives a reply with TC
9065 // set, it should ignore that response, and query again, using a
9066 // mechanism, such as a TCP connection, that will permit larger replies.
9067 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
9068 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
9069 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
9070 // <rdar://problem/6690034> Can't bind to Active Directory
9071 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
9072 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
9073 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
9074 // and not even do the TCP query.
9075 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
9076 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
9077 // either the authority section or additional section, then that implies that truncation occurred beyond the answer
9078 // section, and the answer section is therefore assumed to be complete.
9079 //
9080 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
9081 // When a response is so long that truncation is required, the truncation
9082 // should start at the end of the response and work forward in the
9083 // datagram. Thus if there is any data for the authority section, the
9084 // answer section is guaranteed to be unique.
9085 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) &&
9086 ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return;
9087
9088 if (LLQType == uDNS_LLQ_Ignore) return;
9089
9090 // 1. We ignore questions (if any) in mDNS response packets
9091 // 2. If this is an LLQ response, we handle it much the same
9092 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9093 if (ResponseMCast || LLQType == uDNS_LLQ_Events)
9094 ptr = LocateAnswers(response, end);
9095 // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9096 // in this response packet are immediately deemed to be invalid.
9097 else
9098 {
9099 mDNSBool failure, returnEarly;
9100 rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
9101 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
9102 returnEarly = mDNSfalse;
9103 // We could possibly combine this with the similar loop at the end of this function --
9104 // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9105 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9106 // which it was received (or refreshed), and then at the end if we find any cache records which
9107 // answer questions in this packet's question section, but which aren't tagged with this packet's
9108 // packet number, then we deduce they are old and delete them
9109 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
9110 {
9111 DNSQuestion q, *qptr = mDNSNULL, *suspiciousForQ = mDNSNULL;
9112 ptr = getQuestion(response, ptr, end, InterfaceID, &q);
9113 if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr, &suspiciousForQ)))
9114 {
9115 if (!failure)
9116 {
9117 CacheRecord *cr;
9118 // Remember the unicast question that we found, which we use to make caching
9119 // decisions later on in this function
9120 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
9121 if (!mDNSOpaque16IsZero(response->h.id))
9122 {
9123 unicastQuestion = qptr;
9124 if (qptr->qDNSServer && DNSSECQuestion(qptr))
9125 {
9126 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9127 "[R%d->Q%d] mDNSCoreReceiveResponse: Setting aware for " PRI_DM_NAME " (" PUB_S ") on " PRI_IP_ADDR,
9128 qptr->request_id, mDNSVal16(qptr->TargetQID), DM_NAME_PARAM(qptr->qname.c),
9129 DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr);
9130
9131 qptr->qDNSServer->DNSSECAware = mDNStrue;
9132 qptr->qDNSServer->req_DO = mDNStrue;
9133 }
9134 if (qptr->ValidatingResponse)
9135 DNSSECQuestion = mDNStrue;
9136 }
9137 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
9138 {
9139 if (SameNameCacheRecordAnswersQuestion(cr, qptr))
9140 {
9141 debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
9142 cr->resrec.InterfaceID, CRDisplayString(m, cr));
9143 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9144 cr->TimeRcvd = m->timenow - TicksTTL(cr) - 1;
9145 cr->UnansweredQueries = MaxUnansweredQueries;
9146 cr->CRDNSSECQuestion = 0;
9147 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9148 {
9149 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9150 "[R%d->Q%d] mDNSCoreReceiveResponse: CRDNSSECQuestion set for record " PRI_S ", question " PRI_DM_NAME " (" PUB_S ")",
9151 unicastQuestion->request_id, mDNSVal16(unicastQuestion->TargetQID),
9152 CRDisplayString(m, cr), DM_NAME_PARAM(unicastQuestion->qname.c),
9153 DNSTypeName(unicastQuestion->qtype));
9154 cr->CRDNSSECQuestion = 1;
9155 }
9156 }
9157 }
9158 }
9159 else
9160 {
9161 if (qptr)
9162 {
9163 // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
9164 // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
9165 // req_DO to false here, the next retransmission for this question will turn off validation
9166 // and hence retransmit without the EDNS0/DOK option.
9167 if (DNSSECOptionalQuestion(qptr) && qptr->qDNSServer && !qptr->qDNSServer->DNSSECAware)
9168 {
9169 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9170 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query " PRI_DM_NAME " (" PUB_S "), clear DO flag",
9171 qptr->request_id, mDNSVal16(qptr->TargetQID), qptr->qDNSServer, rcode,
9172 DM_NAME_PARAM(q.qname.c), DNSTypeName(q.qtype));
9173 qptr->qDNSServer->req_DO = mDNSfalse;
9174 }
9175 // For Unicast DNS Queries, penalize the DNSServer
9176 else
9177 {
9178 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9179 "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME " (" PUB_S ")",
9180 qptr->request_id, mDNSVal16(qptr->TargetQID), qptr->qDNSServer, rcode,
9181 DM_NAME_PARAM(q.qname.c), DNSTypeName(q.qtype));
9182 PenalizeDNSServer(m, qptr, response->h.flags);
9183 }
9184 }
9185 returnEarly = mDNStrue;
9186 }
9187 }
9188 else if (!InterfaceID && suspiciousForQ)
9189 {
9190 // If a response is suspicious for a question, then reissue the question via TCP
9191 LogInfo("[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded suspiciously to query %##s (%s) qID %d != rID: %d",
9192 suspiciousForQ->request_id, mDNSVal16(suspiciousForQ->TargetQID),
9193 suspiciousForQ->qDNSServer, q.qname.c, DNSTypeName(q.qtype),
9194 mDNSVal16(suspiciousForQ->TargetQID), mDNSVal16(response->h.id));
9195 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
9196 m->NextSuspiciousTimeout = NonZeroTime(m->timenow + (SUSPICIOUS_REPLY_DEFENSE_SECS * mDNSPlatformOneSecond));
9197 #endif
9198 uDNS_RestartQuestionAsTCP(m, suspiciousForQ, srcaddr, srcport);
9199 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9200 suspiciousForQ->metrics.dnsOverTCPState = DNSOverTCP_Suspicious;
9201 #endif
9202 return;
9203 }
9204 }
9205 if (returnEarly)
9206 {
9207 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9208 "[Q%d] Ignoring %2d Answer" PUB_S " %2d Authorit" PUB_S " %2d Additional" PUB_S,
9209 mDNSVal16(response->h.id),
9210 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,",
9211 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,",
9212 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
9213 // not goto exit because we won't have any CacheFlushRecords and we do not want to
9214 // generate negative cache entries (we want to query the next server)
9215 return;
9216 }
9217 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9218 {
9219 BumpDNSSECStats(m, kStatsActionSet, kStatsTypeMsgSize, (end - response->data));
9220 }
9221 }
9222
9223 // Parse the NSEC3 records from the Authority section before we process
9224 // the Answer section so that we can cache them along with the proper
9225 // cache records we create.
9226 if (mDNSOpaque16IsZero(response->h.id))
9227 mDNSParseNSEC3Records(m, response, end, InterfaceID, &McastNSEC3Records);
9228
9229 for (i = 0; i < totalrecords && ptr && ptr < end; i++)
9230 {
9231 // All responses sent via LL multicast are acceptable for caching
9232 // All responses received over our outbound TCP connections are acceptable for caching
9233 // We accept all records in a unicast response to a multicast query once we find one that
9234 // answers an active question.
9235 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse;
9236 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9237 // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9238
9239 const mDNSu8 RecordType =
9240 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns :
9241 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
9242 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
9243 if (!ptr) goto exit; // Break out of the loop and clean up our CacheFlushRecords list before exiting
9244
9245 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
9246 {
9247 mDNSCoreResetRecord(m);
9248 continue;
9249 }
9250
9251 // We have already parsed the NSEC3 records and cached them approrpriately for
9252 // multicast responses.
9253 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype == kDNSType_NSEC3)
9254 {
9255 mDNSCoreResetRecord(m);
9256 continue;
9257 }
9258 // Don't want to cache OPT or TSIG pseudo-RRs
9259 if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
9260 {
9261 mDNSCoreResetRecord(m);
9262 continue;
9263 }
9264 if (m->rec.r.resrec.rrtype == kDNSType_OPT)
9265 {
9266 const rdataOPT *opt;
9267 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9268 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9269 // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9270 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
9271 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
9272 {
9273 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
9274 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
9275 }
9276 mDNSCoreResetRecord(m);
9277 continue;
9278 }
9279 // if a CNAME record points to itself, then don't add it to the cache
9280 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
9281 {
9282 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
9283 mDNSCoreResetRecord(m);
9284 continue;
9285 }
9286
9287 // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9288 // In the case of active LLQs, we'll get remove events when the records actually do go away
9289 // In the case of polling LLQs, we assume the record remains valid until the next poll
9290 if (!mDNSOpaque16IsZero(response->h.id))
9291 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
9292
9293 // If response was not sent via LL multicast,
9294 // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9295 if (!ResponseMCast)
9296 {
9297 if (LLQType)
9298 {
9299 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9300 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9301 // queries to get ADD/RMV events. To lookup the question, we can't use
9302 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9303 // has already matched the question using the 64 bit Id in the packet and we use that here.
9304
9305 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
9306
9307 // If this is a DNSSEC question that is also LongLived, don't accept records from the
9308 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
9309 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
9310 // for both negative responses and wildcard expanded positive responses as both of come
9311 // back with NSEC/NSEC3s.
9312 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9313 AcceptableResponse = mDNSfalse;
9314 }
9315 else if (!AcceptableResponse || !dstaddr)
9316 {
9317 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9318 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9319 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9320 // we create.
9321
9322 DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
9323
9324 // Initialize the DNS server on the resource record which will now filter what questions we answer with
9325 // this record.
9326 //
9327 // We could potentially lookup the DNS server based on the source address, but that may not work always
9328 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9329 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
9330 // on the "id" and "source port", then this response answers the question and assume the response
9331 // came from the same DNS server that we sent the query to.
9332
9333 if (q != mDNSNULL)
9334 {
9335 AcceptableResponse = mDNStrue;
9336 if (!InterfaceID)
9337 {
9338 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9339 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9340 if (!unicastQuestion) unicastQuestion = q; // Acceptable responses to unicast questions need to have (unicastQuestion != nil)
9341 }
9342 else
9343 {
9344 // Accept all remaining records in this unicast response to an mDNS query.
9345 recordAcceptedInResponse = mDNStrue;
9346 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9347 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME " (" PUB_S ")",
9348 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype));
9349 }
9350 }
9351 else
9352 {
9353 // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9354 // the question. The code below does that. So, make this record unacceptable for now
9355 if (!InterfaceID)
9356 {
9357 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9358 AcceptableResponse = mDNSfalse;
9359 }
9360 }
9361 }
9362 }
9363 else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9364 {
9365 // There are some routers (rare, thankfully) that generate bogus ARP responses for
9366 // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9367 // To work with these broken routers, client devices need to blacklist these broken
9368 // routers and ignore their bogus ARP responses. Some devices implement a technique
9369 // such as the one described in US Patent 7436783, which lets clients detect and
9370 // ignore these broken routers: <https://www.google.com/patents/US7436783>
9371
9372 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9373 // approach of just detecting these broken routers and completely disabling IPv4
9374 // link-local communication on interfaces where a broken router is detected.
9375 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9376 // that are deemed “safe” for IPv4 link-local communication;
9377 // the flag is cleared on interfaces where a broken router is detected.
9378
9379 // OS X and iOS will not even try to communicate with an IPv4
9380 // link-local destination on an interface without the IFEF_ARPLL flag set.
9381 // This can cause some badly written applications to freeze for a long time if they
9382 // attempt to connect to an IPv4 link-local destination address and then wait for
9383 // that connection attempt to time out before trying other candidate addresses.
9384
9385 // To mask this client bug, we suppress acceptance of IPv4 link-local address
9386 // records on interfaces where we know the OS will be unwilling even to attempt
9387 // communication with those IPv4 link-local destination addresses.
9388 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9389
9390 const CacheRecord *const rr = &m->rec.r;
9391 const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9392 if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9393 {
9394 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9395 mDNSCoreResetRecord(m);
9396 continue;
9397 }
9398 }
9399
9400 // 1. Check that this packet resource record does not conflict with any of ours
9401 if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9402 {
9403 if (m->CurrentRecord)
9404 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9405 m->CurrentRecord = m->ResourceRecords;
9406 while (m->CurrentRecord)
9407 {
9408 AuthRecord *rr = m->CurrentRecord;
9409 m->CurrentRecord = rr->next;
9410 // We accept all multicast responses, and unicast responses resulting from queries we issued
9411 // For other unicast responses, this code accepts them only for responses with an
9412 // (apparently) local source address that pertain to a record of our own that's in probing state
9413 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9414
9415 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match...
9416 {
9417 // ... check to see if type and rdata are identical
9418 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9419 {
9420 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9421 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9422 {
9423 // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9424 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9425 }
9426 else
9427 {
9428 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; }
9429 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9430 }
9431 }
9432 // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9433 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9434 {
9435 LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9436 m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r), IIDPrintable(InterfaceID));
9437 LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9438
9439 // If this record is marked DependentOn another record for conflict detection purposes,
9440 // then *that* record has to be bumped back to probing state to resolve the conflict
9441 if (rr->DependentOn)
9442 {
9443 while (rr->DependentOn) rr = rr->DependentOn;
9444 LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9445 }
9446
9447 // If we've just whacked this record's ProbeCount, don't need to do it again
9448 if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9449 LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9450 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9451 LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9452 else
9453 {
9454 LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9455 // If we'd previously verified this record, put it back to probing state and try again
9456 if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9457 {
9458 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9459 rr->resrec.RecordType = kDNSRecordTypeUnique;
9460 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9461 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9462 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9463 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9464 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1;
9465 rr->AnnounceCount = InitialAnnounceCount;
9466 InitializeLastAPTime(m, rr);
9467 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate
9468 }
9469 // If we're probing for this record, we just failed
9470 else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9471 {
9472 // At this point in the code, we're probing for uniqueness.
9473 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9474 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9475 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9476 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9477 {
9478 if ((rr->ProbingConflictCount == 0) || (m->MPktNum != rr->LastConflictPktNum))
9479 {
9480 const NetworkInterfaceInfo *const intf = FirstInterfaceForID(m, InterfaceID);
9481 rr->ProbingConflictCount++;
9482 rr->LastConflictPktNum = m->MPktNum;
9483 if (ResponseMCast && (!intf || intf->SupportsUnicastMDNSResponse) &&
9484 (rr->ProbingConflictCount <= kMaxAllowedMCastProbingConflicts))
9485 {
9486 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9487 "spurious multicast conflict (%d/%d) via interface %d for %s",
9488 rr->ProbeCount, kProbingConflictPauseDuration, rr->ProbingConflictCount,
9489 kMaxAllowedMCastProbingConflicts, IIDPrintable(InterfaceID), ARDisplayString(m, rr));
9490 rr->ProbeCount = DefaultProbeCountForTypeUnique;
9491 rr->LastAPTime = m->timenow + kProbingConflictPauseDuration - rr->ThisAPInterval;
9492 SetNextAnnounceProbeTime(m, rr);
9493 }
9494 else
9495 {
9496 LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9497 rr->ProbeCount, ARDisplayString(m, rr), ResponseMCast ? "multi" : "uni", IIDPrintable(InterfaceID));
9498 m->mDNSStats.NameConflicts++;
9499 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9500 // See if this record was also registered with any D2D plugins.
9501 D2D_stop_advertising_record(rr);
9502 #endif
9503 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9504 }
9505 }
9506 }
9507 }
9508 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9509 // same machine giving different answers for the reverse mapping record, or there are two machines on the
9510 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9511 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9512 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9513 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9514 {
9515 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9516 m->mDNSStats.KnownUniqueNameConflicts++;
9517 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9518 D2D_stop_advertising_record(rr);
9519 #endif
9520 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9521 }
9522 else
9523 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9524 }
9525 }
9526 // Else, matching signature, different type or rdata, but not a considered a conflict.
9527 // If the packet record has the cache-flush bit set, then we check to see if we
9528 // have any record(s) of the same type that we should re-assert to rescue them
9529 // (see note about "multi-homing and bridged networks" at the end of this function).
9530 else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
9531 if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2)
9532 { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9533 }
9534 }
9535 }
9536
9537 nseclist = mDNSfalse;
9538 if (!AcceptableResponse)
9539 {
9540 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords, unicastQuestion, &nseclist);
9541 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9542 }
9543
9544 // 2. See if we want to add this packet resource record to our cache
9545 // We only try to cache answers if we have a cache to put them in
9546 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9547 if (!AcceptableResponse) {
9548 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S,
9549 mDNSVal16(response->h.id), CRDisplayString(m, &m->rec.r));
9550 }
9551 if (m->rrcache_size && AcceptableResponse)
9552 {
9553 const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash);
9554 CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec);
9555 CacheRecord *rr = mDNSNULL;
9556
9557 // 2a. Check if this packet resource record is already in our cache.
9558 //
9559 // If this record should go in the nseclist, don't look in the cache for updating it.
9560 // They are supposed to be cached under the "nsec" field of the cache record for
9561 // validation. Just create the cache record.
9562 if (!nseclist)
9563 {
9564 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, unicastQuestion, &cfp, &NSECCachePtr, InterfaceID);
9565 }
9566
9567 // If packet resource record not in our cache, add it now
9568 // (unless it is just a deletion of a record we never had, in which case we don't care)
9569 if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9570 {
9571 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9572 mDNSs32 delay;
9573
9574 if (AddToCFList)
9575 delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9576 else
9577 delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash);
9578
9579 // If unique, assume we may have to delay delivery of this 'add' event.
9580 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9581 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9582 // to schedule an mDNS_Execute task at the appropriate time.
9583 rr = CreateNewCacheEntry(m, slot, cg, delay, !nseclist, srcaddr);
9584 if (rr)
9585 {
9586 rr->responseFlags = response->h.flags;
9587 // If we are not creating signatures, then we need to inform DNSSEC so that
9588 // it does not wait forever. Don't do this if we got NSEC records
9589 // as it indicates that this name does not exist.
9590 if (rr->resrec.rrtype == kDNSType_RRSIG && !nseclist)
9591 {
9592 rrsigsCreated = mDNStrue;
9593 }
9594 // Remember whether we created a cache record in response to a DNSSEC question.
9595 // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9596 rr->CRDNSSECQuestion = 0;
9597 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9598 {
9599 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9600 "[R%d->Q%d] mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record " PRI_S ", question " PRI_DM_NAME " (" PUB_S ")",
9601 unicastQuestion->request_id, mDNSVal16(unicastQuestion->TargetQID), CRDisplayString(m, rr),
9602 DM_NAME_PARAM(unicastQuestion->qname.c), DNSTypeName(unicastQuestion->qtype));
9603 rr->CRDNSSECQuestion = 1;
9604 }
9605 // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9606 // which we should be creating below. It is also needed in the wildcard
9607 // expanded answer case and in that case it is cached along with the answer.
9608 if (nseclist)
9609 {
9610 rr->TimeRcvd = m->timenow;
9611 *nsecp = rr;
9612 nsecp = &rr->next;
9613 }
9614 else if (AddToCFList)
9615 {
9616 *cfp = rr;
9617 cfp = &rr->NextInCFList;
9618 *cfp = (CacheRecord*)1;
9619 }
9620 else if (rr->DelayDelivery)
9621 {
9622 ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9623 }
9624 }
9625 }
9626 }
9627 mDNSCoreResetRecord(m);
9628 }
9629
9630 exit:
9631 mDNSCoreResetRecord(m);
9632
9633 // If we've just received one or more records with their cache flush bits set,
9634 // then scan that cache slot to see if there are any old stale records we need to flush
9635 while (CacheFlushRecords != (CacheRecord*)1)
9636 {
9637 CacheRecord *r1 = CacheFlushRecords, *r2;
9638 const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash);
9639 const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec);
9640 mDNSBool purgedRecords = mDNSfalse;
9641 CacheFlushRecords = CacheFlushRecords->NextInCFList;
9642 r1->NextInCFList = mDNSNULL;
9643
9644 // Look for records in the cache with the same signature as this new one with the cache flush
9645 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9646 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9647 // We make these TTL adjustments *only* for records that still have *more* than one second
9648 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9649 // (and now has half a second remaining) could inadvertently get its life extended, by either
9650 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9651 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9652 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9653 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9654 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9655 // To avoid this, we need to ensure that the cache flushing operation will only act to
9656 // *decrease* a record's remaining lifetime, never *increase* it.
9657 for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9658 {
9659 mDNSu16 id1;
9660 mDNSu16 id2;
9661 if (!r1->resrec.InterfaceID)
9662 {
9663 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9664 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9665 }
9666 else
9667 {
9668 id1 = id2 = 0;
9669 }
9670 // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9671 // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9672 // the new RRSIG that we received. Process only if the typeCovered matches.
9673 if ((r1->resrec.rrtype == r2->resrec.rrtype) && (r1->resrec.rrtype == kDNSType_RRSIG))
9674 {
9675 rdataRRSig *rrsig1 = (rdataRRSig *)(((RDataBody2 *)(r1->resrec.rdata->u.data))->data);
9676 rdataRRSig *rrsig2 = (rdataRRSig *)(((RDataBody2 *)(r2->resrec.rdata->u.data))->data);
9677 if (swap16(rrsig1->typeCovered) != swap16(rrsig2->typeCovered))
9678 {
9679 debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9680 DNSTypeName(swap16(rrsig1->typeCovered)), DNSTypeName(swap16(rrsig2->typeCovered)));
9681 continue;
9682 }
9683 }
9684
9685 // For Unicast (null InterfaceID) the resolver IDs should also match
9686 if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9687 (r1->resrec.InterfaceID || (id1 == id2)) &&
9688 r1->resrec.rrtype == r2->resrec.rrtype &&
9689 r1->resrec.rrclass == r2->resrec.rrclass)
9690 {
9691 if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal)
9692 {
9693 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2);
9694 r1->resrec.mortality = Mortality_Immortal; // Immortalize the replacement record
9695 }
9696
9697 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9698 // else, if record is old, mark it to be flushed
9699 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9700 {
9701 // If we find mismatched TTLs in an RRSet, correct them.
9702 // We only do this for records with a TTL of 2 or higher. It's possible to have a
9703 // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9704 // which we treat as a goodbye followed by an addition) and in that case it would be
9705 // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9706
9707 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9708 // because certain early Bonjour devices are known to have this specific mismatch, and
9709 // there's no point filling syslog with messages about something we already know about.
9710 // We also don't log this for uDNS responses, since a caching name server is obliged
9711 // to give us an aged TTL to correct for how long it has held the record,
9712 // so our received TTLs are expected to vary in that case
9713
9714 // We also suppress log message in the case of SRV records that are received
9715 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9716 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9717 // GM builds.
9718 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9719 {
9720 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9721 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9722 mDNSOpaque16IsZero(response->h.id))
9723 LogInfo("Correcting TTL from %4d to %4d for %s",
9724 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9725 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9726 }
9727 r2->TimeRcvd = m->timenow;
9728 SetNextCacheCheckTimeForRecord(m, r2);
9729 }
9730 else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed
9731 {
9732 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9733 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9734 // We set stale records to expire in one second.
9735 // This gives the owner a chance to rescue it if necessary.
9736 // This is important in the case of multi-homing and bridged networks:
9737 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9738 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9739 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9740 // will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9741 // By delaying the deletion by one second, we give X a change to notice that this bridging has
9742 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9743
9744 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9745 // final expiration queries for this record.
9746
9747 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9748 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9749 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9750 // <rdar://problem/5636422> Updating TXT records is too slow
9751 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9752 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9753 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9754 {
9755 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9756 r2->resrec.rroriginalttl = 0;
9757 }
9758 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9759 {
9760 // We only set a record to expire in one second if it currently has *more* than a second to live
9761 // If it's already due to expire in a second or less, we just leave it alone
9762 r2->resrec.rroriginalttl = 1;
9763 r2->UnansweredQueries = MaxUnansweredQueries;
9764 r2->TimeRcvd = m->timenow - 1;
9765 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9766 // that we marked for deletion via an explicit DE record
9767 }
9768 SetNextCacheCheckTimeForRecord(m, r2);
9769 }
9770 else
9771 {
9772 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9773 if (r2->resrec.mortality == Mortality_Ghost)
9774 {
9775 DNSQuestion * q;
9776 for (q = m->Questions; q; q=q->next)
9777 {
9778 if (!q->LongLived && ActiveQuestion(q) &&
9779 CacheRecordAnswersQuestion(r2, q) &&
9780 q->metrics.expiredAnswerState == ExpiredAnswer_AnsweredWithExpired)
9781 {
9782 q->metrics.expiredAnswerState = ExpiredAnswer_ExpiredAnswerChanged;
9783 }
9784 }
9785 }
9786 #endif
9787 // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9788 r2->resrec.mortality = Mortality_Mortal; // We want it purged, so remove any immortality
9789 mDNS_PurgeCacheResourceRecord(m, r2);
9790 purgedRecords = mDNStrue;
9791 }
9792 }
9793 }
9794
9795 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to
9796 {
9797 // If we had a unicast question for this response with at least one positive answer and we
9798 // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9799 // signatures along with the cache record which will be used for validation later. If
9800 // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9801 // use that instead.
9802 if (response->h.numAnswers && unicastQuestion && NSECRecords)
9803 {
9804 if (!NSECCachePtr)
9805 {
9806 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9807 "[R%d->Q%d] mDNSCoreReceiveResponse: Updating NSECCachePtr to " PRI_S,
9808 unicastQuestion->request_id, mDNSVal16(unicastQuestion->TargetQID), CRDisplayString(m, r1));
9809 NSECCachePtr = r1;
9810 }
9811 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9812 // might start the verification process which needs these NSEC records
9813 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9814 {
9815 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9816 FreeNSECRecords(m, NSECRecords);
9817 }
9818 NSECRecords = mDNSNULL;
9819 NSECCachePtr = mDNSNULL;
9820 }
9821 if (r1->resrec.InterfaceID)
9822 {
9823 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash);
9824 }
9825 else
9826 {
9827 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9828 // them to be deleted before any ADD events for this record.
9829 r1->DelayDelivery = purgedRecords ? NonZeroTime(m->timenow) : 0;
9830 }
9831 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9832 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9833 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9834 }
9835 }
9836
9837 // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9838 // update them now for future validations.
9839 if (NSECRecords && NSECCachePtr)
9840 {
9841 LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m, NSECCachePtr));
9842 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9843 {
9844 LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9845 FreeNSECRecords(m, NSECRecords);
9846 }
9847 NSECRecords = mDNSNULL;
9848 NSECCachePtr = mDNSNULL;
9849 }
9850
9851 // If there is at least one answer and we did not create RRSIGs and there was a
9852 // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9853 // were created. We don't need to give a hint:
9854 //
9855 // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9856 // generate a negative response
9857 //
9858 // - if we have NSECRecords, it means we might have a potential proof for
9859 // non-existence of name that we are looking for
9860 //
9861 if (response->h.numAnswers && !rrsigsCreated && DNSSECQuestion && !NSECRecords)
9862 mDNSCoreReceiveNoDNSSECAnswers(m, response, end, dstaddr, dstport, InterfaceID);
9863
9864 // See if we need to generate negative cache entries for unanswered unicast questions
9865 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, LLQType, rcode, NSECRecords);
9866
9867 if (McastNSEC3Records)
9868 {
9869 debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9870 FreeNSECRecords(m, McastNSEC3Records);
9871 }
9872 }
9873
9874 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9875 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9876 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9877 // that warrants waking the sleeping host.
9878 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9879
9880 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9881 {
9882 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9883 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9884 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9885 // simple, we use the same mechanism for both lists.
9886 if (!e->l[0])
9887 {
9888 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9889 return;
9890 }
9891 m->CurrentRecord = thelist;
9892 while (m->CurrentRecord)
9893 {
9894 AuthRecord *const rr = m->CurrentRecord;
9895 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9896 {
9897 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9898 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9899 }
9900 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9901 m->CurrentRecord = rr->next;
9902 }
9903 }
9904
9905 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9906 {
9907 if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9908 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9909 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9910 }
9911
9912 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9913 {
9914 if (result && result != mStatus_MemFree)
9915 LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9916
9917 if (result == mStatus_NameConflict)
9918 {
9919 mDNS_Lock(m);
9920 LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9921 if (ar->WakeUp.HMAC.l[0])
9922 {
9923 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse); // Send one wakeup magic packet
9924 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken
9925 }
9926 mDNS_Unlock(m);
9927 }
9928
9929 if (result == mStatus_NameConflict || result == mStatus_MemFree)
9930 {
9931 m->ProxyRecords--;
9932 mDNSPlatformMemFree(ar);
9933 mDNS_UpdateAllowSleep(m);
9934 }
9935 }
9936
9937 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9938 {
9939 int i;
9940 mDNSs8 hval = 0;
9941 int colons = 0;
9942 mDNSu8 val = 0;
9943
9944 for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9945 {
9946 hval = HexVal(*ptr);
9947 if (hval != -1)
9948 {
9949 val <<= 4;
9950 val |= hval;
9951 }
9952 else if (*ptr == ':')
9953 {
9954 if (colons >=5)
9955 {
9956 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9957 return mDNSNULL;
9958 }
9959 eth->b[colons] = val;
9960 colons++;
9961 val = 0;
9962 }
9963 }
9964 if (colons != 5)
9965 {
9966 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9967 return mDNSNULL;
9968 }
9969 eth->b[colons] = val;
9970 return ptr;
9971 }
9972
9973 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9974 {
9975 int hval;
9976 int value;
9977 int numBytes;
9978 int digitsProcessed;
9979 int zeroFillStart;
9980 int numColons;
9981 mDNSu8 v6addr[16];
9982
9983 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9984 // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9985 //
9986 // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9987 // the result in "v6"
9988
9989 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9990 while (ptr < limit && *ptr != ' ')
9991 {
9992 hval = HexVal(*ptr);
9993 if (hval != -1)
9994 {
9995 value <<= 4;
9996 value |= hval;
9997 digitsProcessed = 1;
9998 }
9999 else if (*ptr == ':')
10000 {
10001 if (!digitsProcessed)
10002 {
10003 // If we have already seen a "::", we should not see one more. Handle the special
10004 // case of "::"
10005 if (numColons)
10006 {
10007 // if we never filled any bytes and the next character is space (we have reached the end)
10008 // we are done
10009 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
10010 {
10011 mDNSPlatformMemZero(v6->b, 16);
10012 return ptr + 1;
10013 }
10014 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
10015 return mDNSNULL;
10016 }
10017
10018 // We processed "::". We need to fill zeroes later. For now, mark the
10019 // point where we will start filling zeroes from.
10020 zeroFillStart = numBytes;
10021 numColons++;
10022 }
10023 else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
10024 {
10025 // We have a trailing ":" i.e., no more characters after ":"
10026 LogMsg("GetValueForIPv6Addr: Trailing colon");
10027 return mDNSNULL;
10028 }
10029 else
10030 {
10031 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
10032 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
10033 // filled here is 12 and 13.
10034 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
10035
10036 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
10037 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
10038 digitsProcessed = value = 0;
10039
10040 // Make sure that we did not fill the 13th and 14th byte above
10041 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
10042 }
10043 }
10044 ptr++;
10045 }
10046
10047 // We should be processing the last set of bytes following the last ":" here
10048 if (!digitsProcessed)
10049 {
10050 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
10051 return mDNSNULL;
10052 }
10053
10054 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
10055 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
10056 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
10057
10058 if (zeroFillStart)
10059 {
10060 int i, j, n;
10061 for (i = 0; i < zeroFillStart; i++)
10062 v6->b[i] = v6addr[i];
10063 for (j = i, n = 0; n < 16 - numBytes; j++, n++)
10064 v6->b[j] = 0;
10065 for (; j < 16; i++, j++)
10066 v6->b[j] = v6addr[i];
10067 }
10068 else if (numBytes == 16)
10069 mDNSPlatformMemCopy(v6->b, v6addr, 16);
10070 else
10071 {
10072 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
10073 return mDNSNULL;
10074 }
10075 return ptr;
10076 }
10077
10078 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
10079 {
10080 mDNSu32 val;
10081 int dots = 0;
10082 val = 0;
10083
10084 for ( ; ptr < limit && *ptr != ' '; ptr++)
10085 {
10086 if (*ptr >= '0' && *ptr <= '9')
10087 val = val * 10 + *ptr - '0';
10088 else if (*ptr == '.')
10089 {
10090 if (val > 255 || dots >= 3)
10091 {
10092 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
10093 return mDNSNULL;
10094 }
10095 v4->b[dots++] = val;
10096 val = 0;
10097 }
10098 else
10099 {
10100 // We have a zero at the end and if we reached that, then we are done.
10101 if (*ptr == 0 && ptr == limit - 1 && dots == 3)
10102 {
10103 v4->b[dots] = val;
10104 return ptr + 1;
10105 }
10106 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
10107 }
10108 }
10109 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
10110 v4->b[dots] = val;
10111 return ptr;
10112 }
10113
10114 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
10115 {
10116 mDNSu32 val;
10117
10118 val = 0;
10119 for ( ; ptr < limit && *ptr != ' '; ptr++)
10120 {
10121 if (*ptr < '0' || *ptr > '9')
10122 {
10123 // We have a zero at the end and if we reached that, then we are done.
10124 if (*ptr == 0 && ptr == limit - 1)
10125 {
10126 *value = val;
10127 return ptr + 1;
10128 }
10129 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
10130 }
10131 val = val * 10 + *ptr - '0';
10132 }
10133 *value = val;
10134 return ptr;
10135 }
10136
10137 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
10138 {
10139 mDNSAddr laddr, raddr;
10140 mDNSEthAddr eth;
10141 mDNSIPPort lport, rport;
10142 mDNSu32 timeout, seq, ack;
10143 mDNSu16 win;
10144
10145 if (!mDNS_KeepaliveRecord(&rr->resrec))
10146 {
10147 return mDNSfalse;
10148 }
10149
10150 timeout = seq = ack = 0;
10151 win = 0;
10152 laddr = raddr = zeroAddr;
10153 lport = rport = zeroIPPort;
10154 eth = zeroEthAddr;
10155
10156 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10157
10158 if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
10159 mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
10160 mDNSEthAddressIsZero(eth))
10161 {
10162 return mDNSfalse;
10163 }
10164
10165 return mDNStrue;
10166 }
10167
10168
10169 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
10170 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
10171 {
10172 if (ar->resrec.rrtype != kDNSType_NULL)
10173 return;
10174
10175 if (mDNS_KeepaliveRecord(&ar->resrec))
10176 {
10177 int len = ar->resrec.rdlength;
10178 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
10179 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
10180 mDNSu32 value = 0;
10181
10182 while (ptr < limit)
10183 {
10184 mDNSu8 param = *ptr;
10185 ptr += 2; // Skip the letter and the "="
10186 if (param == 'h')
10187 {
10188 laddr->type = mDNSAddrType_IPv4;
10189 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
10190 }
10191 else if (param == 'd')
10192 {
10193 raddr->type = mDNSAddrType_IPv4;
10194 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
10195 }
10196 else if (param == 'H')
10197 {
10198 laddr->type = mDNSAddrType_IPv6;
10199 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
10200 }
10201 else if (param == 'D')
10202 {
10203 raddr->type = mDNSAddrType_IPv6;
10204 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
10205 }
10206 else if (param == 'm')
10207 {
10208 ptr = GetValueForMACAddr(ptr, limit, eth);
10209 }
10210 else
10211 {
10212 ptr = GetValueForKeepalive(ptr, limit, &value);
10213 }
10214 if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10215
10216 // Extract everything in network order so that it is easy for sending a keepalive and also
10217 // for matching incoming TCP packets
10218 switch (param)
10219 {
10220 case 't':
10221 *timeout = value;
10222 //if (*timeout < 120) *timeout = 120;
10223 break;
10224 case 'h':
10225 case 'H':
10226 case 'd':
10227 case 'D':
10228 case 'm':
10229 case 'i':
10230 case 'c':
10231 break;
10232 case 'l':
10233 lport->NotAnInteger = swap16((mDNSu16)value);
10234 break;
10235 case 'r':
10236 rport->NotAnInteger = swap16((mDNSu16)value);
10237 break;
10238 case 's':
10239 *seq = swap32(value);
10240 break;
10241 case 'a':
10242 *ack = swap32(value);
10243 break;
10244 case 'w':
10245 *win = swap16((mDNSu16)value);
10246 break;
10247 default:
10248 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
10249 ptr = limit;
10250 break;
10251 }
10252 ptr++; // skip the space
10253 }
10254 }
10255 }
10256
10257 // Matches the proxied auth records to the incoming TCP packet and returns the match and its sequence and ack in "rseq" and "rack" so that
10258 // the clients need not retrieve this information from the auth record again.
10259 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
10260 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
10261 {
10262 AuthRecord *ar;
10263 mDNSAddr laddr, raddr;
10264 mDNSEthAddr eth;
10265 mDNSIPPort lport, rport;
10266 mDNSu32 timeout, seq, ack;
10267 mDNSu16 win;
10268
10269 for (ar = m->ResourceRecords; ar; ar=ar->next)
10270 {
10271 timeout = seq = ack = 0;
10272 win = 0;
10273 laddr = raddr = zeroAddr;
10274 lport = rport = zeroIPPort;
10275
10276 if (!ar->WakeUp.HMAC.l[0]) continue;
10277
10278 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10279
10280 // Did we parse correctly ?
10281 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10282 {
10283 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
10284 continue;
10285 }
10286
10287 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10288 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
10289
10290 // Does it match the incoming TCP packet ?
10291 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
10292 {
10293 // returning in network order
10294 *rseq = seq;
10295 *rack = ack;
10296 return ar;
10297 }
10298 }
10299 return mDNSNULL;
10300 }
10301
10302 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
10303 {
10304 AuthRecord *ar;
10305
10306 for (ar = m->ResourceRecords; ar; ar=ar->next)
10307 {
10308 mDNSu32 timeout, seq, ack;
10309 mDNSu16 win;
10310 mDNSAddr laddr, raddr;
10311 mDNSEthAddr eth;
10312 mDNSIPPort lport, rport;
10313
10314 timeout = seq = ack = 0;
10315 win = 0;
10316
10317 laddr = raddr = zeroAddr;
10318 lport = rport = zeroIPPort;
10319
10320 if (!ar->WakeUp.HMAC.l[0]) continue;
10321
10322 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10323
10324 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10325 {
10326 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
10327 continue;
10328 }
10329 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10330
10331 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10332 // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10333 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
10334 {
10335 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10336 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
10337 }
10338 if (m->NextScheduledKA - ar->KATimeExpire > 0)
10339 m->NextScheduledKA = ar->KATimeExpire;
10340 }
10341 }
10342
10343 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
10344 {
10345 mDNSu32 timeout, seq, ack, seqInc;
10346 mDNSu16 win;
10347 mDNSAddr laddr, raddr;
10348 mDNSEthAddr eth;
10349 mDNSIPPort lport, rport;
10350 mDNSu8 *ptr;
10351
10352 if (ar == mDNSNULL)
10353 {
10354 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10355 return;
10356 }
10357
10358 timeout = seq = ack = 0;
10359 win = 0;
10360
10361 laddr = raddr = zeroAddr;
10362 lport = rport = zeroIPPort;
10363
10364 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10365
10366 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10367 {
10368 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
10369 return;
10370 }
10371
10372 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10373 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10374 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10375 // it's converted to host byte order before incrementing it by one.
10376 ptr = (mDNSu8 *)&seq;
10377 seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
10378 ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
10379 ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
10380 ptr[2] = (mDNSu8)((seqInc >> 8) & 0xFF);
10381 ptr[3] = (mDNSu8)((seqInc ) & 0xFF);
10382 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10383 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10384 }
10385
10386 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
10387 const DNSMessage *const msg, const mDNSu8 *end,
10388 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
10389 const mDNSInterfaceID InterfaceID)
10390 {
10391 int i;
10392 AuthRecord opt;
10393 mDNSu8 *p = m->omsg.data;
10394 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option
10395 mDNSu32 updatelease = 0;
10396 const mDNSu8 *ptr;
10397
10398 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10399 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10400 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
10401 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,",
10402 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,",
10403 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,",
10404 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data);
10405
10406 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
10407
10408 if (mDNS_PacketLoggingEnabled)
10409 DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10410
10411 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
10412 if (ptr)
10413 {
10414 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10415 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10416 {
10417 const rdataOPT *o;
10418 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10419 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10420 {
10421 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10422 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner;
10423 }
10424 }
10425 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10426 }
10427
10428 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10429
10430 if (!updatelease || !owner.HMAC.l[0])
10431 {
10432 static int msgs = 0;
10433 if (msgs < 100)
10434 {
10435 msgs++;
10436 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10437 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10438 }
10439 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10440 }
10441 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10442 {
10443 static int msgs = 0;
10444 if (msgs < 100)
10445 {
10446 msgs++;
10447 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10448 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10449 }
10450 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10451 }
10452 else
10453 {
10454 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10455
10456 if (updatelease > 24 * 60 * 60)
10457 updatelease = 24 * 60 * 60;
10458
10459 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10460 updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10461
10462 ptr = LocateAuthorities(msg, end);
10463
10464 // Clear any stale TCP keepalive records that may exist
10465 ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10466 ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10467
10468 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10469 {
10470 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10471 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10472 {
10473 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10474 AuthRecord *ar = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10475 if (!ar)
10476 {
10477 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10478 break;
10479 }
10480 else
10481 {
10482 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10483 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10484 // All stale keepalive records have been flushed prior to this loop.
10485 if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10486 {
10487 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10488 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10489 }
10490 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10491 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10492 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10493 ar->resrec.rdata->MaxRDLength = RDLengthMem;
10494 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10495 ar->ForceMCast = mDNStrue;
10496 ar->WakeUp = owner;
10497 if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10498 {
10499 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10500 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10501 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10502 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10503 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10504 }
10505 ar->TimeRcvd = m->timenow;
10506 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10507 if (m->NextScheduledSPS - ar->TimeExpire > 0)
10508 m->NextScheduledSPS = ar->TimeExpire;
10509 ar->KATimeExpire = 0;
10510 mDNS_Register_internal(m, ar);
10511
10512 m->ProxyRecords++;
10513 mDNS_UpdateAllowSleep(m);
10514 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10515 }
10516 }
10517 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
10518 }
10519
10520 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10521 {
10522 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10523 ClearProxyRecords(m, &owner, m->DuplicateRecords);
10524 ClearProxyRecords(m, &owner, m->ResourceRecords);
10525 }
10526 else
10527 {
10528 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10529 opt.resrec.rrclass = NormalMaxDNSMessageData;
10530 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record
10531 opt.resrec.rdestimate = sizeof(rdataOPT);
10532 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease;
10533 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10534 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10535 }
10536 }
10537
10538 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, mDNSNULL, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSfalse);
10539 mDNS_SendKeepalives(m);
10540 }
10541
10542 mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg)
10543 {
10544 mDNSu8 *ptr = msg->data;
10545 mDNSu8 *end = mDNSNULL;
10546 mDNSu32 length = 0;
10547 AuthRecord opt;
10548 NetworkInterfaceInfo *intf;
10549
10550 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10551 opt.resrec.rrclass = NormalMaxDNSMessageData;
10552 opt.resrec.rdlength = sizeof(rdataOPT);
10553 opt.resrec.rdestimate = sizeof(rdataOPT);
10554
10555 intf = FirstInterfaceForID(m, InterfaceID);
10556 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
10557
10558 LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt));
10559 end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec);
10560 if (end != mDNSNULL)
10561 {
10562 // Put all the integer values in IETF byte-order (MSB first, LSB second)
10563 SwapDNSHeaderBytes(msg);
10564 length = (end - msg->data);
10565 }
10566 else
10567 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10568
10569 return length;
10570 }
10571
10572 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10573 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10574 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10575 // Really, both should be unified and handled in one place.
10576 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10577 {
10578 if (InterfaceID)
10579 {
10580 mDNSu32 pktlease = 0, spsupdates = 0;
10581 const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease);
10582 const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour
10583 if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10584
10585 if (m->CurrentRecord)
10586 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10587 m->CurrentRecord = m->ResourceRecords;
10588 while (m->CurrentRecord)
10589 {
10590 AuthRecord *const rr = m->CurrentRecord;
10591 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10592 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10593 {
10594 // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10595 // Clear the updateid when we are done sending on all interfaces.
10596 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10597 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10598 bit_clr_opaque64(rr->updateIntID, scopeid);
10599 if (mDNSOpaque64IsZero(&rr->updateIntID))
10600 rr->updateid = zeroID;
10601 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10602 spsupdates++;
10603 LogSPS("Sleep Proxy %s record %2d %5d 0x%x 0x%x (%d) %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", spsupdates, updatelease, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr));
10604 if (rr->WakeUp.HMAC.l[0])
10605 {
10606 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10607 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10608 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10609 }
10610 }
10611 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10612 // new records could have been added to the end of the list as a result of that call.
10613 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10614 m->CurrentRecord = rr->next;
10615 }
10616 if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10617 {
10618 char *ifname;
10619 mDNSAddr spsaddr;
10620 DNSMessage optMsg;
10621 int length;
10622 // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10623 ifname = InterfaceNameForID(m, InterfaceID);
10624 mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10625 mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10626
10627 // Store the Owner OPT record for this interface.
10628 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10629 InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags);
10630 length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg);
10631 if (length != 0)
10632 {
10633 length += sizeof(DNSMessageHeader);
10634 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length);
10635 }
10636 }
10637 }
10638 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10639 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10640 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10641 }
10642
10643 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
10644 const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
10645 {
10646 if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10647 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10648
10649 // Create empty resource record
10650 cr->resrec.RecordType = kDNSRecordTypePacketNegative;
10651 cr->resrec.InterfaceID = InterfaceID;
10652 cr->resrec.rDNSServer = dnsserver;
10653 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry
10654 cr->resrec.rrtype = rrtype;
10655 cr->resrec.rrclass = rrclass;
10656 cr->resrec.rroriginalttl = ttl_seconds;
10657 cr->resrec.rdlength = 0;
10658 cr->resrec.rdestimate = 0;
10659 cr->resrec.namehash = namehash;
10660 cr->resrec.rdatahash = 0;
10661 cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10662 cr->resrec.rdata->MaxRDLength = 0;
10663
10664 cr->NextInKAList = mDNSNULL;
10665 cr->TimeRcvd = m->timenow;
10666 cr->DelayDelivery = 0;
10667 cr->NextRequiredQuery = m->timenow;
10668 cr->CRActiveQuestion = mDNSNULL;
10669 cr->UnansweredQueries = 0;
10670 cr->LastUnansweredTime = 0;
10671 cr->NextInCFList = mDNSNULL;
10672 cr->nsec = mDNSNULL;
10673 cr->soa = mDNSNULL;
10674 cr->CRDNSSECQuestion = 0;
10675 // Initialize to the basic one and the caller can set it to more
10676 // specific based on the response if any
10677 cr->responseFlags = ResponseFlags;
10678 }
10679
10680 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10681 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10682 const mDNSInterfaceID InterfaceID)
10683 {
10684 mDNSInterfaceID ifid = InterfaceID;
10685 const mDNSu8 *const pkt = (mDNSu8 *)msg;
10686 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery;
10687 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10688 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update;
10689 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10690 mDNSu8 QR_OP;
10691 mDNSu8 *ptr = mDNSNULL;
10692 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10693 if (TLS) dstaddr = mDNSNULL;
10694
10695 #ifndef UNICAST_DISABLED
10696 if (mDNSSameAddress(srcaddr, &m->Router))
10697 {
10698 #ifdef _LEGACY_NAT_TRAVERSAL_
10699 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10700 {
10701 mDNS_Lock(m);
10702 LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10703 mDNS_Unlock(m);
10704 return;
10705 }
10706 #endif
10707 if (mDNSSameIPPort(srcport, NATPMPPort))
10708 {
10709 mDNS_Lock(m);
10710 uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10711 mDNS_Unlock(m);
10712 return;
10713 }
10714 }
10715 #ifdef _LEGACY_NAT_TRAVERSAL_
10716 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10717 #endif
10718
10719 #endif
10720 if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader))
10721 {
10722 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt));
10723 return;
10724 }
10725 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10726 // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10727 ptr = (mDNSu8 *)&msg->h.numQuestions;
10728 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10729 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10730 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10731 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10732
10733 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10734
10735 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10736 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10737 if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10738
10739 mDNS_Lock(m);
10740 m->PktNum++;
10741 if (mDNSOpaque16IsZero(msg->h.id))
10742 {
10743 m->MPktNum++;
10744 #if APPLE_OSX_mDNSResponder
10745 // Track the number of multicast packets received from a source outside our subnet.
10746 // Check the destination address to avoid accounting for spurious packets that
10747 // comes in with message id zero.
10748 if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr &&
10749 mDNSAddressIsAllDNSLinkGroup(dstaddr))
10750 {
10751 m->RemoteSubnet++;
10752 }
10753 #endif // #if APPLE_OSX_mDNSResponder
10754 }
10755
10756 #ifndef UNICAST_DISABLED
10757 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10758 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10759 {
10760 ifid = mDNSInterface_Any;
10761 if (mDNS_PacketLoggingEnabled)
10762 DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10763 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10764 // Note: mDNSCore also needs to get access to received unicast responses
10765 }
10766 #endif
10767 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10768 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10769 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10770 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID);
10771 else
10772 {
10773 if (mDNS_LoggingEnabled)
10774 {
10775 static int msgCount = 0;
10776 if (msgCount < 1000) {
10777 int i = 0;
10778 msgCount++;
10779 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10780 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID);
10781 while (i < (int)(end - pkt))
10782 {
10783 char buffer[128];
10784 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10785 do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15);
10786 LogInfo("%s", buffer);
10787 }
10788 }
10789 }
10790 }
10791 // Packet reception often causes a change to the task list:
10792 // 1. Inbound queries can cause us to need to send responses
10793 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10794 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10795 // 4. Response packets that answer questions may cause our client to issue new questions
10796 mDNS_Unlock(m);
10797 }
10798
10799 // ***************************************************************************
10800 #if COMPILER_LIKES_PRAGMA_MARK
10801 #pragma mark -
10802 #pragma mark - Searcher Functions
10803 #endif
10804
10805 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10806 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10807 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10808 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10809 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10810 //
10811 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10812 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10813 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10814 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10815 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10816 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10817 // breaks this design principle.
10818 //
10819
10820 // If IsLLQ(Q) is true, it means the question is both:
10821 // (a) long-lived and
10822 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10823 // for multicast questions, we don't want to treat LongLived as anything special
10824 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10825 #define AWDLIsIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10826 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10827
10828 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10829 {
10830 DNSQuestion *q;
10831 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10832 // This prevents circular references, where two questions are each marked as a duplicate of the other.
10833 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10834 // further in the list.
10835 for (q = m->Questions; q && (q != question); q = q->next)
10836 {
10837 if (!SameQuestionKind(q, question)) continue;
10838 if (q->qnamehash != question->qnamehash) continue;
10839 if (q->InterfaceID != question->InterfaceID) continue;
10840 if (q->qtype != question->qtype) continue;
10841 if (q->qclass != question->qclass) continue;
10842 if (IsLLQ(q) != IsLLQ(question)) continue;
10843 if (q->AuthInfo && !question->AuthInfo) continue;
10844 if (q->ValidationRequired != question->ValidationRequired) continue;
10845 if (q->ValidatingResponse != question->ValidatingResponse) continue;
10846 if (!q->Suppressed != !question->Suppressed) continue;
10847 if (q->BrowseThreshold != question->BrowseThreshold) continue;
10848 if (AWDLIsIncluded(q) != AWDLIsIncluded(question)) continue;
10849 if (!SameDomainName(&q->qname, &question->qname)) continue;
10850 return(q);
10851 }
10852 return(mDNSNULL);
10853 }
10854
10855 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10856 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10857 {
10858 DNSQuestion *q;
10859 DNSQuestion *first = mDNSNULL;
10860
10861 // This is referring to some other question as duplicate. No other question can refer to this
10862 // question as a duplicate.
10863 if (question->DuplicateOf)
10864 {
10865 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
10866 "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME " (" PUB_S ") duplicate of %p " PRI_DM_NAME " (" PUB_S ")",
10867 question->request_id, mDNSVal16(question->DuplicateOf->TargetQID), mDNSVal16(question->TargetQID),
10868 question, DM_NAME_PARAM(question->qname.c), DNSTypeName(question->qtype), question->DuplicateOf,
10869 DM_NAME_PARAM(question->DuplicateOf->qname.c), DNSTypeName(question->DuplicateOf->qtype));
10870 return;
10871 }
10872
10873 for (q = m->Questions; q; q=q->next) // Scan our list of questions
10874 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate
10875 {
10876 q->DuplicateOf = first;
10877 if (!first)
10878 {
10879 first = q;
10880 // If q used to be a duplicate, but now is not,
10881 // then inherit the state from the question that's going away
10882 q->LastQTime = question->LastQTime;
10883 q->ThisQInterval = question->ThisQInterval;
10884 q->ExpectUnicastResp = question->ExpectUnicastResp;
10885 q->LastAnswerPktNum = question->LastAnswerPktNum;
10886 q->RecentAnswerPkts = question->RecentAnswerPkts;
10887 q->RequestUnicast = question->RequestUnicast;
10888 q->LastQTxTime = question->LastQTxTime;
10889 q->CNAMEReferrals = question->CNAMEReferrals;
10890 q->nta = question->nta;
10891 q->servAddr = question->servAddr;
10892 q->servPort = question->servPort;
10893 q->qDNSServer = question->qDNSServer;
10894 q->validDNSServers = question->validDNSServers;
10895 q->unansweredQueries = question->unansweredQueries;
10896 q->noServerResponse = question->noServerResponse;
10897 q->triedAllServersOnce = question->triedAllServersOnce;
10898
10899 q->TargetQID = question->TargetQID;
10900 q->LocalSocket = question->LocalSocket;
10901 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10902
10903 q->state = question->state;
10904 // q->tcp = question->tcp;
10905 q->ReqLease = question->ReqLease;
10906 q->expire = question->expire;
10907 q->ntries = question->ntries;
10908 q->id = question->id;
10909
10910 question->LocalSocket = mDNSNULL;
10911 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question
10912 // question->tcp = mDNSNULL;
10913
10914 if (q->LocalSocket)
10915 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10916
10917 if (q->nta)
10918 {
10919 LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10920 q->nta->ZoneDataContext = q;
10921 }
10922
10923 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10924 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10925
10926 if (question->state == LLQ_Established)
10927 {
10928 LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10929 question->state = 0; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10930 }
10931
10932 SetNextQueryTime(m,q);
10933 }
10934 }
10935 }
10936
10937 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10938 {
10939 McastResolver **p = &m->McastResolvers;
10940 McastResolver *tmp = mDNSNULL;
10941
10942 if (!d) d = (const domainname *)"";
10943
10944 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10945 "mDNS_AddMcastResolver: Adding " PUB_DM_NAME ", InterfaceID %p, timeout %u", DM_NAME_PARAM(d), interface, timeout);
10946
10947 mDNS_CheckLock(m);
10948
10949 while (*p) // Check if we already have this {interface, domain} tuple registered
10950 {
10951 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10952 {
10953 if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10954 (*p)->flags &= ~McastResolver_FlagDelete;
10955 tmp = *p;
10956 *p = tmp->next;
10957 tmp->next = mDNSNULL;
10958 }
10959 else
10960 p=&(*p)->next;
10961 }
10962
10963 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10964 else
10965 {
10966 // allocate, add to list
10967 *p = (McastResolver *) mDNSPlatformMemAllocateClear(sizeof(**p));
10968 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10969 else
10970 {
10971 (*p)->interface = interface;
10972 (*p)->flags = McastResolver_FlagNew;
10973 (*p)->timeout = timeout;
10974 AssignDomainName(&(*p)->domain, d);
10975 (*p)->next = mDNSNULL;
10976 }
10977 }
10978 return(*p);
10979 }
10980
10981 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10982 {
10983 mDNSs32 ptime = 0;
10984 if (server->penaltyTime != 0)
10985 {
10986 ptime = server->penaltyTime - m->timenow;
10987 if (ptime < 0)
10988 {
10989 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10990 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10991 // here
10992 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10993 ptime, server->penaltyTime, m->timenow);
10994 server->penaltyTime = 0;
10995 ptime = 0;
10996 }
10997 }
10998 return ptime;
10999 }
11000
11001 //Checks to see whether the newname is a better match for the name, given the best one we have
11002 //seen so far (given in bestcount).
11003 //Returns -1 if the newname is not a better match
11004 //Returns 0 if the newname is the same as the old match
11005 //Returns 1 if the newname is a better match
11006 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
11007 int bestcount)
11008 {
11009 // If the name contains fewer labels than the new server's domain or the new name
11010 // contains fewer labels than the current best, then it can't possibly be a better match
11011 if (namecount < newcount || newcount < bestcount) return -1;
11012
11013 // If there is no match, return -1 and the caller will skip this newname for
11014 // selection
11015 //
11016 // If we find a match and the number of labels is the same as bestcount, then
11017 // we return 0 so that the caller can do additional logic to pick one of
11018 // the best based on some other factors e.g., penaltyTime
11019 //
11020 // If we find a match and the number of labels is more than bestcount, then we
11021 // return 1 so that the caller can pick this over the old one.
11022 //
11023 // Note: newcount can either be equal or greater than bestcount beause of the
11024 // check above.
11025
11026 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
11027 return bestcount == newcount ? 0 : 1;
11028 else
11029 return -1;
11030 }
11031
11032 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
11033 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
11034 // names. In that case, we give a default timeout of 5 seconds
11035 #define DEFAULT_MCAST_TIMEOUT 5
11036 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
11037 {
11038 McastResolver *curmatch = mDNSNULL;
11039 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
11040 McastResolver *curr;
11041 int bettermatch, currcount;
11042 for (curr = m->McastResolvers; curr; curr = curr->next)
11043 {
11044 currcount = CountLabels(&curr->domain);
11045 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11046 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
11047 // the timeout value from the first one
11048 if (bettermatch == 1)
11049 {
11050 curmatch = curr;
11051 bestmatchlen = currcount;
11052 }
11053 }
11054 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
11055 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
11056 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
11057 }
11058
11059 // Returns true if it is a Domain Enumeration Query
11060 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
11061 {
11062 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
11063 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
11064 const domainname *d = qname;
11065 const mDNSu8 *label;
11066 int i = 0;
11067
11068 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
11069 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
11070
11071 label = (const mDNSu8 *)d;
11072 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
11073 {
11074 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
11075 i++;
11076 }
11077 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
11078 {
11079 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
11080 return mDNSfalse;
11081 }
11082 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
11083
11084 // CountLabels already verified the number of labels
11085 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label
11086 label = (const mDNSu8 *)d;
11087 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
11088 {
11089 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
11090 return(mDNSfalse);
11091 }
11092 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
11093
11094 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label
11095 label = (const mDNSu8 *)d;
11096 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
11097 {
11098 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
11099 return(mDNSfalse);
11100 }
11101 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
11102
11103 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
11104
11105 return mDNStrue;
11106 }
11107
11108 // Note: InterfaceID is the InterfaceID of the question
11109 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11110 {
11111 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11112 // with scopeType set to kScopeNone)
11113 //
11114 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11115 // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11116 //
11117 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11118 // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11119 //
11120 // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11121 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11122 //
11123 // If the first condition fails, following are the possible cases (the notes below are using
11124 // InterfaceID for discussion and the same holds good for ServiceID):
11125 //
11126 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11127 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11128 //
11129 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11130 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11131 // would fail in this case.
11132 //
11133 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11134 // should match (Refer to (2) above).
11135
11136 if (((d->scopeType == kScopeNone) && (!InterfaceID && ServiceID == -1)) ||
11137 ((d->scopeType == kScopeInterfaceID) && d->interface == InterfaceID) ||
11138 ((d->scopeType == kScopeServiceID) && d->serviceID == ServiceID))
11139 {
11140 return mDNStrue;
11141 }
11142 return mDNSfalse;
11143 }
11144
11145 // Sets all the Valid DNS servers for a question
11146 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
11147 {
11148 int bestmatchlen = -1, namecount = CountLabels(&question->qname);
11149 DNSServer *curr;
11150 int bettermatch, currcount;
11151 int index = 0;
11152 mDNSu32 timeout = 0;
11153 mDNSBool DEQuery;
11154
11155 question->validDNSServers = zeroOpaque128;
11156 DEQuery = DomainEnumQuery(&question->qname);
11157 for (curr = m->DNSServers; curr; curr = curr->next)
11158 {
11159 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scopeType);
11160 // skip servers that will soon be deleted
11161 if (curr->flags & DNSServerFlag_Delete)
11162 {
11163 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11164 continue;
11165 }
11166
11167 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11168 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11169 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11170 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11171 // match the scoped entries by mistake.
11172 //
11173 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11174
11175 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11176 if (((curr->scopeType == kScopeInterfaceID) && (curr->interface == mDNSInterface_Any)) ||
11177 ((curr->scopeType == kScopeServiceID) && (curr->serviceID <= 0)))
11178 {
11179 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11180 (int)curr->scopeType, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
11181 continue;
11182 }
11183
11184 currcount = CountLabels(&curr->domain);
11185 if ((!DEQuery || !curr->isCell) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
11186 {
11187 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11188
11189 // If we found a better match (bettermatch == 1) then clear all the bits
11190 // corresponding to the old DNSServers that we have may set before and start fresh.
11191 // If we find an equal match, then include that DNSServer also by setting the corresponding
11192 // bit
11193 if ((bettermatch == 1) || (bettermatch == 0))
11194 {
11195 bestmatchlen = currcount;
11196 if (bettermatch)
11197 {
11198 debugf("SetValidDNSServers: Resetting all the bits");
11199 question->validDNSServers = zeroOpaque128;
11200 timeout = 0;
11201 }
11202 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11203 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scopeType, index, curr->timeout,
11204 curr->interface);
11205 timeout += curr->timeout;
11206 if (DEQuery)
11207 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->isCell);
11208 bit_set_opaque128(question->validDNSServers, index);
11209 }
11210 }
11211 index++;
11212 }
11213 question->noServerResponse = 0;
11214
11215 debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11216 question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
11217 // If there are no matching resolvers, then use the default timeout value.
11218 // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
11219 return ((question->ProxyQuestion || question->ValidatingResponse) ? DEFAULT_UDNSSEC_TIMEOUT : timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
11220 }
11221
11222 // Get the Best server that matches a name. If you find penalized servers, look for the one
11223 // that will come out of the penalty box soon
11224 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits,
11225 int *selected, mDNSBool nameMatch)
11226 {
11227 DNSServer *curmatch = mDNSNULL;
11228 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
11229 DNSServer *curr;
11230 mDNSs32 bestPenaltyTime, currPenaltyTime;
11231 int bettermatch, currcount;
11232 int index = 0;
11233 int currindex = -1;
11234
11235 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]);
11236 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
11237 for (curr = m->DNSServers; curr; curr = curr->next)
11238 {
11239 // skip servers that will soon be deleted
11240 if (curr->flags & DNSServerFlag_Delete)
11241 {
11242 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11243 continue;
11244 }
11245
11246 // Check if this is a valid DNSServer
11247 if (!bit_get_opaque64(validBits, index))
11248 {
11249 debugf("GetBestServer: continuing for index %d", index);
11250 index++;
11251 continue;
11252 }
11253
11254 currcount = CountLabels(&curr->domain);
11255 currPenaltyTime = PenaltyTimeForServer(m, curr);
11256
11257 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11258 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
11259
11260 // If there are multiple best servers for a given question, we will pick the first one
11261 // if none of them are penalized. If some of them are penalized in that list, we pick
11262 // the least penalized one. BetterMatchForName walks through all best matches and
11263 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11264 // in the list when there are no penalized servers and least one among them
11265 // when there are some penalized servers.
11266
11267 if (DNSServerMatch(curr, InterfaceID, ServiceID))
11268 {
11269
11270 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11271 // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11272 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11273 // part and still do some redundant steps e.g., InterfaceID match
11274
11275 if (nameMatch)
11276 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
11277 else
11278 bettermatch = 0;
11279
11280 // If we found a better match (bettermatch == 1) then we don't need to
11281 // compare penalty times. But if we found an equal match, then we compare
11282 // the penalty times to pick a better match
11283
11284 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
11285 {
11286 currindex = index;
11287 curmatch = curr;
11288 bestmatchlen = currcount;
11289 bestPenaltyTime = currPenaltyTime;
11290 }
11291 }
11292 index++;
11293 }
11294 if (selected) *selected = currindex;
11295 return curmatch;
11296 }
11297
11298 // Look up a DNS Server, matching by name and InterfaceID
11299 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11300 {
11301 DNSServer *curmatch = mDNSNULL;
11302 char *ifname = mDNSNULL; // for logging purposes only
11303 mDNSOpaque128 allValid;
11304
11305 if (InterfaceID == mDNSInterface_LocalOnly)
11306 InterfaceID = mDNSNULL;
11307
11308 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
11309
11310 // By passing in all ones, we make sure that every DNS server is considered
11311 allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF;
11312
11313 curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
11314
11315 if (curmatch != mDNSNULL)
11316 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr,
11317 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11318 InterfaceID, name);
11319 else
11320 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name);
11321
11322 return(curmatch);
11323 }
11324
11325 // Look up a DNS Server for a question within its valid DNSServer bits
11326 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
11327 {
11328 DNSServer *curmatch = mDNSNULL;
11329 char *ifname = mDNSNULL; // for logging purposes only
11330 mDNSInterfaceID InterfaceID = question->InterfaceID;
11331 const domainname *name = &question->qname;
11332 int currindex;
11333
11334 if (InterfaceID == mDNSInterface_LocalOnly)
11335 InterfaceID = mDNSNULL;
11336
11337 if (InterfaceID)
11338 ifname = InterfaceNameForID(m, InterfaceID);
11339
11340 if (!mDNSOpaque128IsZero(&question->validDNSServers))
11341 {
11342 curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
11343 if (currindex != -1)
11344 bit_clr_opaque128(question->validDNSServers, currindex);
11345 }
11346
11347 if (curmatch != mDNSNULL)
11348 {
11349 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11350 "[R%d->Q%d] GetServerForQuestion: %p DNS server (%p) " PRI_IP_ADDR ":%d (Penalty Time Left %d) (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11351 question->request_id, mDNSVal16(question->TargetQID), question, curmatch, &curmatch->addr,
11352 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0),
11353 ifname ? ifname : "None", InterfaceID, question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11354 }
11355 else
11356 {
11357 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11358 "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11359 question->request_id, mDNSVal16(question->TargetQID), question, ifname ? ifname : "None", InterfaceID,
11360 question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11361 }
11362
11363 return(curmatch);
11364 }
11365
11366 // Called in normal client context (lock not held)
11367 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
11368 {
11369 DNSQuestion *q;
11370 mDNS_Lock(m);
11371 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
11372 n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
11373 for (q = m->Questions; q; q=q->next)
11374 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
11375 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead
11376 mDNS_Unlock(m);
11377 }
11378
11379 // This function takes the DNSServer as a separate argument because sometimes the
11380 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11381 // status before switching to it.
11382 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const DNSServer *const server)
11383 {
11384 mDNSBool suppress = mDNSfalse;
11385 const char *reason = NULL;
11386
11387 if (q->BlockedByPolicy)
11388 {
11389 suppress = mDNStrue;
11390 reason = " (blocked by policy)";
11391 }
11392 else if (!server)
11393 {
11394 if (!q->IsUnicastDotLocal)
11395 {
11396 suppress = mDNStrue;
11397 reason = " (no DNS server)";
11398 }
11399 }
11400 else if (server->isCell && (q->flags & kDNSServiceFlagsDenyCellular))
11401 {
11402 suppress = mDNStrue;
11403 reason = " (interface is cellular)";
11404 }
11405 else if (server->isExpensive && (q->flags & kDNSServiceFlagsDenyExpensive))
11406 {
11407 suppress = mDNStrue;
11408 reason = " (interface is expensive)";
11409 }
11410 else if (server->isConstrained && (q->flags & kDNSServiceFlagsDenyConstrained))
11411 {
11412 suppress = mDNStrue;
11413 reason = " (interface is constrained)";
11414 }
11415 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11416 else if (q->SuppressUnusable && !DNS64IsQueryingARecord(q->dns64.state))
11417 #else
11418 else if (q->SuppressUnusable)
11419 #endif
11420 {
11421 if (q->qtype == kDNSType_A)
11422 {
11423 if (!server->usableA)
11424 {
11425 suppress = mDNStrue;
11426 reason = " (A records are unusable)";
11427 }
11428 // If the server's configuration allows A record queries, suppress this query if
11429 // 1. the interface associated with the server is CLAT46; and
11430 // 2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11431 // See <rdar://problem/42672030> for more info.
11432 else if (server->isCLAT46 && (q->flags & kDNSServiceFlagsPathEvaluationDone))
11433 {
11434 suppress = mDNStrue;
11435 reason = " (CLAT46 A records are unusable)";
11436 }
11437 }
11438 else if (q->qtype == kDNSType_AAAA)
11439 {
11440 if (!server->usableAAAA)
11441 {
11442 suppress = mDNStrue;
11443 reason = " (AAAA records are unusable)";
11444 }
11445 }
11446 }
11447 if (suppress)
11448 {
11449 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11450 "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME " " PUB_S PUB_S,
11451 mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), reason ? reason : "");
11452 }
11453 return suppress;
11454 }
11455
11456 mDNSlocal mDNSBool ShouldSuppressQuery(DNSQuestion *q)
11457 {
11458 if (q->InterfaceID == mDNSInterface_LocalOnly)
11459 {
11460 return mDNSfalse;
11461 }
11462 if (!q->IsUnicastDotLocal && IsLocalDomain(&q->qname))
11463 {
11464 return mDNSfalse;
11465 }
11466 return (ShouldSuppressUnicastQuery(q, q->qDNSServer));
11467 }
11468
11469 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11470 {
11471 CacheRecord *cr;
11472 CacheGroup *cg;
11473
11474 cg = CacheGroupForName(m, q->qnamehash, &q->qname);
11475 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
11476 {
11477 // Don't deliver RMV events for negative records
11478 if (cr->resrec.RecordType == kDNSRecordTypePacketNegative)
11479 {
11480 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11481 "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S " Suppressing RMV events for question %p " PRI_DM_NAME " (" PUB_S "), CRActiveQuestion %p, CurrentAnswers %d",
11482 q->request_id, mDNSVal16(q->TargetQID), CRDisplayString(m, cr), q, DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype), cr->CRActiveQuestion, q->CurrentAnswers);
11483 continue;
11484 }
11485
11486 if (SameNameCacheRecordAnswersQuestion(cr, q))
11487 {
11488 LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11489 q->qname.c, CRDisplayString(m, cr), q->LOAddressAnswers);
11490
11491 q->CurrentAnswers--;
11492 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11493 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11494 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
11495 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here
11496 }
11497 }
11498 }
11499
11500 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11501 {
11502 DNSQuestion *q;
11503 for (q = m->NewQuestions; q; q = q->next)
11504 if (q == question) return mDNStrue;
11505 return mDNSfalse;
11506 }
11507
11508 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11509 {
11510 AuthRecord *rr;
11511 AuthGroup *ag;
11512
11513 if (m->CurrentQuestion)
11514 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11515 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11516
11517 if (IsQuestionNew(m, q))
11518 {
11519 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11520 return mDNStrue;
11521 }
11522 m->CurrentQuestion = q;
11523 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
11524 if (ag)
11525 {
11526 for (rr = ag->members; rr; rr=rr->next)
11527 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11528 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11529 {
11530 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11531 ARDisplayString(m, rr));
11532 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11533 {
11534 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11535 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11536 q->CurrentAnswers, q->LOAddressAnswers);
11537 continue;
11538 }
11539 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again
11540 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11541 }
11542 }
11543 m->CurrentQuestion = mDNSNULL;
11544 return mDNStrue;
11545 }
11546
11547 // Returns false if the question got deleted while delivering the RMV events
11548 // The caller should handle the case
11549 mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11550 {
11551 if (m->CurrentQuestion)
11552 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11553 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11554
11555 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11556 // If this question was answered using local auth records, then you can't deliver RMVs using cache
11557 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11558 {
11559 m->CurrentQuestion = q;
11560 CacheRecordRmvEventsForCurrentQuestion(m, q);
11561 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11562 m->CurrentQuestion = mDNSNULL;
11563 }
11564 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11565 return mDNStrue;
11566 }
11567
11568 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11569 {
11570 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11571 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11572 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11573 if (q->Suppressed)
11574 {
11575 q->Suppressed = mDNSfalse;
11576 if (!CacheRecordRmvEventsForQuestion(m, q))
11577 {
11578 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11579 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11580 q->request_id, mDNSVal16(q->TargetQID));
11581 return;
11582 }
11583 q->Suppressed = mDNStrue;
11584 }
11585
11586 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11587 // and Suppressed status does not mean anything for these questions. As we are going to stop the
11588 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11589 // the restart will not be a duplicate ADD
11590 if (!LocalRecordRmvEventsForQuestion(m, q))
11591 {
11592 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11593 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11594 q->request_id, mDNSVal16(q->TargetQID));
11595 return;
11596 }
11597
11598 // There are two cases here.
11599 //
11600 // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11601 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11602 // because when we get the response, if we had entries in the cache already, it will not answer
11603 // this question if the cache entry did not change. Hence, we need to restart
11604 // the query so that it can be answered from the cache.
11605 //
11606 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11607 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11608 // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11609 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11610 // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11611 // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11612 // the question is not suppressed, we don't want two active questions sending packets on the wire.
11613 // This affects both efficiency and also the current design where there is only one active question
11614 // pointed to from a cache entry.
11615 //
11616 // We restart queries in a two step process by first calling stop and build a temporary list which we
11617 // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11618 // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11619 // will soon become the real question) including q->ThisQInterval which might be zero if it was
11620 // suppressed before. At the end when we have restarted all questions, none of them is active as each
11621 // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11622 //
11623 // It is much cleaner and less error prone to build a list of questions and restart at the end.
11624
11625 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11626 "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME " (" PUB_S ")",
11627 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype));
11628 mDNS_StopQuery_internal(m, q);
11629 q->next = *restart;
11630 *restart = q;
11631 }
11632
11633 // The caller should hold the lock
11634 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11635 {
11636 DNSQuestion *q;
11637 DNSQuestion *restart = mDNSNULL;
11638
11639 // We look through all questions including new questions. During network change events,
11640 // we potentially restart questions here in this function that ends up as new questions,
11641 // which may be suppressed at this instance. Before it is handled we get another network
11642 // event that changes the status e.g., address becomes available. If we did not process
11643 // new questions, we would never change its Suppressed status.
11644 //
11645 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11646 // application callback can potentially stop the current question (detected by CurrentQuestion) or
11647 // *any* other question which could be the next one that we may process here. RestartQuestion
11648 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11649 // if the "next" question is stopped while the CurrentQuestion is stopped
11650 if (m->RestartQuestion)
11651 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11652 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11653 m->RestartQuestion = m->Questions;
11654 while (m->RestartQuestion)
11655 {
11656 q = m->RestartQuestion;
11657 m->RestartQuestion = q->next;
11658 if (q->SuppressUnusable)
11659 {
11660 const mDNSBool old = q->Suppressed;
11661 q->Suppressed = ShouldSuppressQuery(q);
11662 if (q->Suppressed != old)
11663 {
11664 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11665 // followed by a negative cache response. Temporarily turn off suppression so that
11666 // AnswerCurrentQuestionWithResourceRecord can answer the question
11667 SuppressStatusChanged(m, q, &restart);
11668 }
11669 }
11670 }
11671 while (restart)
11672 {
11673 q = restart;
11674 restart = restart->next;
11675 q->next = mDNSNULL;
11676 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11677 mDNS_StartQuery_internal(m, q);
11678 }
11679 }
11680
11681 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11682 {
11683 DNSQuestion *q;
11684 DNSQuestion *restartList = mDNSNULL;
11685
11686 if (m->RestartQuestion)
11687 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11688 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11689 m->RestartQuestion = m->Questions;
11690 while (m->RestartQuestion)
11691 {
11692 q = m->RestartQuestion;
11693 m->RestartQuestion = q->next;
11694 if (q->Restart)
11695 {
11696 if (mDNSOpaque16IsZero(q->TargetQID))
11697 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11698
11699 q->Restart = mDNSfalse;
11700 SuppressStatusChanged(m, q, &restartList);
11701 }
11702 }
11703 while ((q = restartList) != mDNSNULL)
11704 {
11705 restartList = q->next;
11706 q->next = mDNSNULL;
11707 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11708 "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME " (" PUB_S ")",
11709 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype));
11710 mDNS_StartQuery_internal(m, q);
11711 }
11712 }
11713
11714 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11715 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11716 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11717 {
11718 if (!ValidateDomainName(&question->qname))
11719 {
11720 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11721 return(mStatus_Invalid);
11722 }
11723
11724 // If this question is referencing a specific interface, verify it exists
11725 if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID))
11726 {
11727 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11728 if (!intf)
11729 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11730 IIDPrintable(question->InterfaceID), question->qname.c, DNSTypeName(question->qtype));
11731 }
11732
11733 return(mStatus_NoError);
11734 }
11735
11736 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11737 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11738 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11739 {
11740 // First reset all DNS Configuration
11741 question->qDNSServer = mDNSNULL;
11742 question->validDNSServers = zeroOpaque128;
11743 question->triedAllServersOnce = mDNSfalse;
11744 question->noServerResponse = mDNSfalse;
11745 question->StopTime = (question->TimeoutQuestion) ? question->StopTime : 0;
11746 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11747 mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
11748 question->metrics.expiredAnswerState = (question->allowExpired != AllowExpired_None) ? ExpiredAnswer_Allowed : ExpiredAnswer_None;
11749 #endif
11750
11751 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11752 if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion)
11753 return;
11754 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11755 if (!mDNSOpaque16IsZero(question->TargetQID))
11756 {
11757 mDNSu32 timeout = SetValidDNSServers(m, question);
11758 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11759 // So if a question is restarted when a network change occurs, the StopTime is not reset.
11760 // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11761 // it gets a full timeout value even if the original question times out earlier.
11762 if (question->TimeoutQuestion && !question->StopTime)
11763 {
11764 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11765 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11766 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11767 mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(question->qname.c), DNSTypeName(question->qtype));
11768 }
11769
11770 question->qDNSServer = GetServerForQuestion(m, question);
11771 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
11772 "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME " " PUB_S " Timeout %d, DNS Server " PRI_IP_ADDR ":%d",
11773 question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(question->qname.c),
11774 DNSTypeName(question->qtype), timeout, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11775 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11776 }
11777 else if (question->TimeoutQuestion && !question->StopTime)
11778 {
11779 // If the question is to be timed out and its a multicast, local-only or P2P case,
11780 // then set it's stop time.
11781 mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ?
11782 DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question);
11783 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11784 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11785 "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11786 question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(question->qname.c), DNSTypeName(question->qtype));
11787 }
11788 // Set StopTime here since it is a part of DNS Configuration
11789 if (question->StopTime)
11790 SetNextQueryStopTime(m, question);
11791 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11792 // will never be transmitted on the wire.
11793 if (!(LocalOnlyOrP2PInterface(question->InterfaceID)))
11794 SetNextQueryTime(m,question);
11795 }
11796
11797 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11798 // state fields of the DNS Question. These are independent of the Client layer.
11799 mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question)
11800 {
11801 int i;
11802 mDNSBool isBlocked = mDNSfalse;
11803
11804 // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11805 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11806 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11807 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11808 // that to go out immediately.
11809 question->next = mDNSNULL;
11810 // ThisQInterval should be initialized before any memory allocations occur. If malloc
11811 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11812 // the question list to check if ThisQInterval is negative which means the question has been
11813 // stopped and can't be on the list. The question is already on the list and ThisQInterval
11814 // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11815 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11816 // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11817 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question
11818 question->qnamehash = DomainNameHashValue(&question->qname);
11819 question->DelayAnswering = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0;
11820 question->LastQTime = m->timenow;
11821 question->ExpectUnicastResp = 0;
11822 question->LastAnswerPktNum = m->PktNum;
11823 question->RecentAnswerPkts = 0;
11824 question->CurrentAnswers = 0;
11825
11826 #if APPLE_OSX_mDNSResponder
11827
11828 // Initial browse threshold used by Finder.
11829 #define mDNSFinderBrowseThreshold 20
11830
11831 // Set the threshold at which we move to a passive browse state,
11832 // not actively sending queries.
11833 if (question->flags & kDNSServiceFlagsThresholdOne)
11834 question->BrowseThreshold = 1;
11835 else if (question->flags & kDNSServiceFlagsThresholdFinder)
11836 question->BrowseThreshold = mDNSFinderBrowseThreshold;
11837 else
11838 question->BrowseThreshold = 0;
11839
11840 #else // APPLE_OSX_mDNSResponder
11841 question->BrowseThreshold = 0;
11842 #endif // APPLE_OSX_mDNSResponder
11843 question->CachedAnswerNeedsUpdate = mDNSfalse;
11844
11845 question->LargeAnswers = 0;
11846 question->UniqueAnswers = 0;
11847 question->LOAddressAnswers = 0;
11848 question->FlappingInterface1 = mDNSNULL;
11849 question->FlappingInterface2 = mDNSNULL;
11850
11851 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11852 // since we would already have the question->ServiceID in that case.
11853 if (!(question->flags & kDNSServiceFlagsServiceIndex))
11854 {
11855 #if APPLE_OSX_mDNSResponder
11856 mDNSPlatformGetDNSRoutePolicy(question, &isBlocked);
11857 #else
11858 question->ServiceID = -1;
11859 #endif
11860 }
11861 else
11862 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11863 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11864
11865 InitDNSConfig(m, question);
11866
11867 question->AuthInfo = GetAuthInfoForQuestion(m, question);
11868
11869 // The question's BlockedByPolicy value must be set before calling ShouldSuppressQuery().
11870 question->BlockedByPolicy = isBlocked ? mDNStrue : mDNSfalse;
11871 question->Suppressed = ShouldSuppressQuery(question);
11872 question->NextInDQList = mDNSNULL;
11873 question->SendQNow = mDNSNULL;
11874 question->SendOnAll = mDNSfalse;
11875 question->RequestUnicast = kDefaultRequestUnicastCount;
11876
11877 #if APPLE_OSX_mDNSResponder
11878 // Set the QU bit in the first query for the following options.
11879 if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder))
11880 {
11881 question->RequestUnicast = SET_QU_IN_FIRST_QUERY;
11882 LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11883 DNSTypeName(question->qtype));
11884 }
11885 #endif // APPLE_OSX_mDNSResponder
11886
11887 question->LastQTxTime = m->timenow;
11888 question->CNAMEReferrals = 0;
11889
11890 question->WakeOnResolveCount = 0;
11891 if (question->WakeOnResolve)
11892 {
11893 question->WakeOnResolveCount = InitialWakeOnResolveCount;
11894 }
11895
11896 for (i=0; i<DupSuppressInfoSize; i++)
11897 question->DupSuppress[i].InterfaceID = mDNSNULL;
11898
11899 question->Restart = mDNSfalse;
11900
11901 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11902 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11903 NextQSendTime(question) - m->timenow,
11904 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11905 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11906
11907 if (question->DelayAnswering)
11908 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11909 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11910 }
11911
11912 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11913 mDNSlocal void InitWABState(DNSQuestion *const question)
11914 {
11915 // We'll create our question->LocalSocket on demand, if needed.
11916 // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11917 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11918 // NAT mapping for receiving inbound add/remove events.
11919 question->LocalSocket = mDNSNULL;
11920 question->unansweredQueries = 0;
11921 question->nta = mDNSNULL;
11922 question->servAddr = zeroAddr;
11923 question->servPort = zeroIPPort;
11924 question->tcp = mDNSNULL;
11925 question->NoAnswer = NoAnswer_Normal;
11926 }
11927
11928 mDNSlocal void InitLLQNATState(mDNS *const m)
11929 {
11930 // If we don't have our NAT mapping active, start it now
11931 if (!m->LLQNAT.clientCallback)
11932 {
11933 m->LLQNAT.Protocol = NATOp_MapUDP;
11934 m->LLQNAT.IntPort = m->UnicastPort4;
11935 m->LLQNAT.RequestedPort = m->UnicastPort4;
11936 m->LLQNAT.clientCallback = LLQNATCallback;
11937 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal just started
11938 mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11939 }
11940 }
11941
11942 mDNSlocal void InitLLQState(DNSQuestion *const question)
11943 {
11944 question->state = LLQ_Init;
11945 question->ReqLease = 0;
11946 question->expire = 0;
11947 question->ntries = 0;
11948 question->id = zeroOpaque64;
11949 }
11950
11951 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11952 // DNSSEC & DNS Proxy fields of the DNS Question.
11953 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11954 {
11955 (void) m;
11956
11957 // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11958 // or the request is going over cellular interface.
11959 //
11960 // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11961 // at ValidationRequired setting also.
11962 if (question->qDNSServer)
11963 {
11964 if (question->qDNSServer->isCell)
11965 {
11966 debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
11967 question->ValidationRequired = mDNSfalse;
11968 }
11969 if (DNSSECOptionalQuestion(question) && !(question->qDNSServer->req_DO))
11970 {
11971 LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11972 question->qname.c, DNSTypeName(question->qtype));
11973 question->ValidationRequired = DNSSEC_VALIDATION_NONE;
11974 }
11975 }
11976 question->ValidationState = (question->ValidationRequired ? DNSSECValRequired : DNSSECValNotRequired);
11977 question->ValidationStatus = 0;
11978 question->responseFlags = zeroID;
11979 }
11980
11981 // Once the question is completely initialized including the duplicate logic, this function
11982 // is called to finalize the unicast question which requires flushing the cache if needed,
11983 // activating the query etc.
11984 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question)
11985 {
11986 // Ensure DNS related info of duplicate question is same as the orig question
11987 if (question->DuplicateOf)
11988 {
11989 question->validDNSServers = question->DuplicateOf->validDNSServers;
11990 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11991 // then we log a line as it could indicate an issue
11992 if (question->DuplicateOf->qDNSServer == mDNSNULL)
11993 {
11994 if (question->qDNSServer) {
11995 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11996 "[R%d->Q%d] FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(" PRI_IP_ADDR ":%d) but original question(%p) has no DNS Server! " PRI_DM_NAME " (" PUB_S ")",
11997 question->request_id, mDNSVal16(question->TargetQID), question,
11998 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11999 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort), question->DuplicateOf,
12000 DM_NAME_PARAM(question->qname.c), DNSTypeName(question->qtype));
12001 }
12002
12003 }
12004 question->qDNSServer = question->DuplicateOf->qDNSServer;
12005 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12006 "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME " (" PUB_S "), DNS Server " PRI_IP_ADDR ":%d",
12007 question->request_id, mDNSVal16(question->DuplicateOf->TargetQID), mDNSVal16(question->TargetQID),
12008 question, question->DuplicateOf, DM_NAME_PARAM(question->qname.c), DNSTypeName(question->qtype),
12009 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
12010 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
12011 }
12012
12013 ActivateUnicastQuery(m, question, mDNSfalse);
12014
12015 if (!question->DuplicateOf && DNSSECQuestion(question))
12016 {
12017 // For DNSSEC questions, we need to have the RRSIGs also for verification.
12018 CheckForDNSSECRecords(m, question);
12019 }
12020 if (question->LongLived)
12021 {
12022 // Unlike other initializations, InitLLQNATState should be done after
12023 // we determine that it is a unicast question. LongLived is set for
12024 // both multicast and unicast browse questions but we should initialize
12025 // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
12026 // start the NAT traversal that is not needed.
12027 InitLLQNATState(m);
12028 }
12029 }
12030
12031 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
12032 {
12033 DNSQuestion **q;
12034 mStatus vStatus;
12035
12036 // First check for cache space (can't do queries if there is no cache space allocated)
12037 if (m->rrcache_size == 0)
12038 return(mStatus_NoCache);
12039
12040 vStatus = ValidateParameters(m, question);
12041 if (vStatus)
12042 return(vStatus);
12043
12044 #ifdef USE_LIBIDN
12045 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12046 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12047 // This applies to the top label (TLD) only
12048 // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12049 if (IsHighASCIILabel(LastLabel(&question->qname)))
12050 {
12051 domainname newname;
12052 if (PerformNextPunycodeConversion(question, &newname))
12053 AssignDomainName(&question->qname, &newname);
12054 }
12055 #endif // USE_LIBIDN
12056
12057 #ifndef UNICAST_DISABLED
12058 question->TargetQID = Question_uDNS(question) ? mDNS_NewMessageID(m) : zeroID;
12059 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
12060 question->LastTargetQID = zeroID;
12061 #endif
12062 #else
12063 question->TargetQID = zeroID;
12064 #endif
12065 debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12066
12067 // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12068 q = &m->Questions;
12069 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12070 q = &m->LocalOnlyQuestions;
12071 while (*q && *q != question)
12072 q=&(*q)->next;
12073
12074 if (*q)
12075 {
12076 LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12077 question->qname.c, DNSTypeName(question->qtype), question);
12078 return(mStatus_AlreadyRegistered);
12079 }
12080 *q = question;
12081
12082 // Intialize the question. The only ordering constraint we have today is that
12083 // InitDNSSECProxyState should be called after the DNS server is selected (in
12084 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12085 // validation.
12086
12087 InitCommonState(m, question);
12088 InitWABState(question);
12089 InitLLQState(question);
12090 InitDNSSECProxyState(m, question);
12091
12092 // FindDuplicateQuestion should be called last after all the intialization
12093 // as the duplicate logic could be potentially based on any field in the
12094 // question.
12095 question->DuplicateOf = FindDuplicateQuestion(m, question);
12096 if (question->DuplicateOf)
12097 question->AuthInfo = question->DuplicateOf->AuthInfo;
12098
12099 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12100 {
12101 if (!m->NewLocalOnlyQuestions)
12102 m->NewLocalOnlyQuestions = question;
12103 }
12104 else
12105 {
12106 if (!m->NewQuestions)
12107 m->NewQuestions = question;
12108
12109 // If the question's id is non-zero, then it's Wide Area
12110 // MUST NOT do this Wide Area setup until near the end of
12111 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12112 // NS, etc.) and if we haven't finished setting up our own question and setting
12113 // m->NewQuestions if necessary then we could end up recursively re-entering
12114 // this routine with the question list data structures in an inconsistent state.
12115 if (!mDNSOpaque16IsZero(question->TargetQID))
12116 {
12117 FinalizeUnicastQuestion(m, question);
12118 }
12119 else
12120 {
12121 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12122 m->NumAllInterfaceQuestions++;
12123 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12124 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12125 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12126 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12127 {
12128 m->NextBonjourDisableTime = 0;
12129 if (m->BonjourEnabled == 0)
12130 {
12131 // Enable Bonjour immediately by scheduling network changed processing where
12132 // we will join the multicast group on each active interface.
12133 m->BonjourEnabled = 1;
12134 m->NetworkChanged = m->timenow;
12135 }
12136 }
12137 #endif
12138 if (question->WakeOnResolve)
12139 {
12140 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
12141 mDNS_PurgeBeforeResolve(m, question);
12142 }
12143 }
12144 }
12145
12146 return(mStatus_NoError);
12147 }
12148
12149 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12150 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
12151 {
12152 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
12153 // This function may be called anytime to free the zone information.The question may or may not have stopped.
12154 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12155 // call it again
12156 if (nta->question.ThisQInterval != -1)
12157 {
12158 mDNS_StopQuery_internal(m, &nta->question);
12159 if (nta->question.ThisQInterval != -1)
12160 LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
12161 }
12162 mDNSPlatformMemFree(nta);
12163 }
12164
12165 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
12166 {
12167 CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12168 CacheRecord *cr;
12169 DNSQuestion **qp = &m->Questions;
12170
12171 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12172
12173 if (LocalOnlyOrP2PInterface(question->InterfaceID))
12174 qp = &m->LocalOnlyQuestions;
12175 while (*qp && *qp != question) qp=&(*qp)->next;
12176 if (*qp) *qp = (*qp)->next;
12177 else
12178 {
12179 #if !ForceAlerts
12180 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active
12181 #endif
12182 LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
12183 return(mStatus_BadReferenceErr);
12184 }
12185
12186 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12187 if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID))
12188 {
12189 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12190 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
12191 m->NumAllInterfaceQuestions--;
12192 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12193 "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12194 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12195 }
12196 #endif
12197
12198 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12199 if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.querySendCount > 0))
12200 {
12201 const domainname * queryName;
12202 mDNSBool isForCell;
12203 mDNSu32 durationMs;
12204
12205 queryName = question->metrics.originalQName ? question->metrics.originalQName : &question->qname;
12206 isForCell = (question->qDNSServer && question->qDNSServer->isCell);
12207 durationMs = ((m->timenow - question->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
12208 MetricsUpdateDNSQueryStats(queryName, question->qtype, mDNSNULL, question->metrics.querySendCount, question->metrics.expiredAnswerState, question->metrics.dnsOverTCPState, durationMs, isForCell);
12209 }
12210 #endif
12211 // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12212 UpdateQuestionDuplicates(m, question);
12213 // But don't trash ThisQInterval until afterwards.
12214 question->ThisQInterval = -1;
12215
12216 // If there are any cache records referencing this as their active question, then see if there is any
12217 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12218 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12219 {
12220 if (cr->CRActiveQuestion == question)
12221 {
12222 DNSQuestion *q;
12223 DNSQuestion *replacement = mDNSNULL;
12224 // If we find an active question that is answered by this cached record, use it as the cache record's
12225 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12226 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12227 // via CacheRecordRmv() when the cache record expires.
12228 for (q = m->Questions; q && (q != m->NewQuestions); q = q->next)
12229 {
12230 if (!q->DuplicateOf && !q->Suppressed && CacheRecordAnswersQuestion(cr, q))
12231 {
12232 if (q->ThisQInterval > 0)
12233 {
12234 replacement = q;
12235 break;
12236 }
12237 else if (!replacement)
12238 {
12239 replacement = q;
12240 }
12241 }
12242 }
12243 if (replacement)
12244 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12245 "CurrentAnswers %d, Suppressed %d", replacement, CRDisplayString(m,cr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->Suppressed);
12246 cr->CRActiveQuestion = replacement; // Question used to be active; new value may or may not be null
12247 if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count
12248 }
12249 }
12250
12251 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12252 // bump its pointer forward one question.
12253 if (m->CurrentQuestion == question)
12254 {
12255 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12256 question->qname.c, DNSTypeName(question->qtype));
12257 m->CurrentQuestion = question->next;
12258 }
12259
12260 if (m->NewQuestions == question)
12261 {
12262 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12263 question->qname.c, DNSTypeName(question->qtype));
12264 m->NewQuestions = question->next;
12265 }
12266
12267 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
12268
12269 if (m->RestartQuestion == question)
12270 {
12271 LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12272 question->qname.c, DNSTypeName(question->qtype));
12273 m->RestartQuestion = question->next;
12274 }
12275
12276 if (m->ValidationQuestion == question)
12277 {
12278 LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
12279 question->qname.c, DNSTypeName(question->qtype));
12280 m->ValidationQuestion = question->next;
12281 }
12282
12283 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12284 question->next = mDNSNULL;
12285
12286 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12287
12288 // And finally, cancel any associated GetZoneData operation that's still running.
12289 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12290 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12291 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12292 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12293 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
12294 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
12295 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
12296 {
12297 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12298 DNSQuestion *q;
12299 for (q = m->Questions; q; q=q->next)
12300 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
12301 if (!q)
12302 {
12303 if (!m->LLQNAT.clientCallback) // Should never happen, but just in case...
12304 {
12305 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12306 }
12307 else
12308 {
12309 LogInfo("Stopping LLQNAT");
12310 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
12311 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
12312 }
12313 }
12314
12315 // If necessary, tell server it can delete this LLQ state
12316 if (question->state == LLQ_Established)
12317 {
12318 question->ReqLease = 0;
12319 sendLLQRefresh(m, question);
12320 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12321 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12322 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12323 // we let that run out its natural course and complete asynchronously.
12324 if (question->tcp)
12325 {
12326 question->tcp->question = mDNSNULL;
12327 question->tcp = mDNSNULL;
12328 }
12329 }
12330 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12331 else if (question->dnsPushServer != mDNSNULL)
12332 {
12333 UnSubscribeToDNSPushNotificationServer(m, question);
12334 }
12335 #endif
12336 }
12337 // wait until we send the refresh above which needs the nta
12338 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
12339
12340 if (question->ValidationRequired && question->DNSSECAuthInfo)
12341 {
12342 LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question->qname.c);
12343 question->DAIFreeCallback(m, question->DNSSECAuthInfo);
12344 question->DNSSECAuthInfo = mDNSNULL;
12345 }
12346 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12347 if (question->metrics.originalQName)
12348 {
12349 mDNSPlatformMemFree(question->metrics.originalQName);
12350 question->metrics.originalQName = mDNSNULL;
12351 }
12352 #endif
12353
12354 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12355 DNS64ResetState(question);
12356 #endif
12357
12358 return(mStatus_NoError);
12359 }
12360
12361 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
12362 {
12363 mStatus status;
12364 mDNS_Lock(m);
12365 status = mDNS_StartQuery_internal(m, question);
12366 mDNS_Unlock(m);
12367 return(status);
12368 }
12369
12370 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
12371 {
12372 mStatus status;
12373 mDNS_Lock(m);
12374 status = mDNS_StopQuery_internal(m, question);
12375 mDNS_Unlock(m);
12376 return(status);
12377 }
12378
12379 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12380 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12381 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12382 // specifically to catch and report if the client callback does try to make API calls
12383 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12384 {
12385 mStatus status;
12386 DNSQuestion *qq;
12387 mDNS_Lock(m);
12388
12389 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12390 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12391
12392 status = mDNS_StopQuery_internal(m, question);
12393 if (status == mStatus_NoError && !qq)
12394 {
12395 const CacheRecord *cr;
12396 CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12397 LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12398 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12399 {
12400 if (cr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameCacheRecordAnswersQuestion(cr, question))
12401 {
12402 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12403 if (question->QuestionCallback)
12404 question->QuestionCallback(m, question, &cr->resrec, mDNSfalse);
12405 }
12406 }
12407 }
12408 mDNS_Unlock(m);
12409 return(status);
12410 }
12411
12412 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12413 {
12414 mStatus status;
12415 mDNS_Lock(m);
12416 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12417 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12418 mDNS_Unlock(m);
12419 return(status);
12420 }
12421
12422 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12423 {
12424 mStatus status = mStatus_BadReferenceErr;
12425 CacheRecord *cr;
12426 mDNS_Lock(m);
12427 cr = FindIdenticalRecordInCache(m, rr);
12428 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12429 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12430 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12431 mDNS_Unlock(m);
12432 return(status);
12433 }
12434
12435 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12436 const domainname *const srv, const domainname *const domain,
12437 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12438 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12439 mDNSQuestionCallback *Callback, void *Context)
12440 {
12441 question->InterfaceID = InterfaceID;
12442 question->flags = flags;
12443 question->qtype = kDNSType_PTR;
12444 question->qclass = kDNSClass_IN;
12445 question->LongLived = mDNStrue;
12446 question->ExpectUnique = mDNSfalse;
12447 question->ForceMCast = ForceMCast;
12448 question->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
12449 question->SuppressUnusable = mDNSfalse;
12450 question->AppendSearchDomains = mDNSfalse;
12451 question->TimeoutQuestion = 0;
12452 question->WakeOnResolve = 0;
12453 question->UseBackgroundTraffic = useBackgroundTrafficClass;
12454 question->ValidationRequired = 0;
12455 question->ValidatingResponse = 0;
12456 question->ProxyQuestion = 0;
12457 question->QuestionCallback = Callback;
12458 question->QuestionContext = Context;
12459
12460 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12461 return(mStatus_BadParamErr);
12462
12463 return(mDNS_StartQuery_internal(m, question));
12464 }
12465
12466 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12467 const domainname *const srv, const domainname *const domain,
12468 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12469 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12470 mDNSQuestionCallback *Callback, void *Context)
12471 {
12472 mStatus status;
12473 mDNS_Lock(m);
12474 status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12475 mDNS_Unlock(m);
12476 return(status);
12477 }
12478
12479
12480 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12481 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12482 {
12483 question->InterfaceID = InterfaceID;
12484 question->flags = 0;
12485 question->qtype = kDNSType_PTR;
12486 question->qclass = kDNSClass_IN;
12487 question->LongLived = mDNSfalse;
12488 question->ExpectUnique = mDNSfalse;
12489 question->ForceMCast = mDNSfalse;
12490 question->ReturnIntermed = mDNSfalse;
12491 question->SuppressUnusable = mDNSfalse;
12492 question->AppendSearchDomains = mDNSfalse;
12493 question->TimeoutQuestion = 0;
12494 question->WakeOnResolve = 0;
12495 question->UseBackgroundTraffic = mDNSfalse;
12496 question->ValidationRequired = 0;
12497 question->ValidatingResponse = 0;
12498 question->ProxyQuestion = 0;
12499 question->pid = mDNSPlatformGetPID();
12500 question->euid = 0;
12501 question->QuestionCallback = Callback;
12502 question->QuestionContext = Context;
12503 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12504 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12505 if (!dom) dom = &localdomain;
12506 if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12507 return(mDNS_StartQuery(m, question));
12508 }
12509
12510 // ***************************************************************************
12511 #if COMPILER_LIKES_PRAGMA_MARK
12512 #pragma mark -
12513 #pragma mark - Responder Functions
12514 #endif
12515
12516 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12517 {
12518 mStatus status;
12519 mDNS_Lock(m);
12520 status = mDNS_Register_internal(m, rr);
12521 mDNS_Unlock(m);
12522 return(status);
12523 }
12524
12525 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12526 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12527 {
12528 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12529 {
12530 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12531 return(mStatus_Invalid);
12532 }
12533
12534 mDNS_Lock(m);
12535
12536 // If TTL is unspecified, leave TTL unchanged
12537 if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12538
12539 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12540 if (rr->NewRData)
12541 {
12542 RData *n = rr->NewRData;
12543 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ...
12544 if (rr->UpdateCallback)
12545 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary
12546 }
12547
12548 rr->NewRData = newrdata;
12549 rr->newrdlength = newrdlength;
12550 rr->UpdateCallback = Callback;
12551
12552 #ifndef UNICAST_DISABLED
12553 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12554 {
12555 mStatus status = uDNS_UpdateRecord(m, rr);
12556 // The caller frees the memory on error, don't retain stale pointers
12557 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12558 mDNS_Unlock(m);
12559 return(status);
12560 }
12561 #endif
12562
12563 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12564 rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12565 CompleteRDataUpdate(m, rr);
12566 else
12567 {
12568 rr->AnnounceCount = InitialAnnounceCount;
12569 InitializeLastAPTime(m, rr);
12570 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12571 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12572 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12573 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12574 if (rr->UpdateCredits <= 5)
12575 {
12576 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12577 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12578 rr->ThisAPInterval *= 4;
12579 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12580 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12581 rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12582 }
12583 rr->resrec.rroriginalttl = newttl;
12584 }
12585
12586 mDNS_Unlock(m);
12587 return(mStatus_NoError);
12588 }
12589
12590 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12591 // the record list and/or question list.
12592 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12593 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12594 {
12595 mStatus status;
12596 mDNS_Lock(m);
12597 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12598 mDNS_Unlock(m);
12599 return(status);
12600 }
12601
12602 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12603 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12604 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12605 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *m, AuthRecord *rr, mStatus result);
12606 #endif
12607
12608 mDNSlocal AuthRecord *GetInterfaceAddressRecord(NetworkInterfaceInfo *intf, mDNSBool forRandHostname)
12609 {
12610 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12611 return(forRandHostname ? &intf->RR_AddrRand : &intf->RR_A);
12612 #else
12613 (void)forRandHostname; // Unused.
12614 return(&intf->RR_A);
12615 #endif
12616 }
12617
12618 mDNSlocal AuthRecord *GetFirstAddressRecordEx(const mDNS *const m, const mDNSBool forRandHostname)
12619 {
12620 NetworkInterfaceInfo *intf;
12621 for (intf = m->HostInterfaces; intf; intf = intf->next)
12622 {
12623 if (!intf->Advertise) continue;
12624 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12625 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
12626 #endif
12627 return(GetInterfaceAddressRecord(intf, forRandHostname));
12628 }
12629 return(mDNSNULL);
12630 }
12631 #define GetFirstAddressRecord(M) GetFirstAddressRecordEx(M, mDNSfalse)
12632
12633 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12634 // (It's a set of records, not a set of interfaces.)
12635 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12636 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool useRandomizedHostname)
12637 #else
12638 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12639 #endif
12640 {
12641 const domainname *hostname;
12642 mDNSRecordCallback *hostnameCallback;
12643 AuthRecord *addrAR;
12644 AuthRecord *ptrAR;
12645 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12646 const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12647 #endif
12648 mDNSu8 addrRecordType;
12649 char buffer[MAX_REVERSE_MAPPING_NAME];
12650
12651 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12652 if (interfaceIsAWDL || useRandomizedHostname)
12653 {
12654 hostname = &m->RandomizedHostname;
12655 hostnameCallback = mDNS_RandomizedHostNameCallback;
12656 }
12657 else
12658 #endif
12659 {
12660 hostname = &m->MulticastHostname;
12661 hostnameCallback = mDNS_HostNameCallback;
12662 }
12663
12664 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12665 if (!interfaceIsAWDL && useRandomizedHostname)
12666 {
12667 addrAR = &set->RR_AddrRand;
12668 ptrAR = mDNSNULL;
12669 }
12670 else
12671 #endif
12672 {
12673 addrAR = &set->RR_A;
12674 ptrAR = &set->RR_PTR;
12675 }
12676 if (addrAR->resrec.RecordType != kDNSRecordTypeUnregistered) return;
12677
12678 addrRecordType = set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
12679 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12680 if (hostname == &m->RandomizedHostname) addrRecordType = kDNSRecordTypeKnownUnique;
12681 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12682 "AdvertiseInterface: Advertising " PUB_S " hostname on interface " PUB_S,
12683 (hostname == &m->RandomizedHostname) ? "randomized" : "normal", set->ifname);
12684 #else
12685 LogInfo("AdvertiseInterface: Advertising for ifname %s", set->ifname);
12686 #endif
12687
12688 // Send dynamic update for non-linklocal IPv4 Addresses
12689 mDNS_SetupResourceRecord(addrAR, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, addrRecordType, AuthRecordAny, hostnameCallback, set);
12690 if (ptrAR) mDNS_SetupResourceRecord(ptrAR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12691
12692 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12693 addrAR->AllowRemoteQuery = mDNStrue;
12694 if (ptrAR) ptrAR->AllowRemoteQuery = mDNStrue;
12695 #endif
12696 // 1. Set up Address record to map from host name ("foo.local.") to IP address
12697 // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12698 AssignDomainName(&addrAR->namestorage, hostname);
12699 if (set->ip.type == mDNSAddrType_IPv4)
12700 {
12701 addrAR->resrec.rrtype = kDNSType_A;
12702 addrAR->resrec.rdata->u.ipv4 = set->ip.ip.v4;
12703 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12704 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12705 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12706 }
12707 else if (set->ip.type == mDNSAddrType_IPv6)
12708 {
12709 int i;
12710 addrAR->resrec.rrtype = kDNSType_AAAA;
12711 addrAR->resrec.rdata->u.ipv6 = set->ip.ip.v6;
12712 for (i = 0; i < 16; i++)
12713 {
12714 static const char hexValues[] = "0123456789ABCDEF";
12715 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12716 buffer[i * 4 + 1] = '.';
12717 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12718 buffer[i * 4 + 3] = '.';
12719 }
12720 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12721 }
12722
12723 if (ptrAR)
12724 {
12725 MakeDomainNameFromDNSNameString(&ptrAR->namestorage, buffer);
12726 ptrAR->AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12727 ptrAR->ForceMCast = mDNStrue; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12728 }
12729
12730 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12731 addrAR->RRSet = interfaceIsAWDL ? addrAR : GetFirstAddressRecordEx(m, useRandomizedHostname);
12732 #else
12733 addrAR->RRSet = GetFirstAddressRecord(m);
12734 #endif
12735 if (!addrAR->RRSet) addrAR->RRSet = addrAR;
12736 mDNS_Register_internal(m, addrAR);
12737 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Initialized RRSet for " PRI_S, ARDisplayString(m, addrAR));
12738 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "RRSet: " PRI_S, ARDisplayString(m, addrAR->RRSet));
12739 if (ptrAR) mDNS_Register_internal(m, ptrAR);
12740
12741 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12742 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12743 D2D_start_advertising_interface(set);
12744 #endif
12745 }
12746
12747 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set)
12748 {
12749 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12750 if (mDNSPlatformInterfaceIsAWDL(set->InterfaceID))
12751 {
12752 if ((m->AutoTargetAWDLIncludedCount > 0) || (m->AutoTargetAWDLOnlyCount > 0))
12753 {
12754 AdvertiseInterface(m, set, mDNSfalse);
12755 }
12756 }
12757 else
12758 {
12759 if (m->AutoTargetServices > 0) AdvertiseInterface(m, set, mDNSfalse);
12760 if (m->AutoTargetAWDLIncludedCount > 0) AdvertiseInterface(m, set, mDNStrue);
12761 }
12762 #else
12763 if (m->AutoTargetServices > 0) AdvertiseInterface(m, set);
12764 #endif
12765 }
12766
12767 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags)
12768 {
12769 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12770 const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12771 #endif
12772
12773 // Unregister these records.
12774 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12775 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12776 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12777 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12778 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12779 if ((!interfaceIsAWDL && (flags & kDeadvertiseFlag_NormalHostname)) ||
12780 ( interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname)))
12781 #else
12782 if (flags & kDeadvertiseFlag_NormalHostname)
12783 #endif
12784 {
12785 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12786 "DeadvertiseInterface: Deadvertising " PUB_S " hostname on interface " PUB_S,
12787 (flags & kDeadvertiseFlag_RandHostname) ? "randomized" : "normal", set->ifname);
12788 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12789 D2D_stop_advertising_interface(set);
12790 #endif
12791 if (set->RR_A.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal);
12792 if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12793 }
12794 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12795 if (!interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname))
12796 {
12797 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12798 "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S, set->ifname);
12799 AuthRecord *const ar = &set->RR_AddrRand;
12800 if (ar->resrec.RecordType) mDNS_Deregister_internal(m, ar, mDNS_Dereg_normal);
12801 }
12802 #endif
12803 }
12804
12805 // Change target host name for record.
12806 mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr)
12807 {
12808 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12809 // If this record was also registered with any D2D plugins, stop advertising
12810 // the version with the old host name.
12811 D2D_stop_advertising_record(rr);
12812 #endif
12813
12814 SetTargetToHostName(m, rr);
12815
12816 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12817 // Advertise the record with the updated host name with the D2D plugins if appropriate.
12818 D2D_start_advertising_record(rr);
12819 #endif
12820 }
12821
12822 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m, DeadvertiseFlags flags)
12823 {
12824 NetworkInterfaceInfo *intf;
12825 for (intf = m->HostInterfaces; intf; intf = intf->next)
12826 {
12827 if (intf->Advertise) DeadvertiseInterface(m, intf, flags);
12828 }
12829 }
12830
12831 mDNSexport void mDNS_SetFQDN(mDNS *const m)
12832 {
12833 domainname newmname;
12834 AuthRecord *rr;
12835 newmname.c[0] = 0;
12836
12837 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12838 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12839
12840 mDNS_Lock(m);
12841
12842 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12843 else
12844 {
12845 AssignDomainName(&m->MulticastHostname, &newmname);
12846 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_NormalHostname);
12847 AdvertiseNecessaryInterfaceRecords(m);
12848 }
12849
12850 // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12851 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12852 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12853
12854 mDNS_Unlock(m);
12855 }
12856
12857 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12858 {
12859 (void)rr; // Unused parameter
12860
12861 #if MDNS_DEBUGMSGS
12862 {
12863 char *msg = "Unknown result";
12864 if (result == mStatus_NoError) msg = "Name registered";
12865 else if (result == mStatus_NameConflict) msg = "Name conflict";
12866 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12867 }
12868 #endif
12869
12870 if (result == mStatus_NoError)
12871 {
12872 // Notify the client that the host name is successfully registered
12873 if (m->MainCallback)
12874 m->MainCallback(m, mStatus_NoError);
12875 }
12876 else if (result == mStatus_NameConflict)
12877 {
12878 domainlabel oldlabel = m->hostlabel;
12879
12880 // 1. First give the client callback a chance to pick a new name
12881 if (m->MainCallback)
12882 m->MainCallback(m, mStatus_NameConflict);
12883
12884 // 2. If the client callback didn't do it, add (or increment) an index ourselves
12885 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12886 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12887 if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12888 IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12889
12890 // 3. Generate the FQDNs from the hostlabel,
12891 // and make sure all SRV records, etc., are updated to reference our new hostname
12892 mDNS_SetFQDN(m);
12893 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12894 }
12895 else if (result == mStatus_MemFree)
12896 {
12897 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12898 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12899 debugf("mDNS_HostNameCallback: MemFree (ignored)");
12900 }
12901 else
12902 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c);
12903 }
12904
12905 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12906 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *const m, AuthRecord *const addrRecord, const mStatus result)
12907 {
12908 (void)addrRecord; // Unused parameter
12909
12910 if (result == mStatus_NameConflict)
12911 {
12912 AuthRecord *rr;
12913 domainlabel newUUIDLabel;
12914
12915 GetRandomUUIDLabel(&newUUIDLabel);
12916 if (SameDomainLabel(newUUIDLabel.c, m->RandomizedHostname.c))
12917 {
12918 IncrementLabelSuffix(&newUUIDLabel, mDNSfalse);
12919 }
12920
12921 mDNS_Lock(m);
12922
12923 m->RandomizedHostname.c[0] = 0;
12924 AppendDomainLabel(&m->RandomizedHostname, &newUUIDLabel);
12925 AppendLiteralLabelString(&m->RandomizedHostname, "local");
12926
12927 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_RandHostname);
12928 AdvertiseNecessaryInterfaceRecords(m);
12929 for (rr = m->ResourceRecords; rr; rr = rr->next)
12930 {
12931 if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12932 }
12933 for (rr = m->DuplicateRecords; rr; rr = rr->next)
12934 {
12935 if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12936 }
12937
12938 mDNS_Unlock(m);
12939 }
12940 }
12941 #endif
12942
12943 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12944 {
12945 NetworkInterfaceInfo *intf;
12946 active->IPv4Available = mDNSfalse;
12947 active->IPv6Available = mDNSfalse;
12948 for (intf = m->HostInterfaces; intf; intf = intf->next)
12949 if (intf->InterfaceID == active->InterfaceID)
12950 {
12951 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12952 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12953 }
12954 }
12955
12956 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12957 {
12958 AuthRecord *rr;
12959 LogInfo("RestartRecordGetZoneData: ResourceRecords");
12960 for (rr = m->ResourceRecords; rr; rr=rr->next)
12961 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12962 {
12963 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12964 // Zero out the updateid so that if we have a pending response from the server, it won't
12965 // be accepted as a valid response. If we accept the response, we might free the new "nta"
12966 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12967 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12968 }
12969 }
12970
12971 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12972 {
12973 int i;
12974 // We initialize ThisQInterval to -1 indicating that the question has not been started
12975 // yet. If the question (browse) is started later during interface registration, it will
12976 // be stopped during interface deregistration. We can't sanity check to see if the
12977 // question has been stopped or not before initializing it to -1 because we need to
12978 // initialize it to -1 the very first time.
12979
12980 set->NetWakeBrowse.ThisQInterval = -1;
12981 for (i=0; i<3; i++)
12982 {
12983 set->NetWakeResolve[i].ThisQInterval = -1;
12984 set->SPSAddr[i].type = mDNSAddrType_None;
12985 }
12986 set->NextSPSAttempt = -1;
12987 set->NextSPSAttemptTime = m->timenow;
12988 }
12989
12990 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12991 {
12992 NetworkInterfaceInfo *p = m->HostInterfaces;
12993 while (p && p != set) p=p->next;
12994 if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12995
12996 if (set->InterfaceActive)
12997 {
12998 LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12999 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
13000 }
13001 }
13002
13003 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
13004 {
13005 NetworkInterfaceInfo *p = m->HostInterfaces;
13006 while (p && p != set) p=p->next;
13007 if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
13008
13009 // Note: We start the browse only if the interface is NetWake capable and we use this to
13010 // stop the resolves also. Hence, the resolves should not be started without the browse
13011 // being started i.e, resolves should not happen unless NetWake capable which is
13012 // guaranteed by BeginSleepProcessing.
13013 if (set->NetWakeBrowse.ThisQInterval >= 0)
13014 {
13015 int i;
13016 LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
13017
13018 // Stop our browse and resolve operations
13019 mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
13020 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
13021
13022 // Make special call to the browse callback to let it know it can to remove all records for this interface
13023 if (m->SPSBrowseCallback)
13024 {
13025 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
13026 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, mDNSfalse);
13027 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
13028 }
13029
13030 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
13031 // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
13032 InitializeNetWakeState(m, set);
13033 }
13034 }
13035
13036 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13037 {
13038 AuthRecord *rr;
13039 mDNSBool FirstOfType = mDNStrue;
13040 NetworkInterfaceInfo **p = &m->HostInterfaces;
13041
13042 if (!set->InterfaceID)
13043 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
13044
13045 if (!mDNSAddressIsValidNonZero(&set->mask))
13046 { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
13047
13048 mDNS_Lock(m);
13049
13050 // Assume this interface will be active now, unless we find a duplicate already in the list
13051 set->InterfaceActive = mDNStrue;
13052 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
13053 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
13054
13055 InitializeNetWakeState(m, set);
13056
13057 // Scan list to see if this InterfaceID is already represented
13058 while (*p)
13059 {
13060 if (*p == set)
13061 {
13062 LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
13063 mDNS_Unlock(m);
13064 return(mStatus_AlreadyRegistered);
13065 }
13066
13067 if ((*p)->InterfaceID == set->InterfaceID)
13068 {
13069 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13070 set->InterfaceActive = mDNSfalse;
13071 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
13072 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
13073 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
13074 }
13075
13076 p=&(*p)->next;
13077 }
13078
13079 set->next = mDNSNULL;
13080 *p = set;
13081
13082 if (set->Advertise) AdvertiseInterfaceIfNeeded(m, set);
13083
13084 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
13085 "mDNS_RegisterInterface: InterfaceID %u " PUB_S " (" PRI_IP_ADDR ") " PUB_S,
13086 IIDPrintable(set->InterfaceID), set->ifname, &set->ip, set->InterfaceActive ?
13087 "not represented in list; marking active and retriggering queries" :
13088 "already represented in list; marking inactive for now");
13089
13090 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
13091
13092 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13093 // giving the false impression that there's an active representative of this interface when there really isn't.
13094 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13095 // even if we believe that we previously had an active representative of this interface.
13096 if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
13097 {
13098 DNSQuestion *q;
13099 // Normally, after an interface comes up, we pause half a second before beginning probing.
13100 // This is to guard against cases where there's rapid interface changes, where we could be confused by
13101 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13102 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13103 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13104 // and think it's a conflicting answer to our probe.
13105 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13106 mDNSs32 probedelay;
13107 mDNSu8 numannounce;
13108 switch (activationSpeed)
13109 {
13110 case FastActivation:
13111 probedelay = (mDNSs32)0;
13112 numannounce = InitialAnnounceCount;
13113 LogMsg("mDNS_RegisterInterface: Using fast activation for DirectLink interface %s (%#a)", set->ifname, &set->ip);
13114 break;
13115
13116 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13117 case SlowActivation:
13118 probedelay = mDNSPlatformOneSecond * 5;
13119 numannounce = (mDNSu8)1;
13120 LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a), doing slow activation", set->ifname, &set->ip);
13121 m->mDNSStats.InterfaceUpFlap++;
13122 break;
13123 #endif
13124
13125 case NormalActivation:
13126 default:
13127 probedelay = mDNSPlatformOneSecond / 2;
13128 numannounce = InitialAnnounceCount;
13129 break;
13130 }
13131
13132 LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
13133
13134 // No probe or sending suppression on DirectLink type interfaces.
13135 if (activationSpeed == FastActivation)
13136 {
13137 m->SuppressSending = 0;
13138 m->SuppressProbes = 0;
13139 }
13140 else
13141 {
13142 // Use a small amount of randomness:
13143 // In the case of a network administrator turning on an Ethernet hub so that all the
13144 // connected machines establish link at exactly the same time, we don't want them all
13145 // to go and hit the network with identical queries at exactly the same moment.
13146 // We set a random delay of up to InitialQuestionInterval (1/3 second).
13147 // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13148 // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13149 // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13150 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13151 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13152 if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
13153
13154 if (m->SuppressProbes == 0 ||
13155 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
13156 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
13157 }
13158
13159 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13160 // it here also handles the wake up case as the network link comes UP after waking causing
13161 // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13162 // that the network link comes UP after 60 seconds and we never set the OWNER option
13163 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
13164 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNS_RegisterInterface: Setting AnnounceOwner");
13165
13166 m->mDNSStats.InterfaceUp++;
13167 for (q = m->Questions; q; q=q->next) // Scan our list of questions
13168 {
13169 if (mDNSOpaque16IsZero(q->TargetQID))
13170 {
13171 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) // If non-specific Q, or Q on this specific interface,
13172 { // then reactivate this question
13173 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13174 // If flapping, delay between first and second queries is nine seconds instead of one second
13175 mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
13176 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
13177 mDNSs32 qdelay = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0;
13178 if (dodelay) LogInfo("No cache records expired for %##s (%s); delaying questions by %d seconds", q->qname.c, DNSTypeName(q->qtype), qdelay);
13179 #else
13180 mDNSs32 initial = InitialQuestionInterval;
13181 mDNSs32 qdelay = 0;
13182 #endif
13183
13184 if (!q->ThisQInterval || q->ThisQInterval > initial)
13185 {
13186 q->ThisQInterval = initial;
13187 q->RequestUnicast = kDefaultRequestUnicastCount;
13188 }
13189 q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
13190 q->RecentAnswerPkts = 0;
13191 SetNextQueryTime(m,q);
13192 }
13193 }
13194 }
13195
13196 // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13197 // we now need them to re-probe if necessary, and then re-announce.
13198 for (rr = m->ResourceRecords; rr; rr=rr->next)
13199 {
13200 if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
13201 {
13202 mDNSCoreRestartRegistration(m, rr, numannounce);
13203 }
13204 }
13205 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
13206 DNSSECProbe(m);
13207 #endif
13208 }
13209
13210 RestartRecordGetZoneData(m);
13211
13212 mDNS_UpdateAllowSleep(m);
13213
13214 mDNS_Unlock(m);
13215 return(mStatus_NoError);
13216 }
13217
13218 mDNSlocal void AdjustAddressRecordSetsEx(mDNS *const m, NetworkInterfaceInfo *removedIntf, mDNSBool forRandHostname)
13219 {
13220 NetworkInterfaceInfo *intf;
13221 const AuthRecord *oldAR;
13222 AuthRecord *newAR;
13223 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13224 if (mDNSPlatformInterfaceIsAWDL(removedIntf->InterfaceID)) return;
13225 #endif
13226 oldAR = GetInterfaceAddressRecord(removedIntf, forRandHostname);
13227 newAR = GetFirstAddressRecordEx(m, forRandHostname);
13228 for (intf = m->HostInterfaces; intf; intf = intf->next)
13229 {
13230 AuthRecord *ar;
13231 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13232 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
13233 #endif
13234 ar = GetInterfaceAddressRecord(intf, forRandHostname);
13235 if (ar->RRSet == oldAR)
13236 {
13237 ar->RRSet = newAR ? newAR : ar;
13238 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Changed RRSet for " PRI_S, ARDisplayString(m, ar));
13239 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "New RRSet: " PRI_S, ARDisplayString(m, ar->RRSet));
13240 }
13241 }
13242 }
13243 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13244 #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue)
13245 #endif
13246 #define AdjustAddressRecordSets(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse)
13247
13248 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13249 // the record list and/or question list.
13250 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13251 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13252 {
13253 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13254 (void)activationSpeed; // Unused parameter
13255 #endif
13256 NetworkInterfaceInfo **p = &m->HostInterfaces;
13257 mDNSBool revalidate = mDNSfalse;
13258 NetworkInterfaceInfo *intf;
13259
13260 mDNS_Lock(m);
13261
13262 // Find this record in our list
13263 while (*p && *p != set) p=&(*p)->next;
13264 if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
13265
13266 mDNS_DeactivateNetWake_internal(m, set);
13267
13268 // Unlink this record from our list
13269 *p = (*p)->next;
13270 set->next = mDNSNULL;
13271
13272 if (!set->InterfaceActive)
13273 {
13274 // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13275 for (intf = m->HostInterfaces; intf; intf = intf->next)
13276 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13277 UpdateInterfaceProtocols(m, intf);
13278 }
13279 else
13280 {
13281 intf = FirstInterfaceForID(m, set->InterfaceID);
13282 if (intf)
13283 {
13284 LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13285 " making it active", IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13286 if (intf->InterfaceActive)
13287 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
13288 intf->InterfaceActive = mDNStrue;
13289 UpdateInterfaceProtocols(m, intf);
13290
13291 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13292
13293 // See if another representative *of the same type* exists. If not, we mave have gone from
13294 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13295 for (intf = m->HostInterfaces; intf; intf = intf->next)
13296 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13297 break;
13298 if (!intf) revalidate = mDNStrue;
13299 }
13300 else
13301 {
13302 mDNSu32 slot;
13303 CacheGroup *cg;
13304 CacheRecord *rr;
13305 DNSQuestion *q;
13306
13307 LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13308 " marking questions etc. dormant", IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13309
13310 m->mDNSStats.InterfaceDown++;
13311
13312 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13313 if (set->McastTxRx && (activationSpeed == SlowActivation))
13314 {
13315 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
13316 m->mDNSStats.InterfaceDownFlap++;
13317 }
13318 #endif
13319
13320 // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13321 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13322 for (q = m->Questions; q; q=q->next)
13323 {
13324 if (mDNSOpaque16IsZero(q->TargetQID)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13325 {
13326 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13327 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13328 {
13329 q->FlappingInterface2 = q->FlappingInterface1;
13330 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away
13331 }
13332 }
13333 }
13334
13335 // 2. Flush any cache records received on this interface
13336 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records
13337 FORALL_CACHERECORDS(slot, cg, rr)
13338 {
13339 if (rr->resrec.InterfaceID == set->InterfaceID)
13340 {
13341 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13342 // If this interface is deemed flapping,
13343 // postpone deleting the cache records in case the interface comes back again
13344 if (set->McastTxRx && (activationSpeed == SlowActivation))
13345 {
13346 // For a flapping interface we want these records to go away after
13347 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13348 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13349 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13350 // if the interface does come back, any relevant questions will be reactivated anyway
13351 rr->UnansweredQueries = MaxUnansweredQueries;
13352 }
13353 else
13354 #endif
13355 {
13356 rr->resrec.mortality = Mortality_Mortal;
13357 mDNS_PurgeCacheResourceRecord(m, rr);
13358 }
13359 }
13360 }
13361 }
13362 }
13363
13364 // If we still have address records referring to this one, update them.
13365 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13366 // so the call to AdjustAddressRecordSets*() won’t accidentally find it.
13367 AdjustAddressRecordSets(m, set);
13368 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13369 AdjustAddressRecordSetsForRandHostname(m, set);
13370 #endif
13371
13372 // If we were advertising on this interface, deregister those address and reverse-lookup records now
13373 if (set->Advertise) DeadvertiseInterface(m, set, kDeadvertiseFlag_All);
13374
13375 // If we have any cache records received on this interface that went away, then re-verify them.
13376 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13377 // giving the false impression that there's an active representative of this interface when there really isn't.
13378 // Don't need to do this when shutting down, because *all* interfaces are about to go away
13379 if (revalidate && !m->ShutdownTime)
13380 {
13381 mDNSu32 slot;
13382 CacheGroup *cg;
13383 CacheRecord *rr;
13384 FORALL_CACHERECORDS(slot, cg, rr)
13385 if (rr->resrec.InterfaceID == set->InterfaceID)
13386 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13387 }
13388
13389 mDNS_UpdateAllowSleep(m);
13390
13391 mDNS_Unlock(m);
13392 }
13393
13394 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13395 {
13396 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13397 (void)m; // Unused parameter
13398
13399 #if MDNS_DEBUGMSGS
13400 {
13401 char *msg = "Unknown result";
13402 if (result == mStatus_NoError) msg = "Name Registered";
13403 else if (result == mStatus_NameConflict) msg = "Name Conflict";
13404 else if (result == mStatus_MemFree) msg = "Memory Free";
13405 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13406 }
13407 #endif
13408
13409 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13410 if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13411
13412 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13413 if (result == mStatus_NameConflict)
13414 {
13415 sr->Conflict = mDNStrue; // Record that this service set had a conflict
13416 mDNS_DeregisterService(m, sr); // Unlink the records from our list
13417 return;
13418 }
13419
13420 if (result == mStatus_MemFree)
13421 {
13422 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13423 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13424 // every record is finished cleaning up.
13425 mDNSu32 i;
13426 ExtraResourceRecord *e = sr->Extras;
13427
13428 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13429 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13430 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13431 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13432 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13433
13434 while (e)
13435 {
13436 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13437 e = e->next;
13438 }
13439
13440 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13441 // then we can now report the NameConflict to the client
13442 if (sr->Conflict) result = mStatus_NameConflict;
13443
13444 }
13445
13446 LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13447 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13448 // function is allowed to do anything, including deregistering this service and freeing its memory.
13449 if (sr->ServiceCallback)
13450 sr->ServiceCallback(m, sr, result);
13451 }
13452
13453 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13454 {
13455 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13456 if (sr->ServiceCallback)
13457 sr->ServiceCallback(m, sr, result);
13458 }
13459
13460
13461 // Derive AuthRecType from the kDNSServiceFlags* values.
13462 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13463 {
13464 AuthRecType artype;
13465
13466 if (InterfaceID == mDNSInterface_LocalOnly)
13467 artype = AuthRecordLocalOnly;
13468 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13469 artype = AuthRecordP2P;
13470 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
13471 && (flags & kDNSServiceFlagsIncludeAWDL))
13472 artype = AuthRecordAnyIncludeAWDLandP2P;
13473 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
13474 artype = AuthRecordAnyIncludeP2P;
13475 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
13476 artype = AuthRecordAnyIncludeAWDL;
13477 else
13478 artype = AuthRecordAny;
13479
13480 return artype;
13481 }
13482
13483 // Note:
13484 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13485 // Type is service type (e.g. "_ipp._tcp.")
13486 // Domain is fully qualified domain name (i.e. ending with a null label)
13487 // We always register a TXT, even if it is empty (so that clients are not
13488 // left waiting forever looking for a nonexistent record.)
13489 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13490 // then the default host name (m->MulticastHostname) is automatically used
13491 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13492 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13493 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13494 const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13495 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13496 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13497 {
13498 mStatus err;
13499 mDNSu32 i;
13500 AuthRecType artype;
13501 mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13502
13503 sr->ServiceCallback = Callback;
13504 sr->ServiceContext = Context;
13505 sr->Conflict = mDNSfalse;
13506
13507 sr->Extras = mDNSNULL;
13508 sr->NumSubTypes = NumSubTypes;
13509 sr->SubTypes = SubTypes;
13510 sr->flags = flags;
13511
13512 artype = setAuthRecType(InterfaceID, flags);
13513
13514 // Initialize the AuthRecord objects to sane values
13515 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13516 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13517 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13518
13519 if (flags & kDNSServiceFlagsWakeOnlyService)
13520 {
13521 sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13522 }
13523
13524 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, recordType, artype, ServiceCallback, sr);
13525 mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr);
13526
13527 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13528 if (mDNSIPPortIsZero(port))
13529 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13530
13531 // If the caller is registering an oversized TXT record,
13532 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13533 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13534 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13535
13536 // Set up the record names
13537 // For now we only create an advisory record for the main type, not for subtypes
13538 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13539 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13540 return(mStatus_BadParamErr);
13541 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13542 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13543 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13544
13545 // 1. Set up the ADV record rdata to advertise our service type
13546 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13547
13548 // 2. Set up the PTR record rdata to point to our service name
13549 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13550 // Note: uDNS registration code assumes that Additional1 points to the SRV record
13551 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13552 sr->RR_PTR.Additional1 = &sr->RR_SRV;
13553 sr->RR_PTR.Additional2 = &sr->RR_TXT;
13554
13555 // 2a. Set up any subtype PTRs to point to our service name
13556 // If the client is using subtypes, it is the client's responsibility to have
13557 // already set the first label of the record name to the subtype being registered
13558 for (i=0; i<NumSubTypes; i++)
13559 {
13560 domainname st;
13561 AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13562 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13563 AppendDomainName(&st, type);
13564 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13565 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13566 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13567 sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13568 sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13569 }
13570
13571 // 3. Set up the SRV record rdata.
13572 sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13573 sr->RR_SRV.resrec.rdata->u.srv.weight = 0;
13574 sr->RR_SRV.resrec.rdata->u.srv.port = port;
13575
13576 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13577 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13578 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13579
13580 // 4. Set up the TXT record rdata,
13581 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13582 // Note: uDNS registration code assumes that DependentOn points to the SRV record
13583 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13584 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13585 {
13586 sr->RR_TXT.resrec.rdlength = txtlen;
13587 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13588 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13589 }
13590 sr->RR_TXT.DependentOn = &sr->RR_SRV;
13591
13592 mDNS_Lock(m);
13593 // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13594 // that if the SRV cannot find a target, rest of the records that belong to this service
13595 // will not be activated.
13596 err = mDNS_Register_internal(m, &sr->RR_SRV);
13597 // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13598 // any list and hence no need to deregister. We could probably do similar checks for other
13599 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13600 if (err)
13601 {
13602 mDNS_Unlock(m);
13603 return err;
13604 }
13605 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13606 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13607 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13608 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13609 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13610 // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13611 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13612 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13613 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13614
13615 mDNS_Unlock(m);
13616
13617 if (err) mDNS_DeregisterService(m, sr);
13618 return(err);
13619 }
13620
13621 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13622 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags)
13623 {
13624 ExtraResourceRecord **e;
13625 mStatus status;
13626 AuthRecType artype;
13627 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13628 ResourceRecord *rr;
13629
13630 artype = setAuthRecType(InterfaceID, flags);
13631
13632 extra->next = mDNSNULL;
13633 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13634 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13635 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13636
13637 mDNS_Lock(m);
13638 rr = mDNSNULL;
13639 if (extra->r.resrec.rrtype == kDNSType_TXT)
13640 {
13641 if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec;
13642 }
13643 else if (extra->r.resrec.rrtype == kDNSType_SRV)
13644 {
13645 if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec;
13646 }
13647
13648 if (!rr)
13649 {
13650 ExtraResourceRecord *srExtra;
13651
13652 for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next)
13653 {
13654 if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask))
13655 {
13656 rr = &srExtra->r.resrec;
13657 break;
13658 }
13659 }
13660 }
13661
13662 if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl))
13663 {
13664 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13665 extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec));
13666 extra->r.resrec.rroriginalttl = rr->rroriginalttl;
13667 }
13668
13669 e = &sr->Extras;
13670 while (*e) e = &(*e)->next;
13671
13672 extra->r.DependentOn = &sr->RR_SRV;
13673
13674 debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13675 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13676
13677 status = mDNS_Register_internal(m, &extra->r);
13678 if (status == mStatus_NoError) *e = extra;
13679
13680 mDNS_Unlock(m);
13681 return(status);
13682 }
13683
13684 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13685 mDNSRecordCallback MemFreeCallback, void *Context)
13686 {
13687 ExtraResourceRecord **e;
13688 mStatus status;
13689
13690 mDNS_Lock(m);
13691 e = &sr->Extras;
13692 while (*e && *e != extra) e = &(*e)->next;
13693 if (!*e)
13694 {
13695 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13696 status = mStatus_BadReferenceErr;
13697 }
13698 else
13699 {
13700 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13701 extra->r.RecordCallback = MemFreeCallback;
13702 extra->r.RecordContext = Context;
13703 *e = (*e)->next;
13704 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13705 }
13706 mDNS_Unlock(m);
13707 return(status);
13708 }
13709
13710 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13711 {
13712 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13713 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13714 domainlabel name1, name2;
13715 domainname type, domain;
13716 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13717 ExtraResourceRecord *extras = sr->Extras;
13718 mStatus err;
13719
13720 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13721 if (!newname)
13722 {
13723 name2 = name1;
13724 IncrementLabelSuffix(&name2, mDNStrue);
13725 newname = &name2;
13726 }
13727
13728 if (SameDomainName(&domain, &localdomain))
13729 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13730 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13731
13732 // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13733 // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13734 if (sr->RR_TXT.NewRData) CompleteRDataUpdate(m, &sr->RR_TXT);
13735 err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13736 host, sr->RR_SRV.resrec.rdata->u.srv.port,
13737 (sr->RR_TXT.resrec.rdata != &sr->RR_TXT.rdatastorage) ? sr->RR_TXT.resrec.rdata : mDNSNULL,
13738 sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13739 sr->SubTypes, sr->NumSubTypes,
13740 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13741
13742 // mDNS_RegisterService() just reset sr->Extras to NULL.
13743 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13744 // through the old list of extra records, and re-add them to our freshly created service registration
13745 while (!err && extras)
13746 {
13747 ExtraResourceRecord *e = extras;
13748 extras = extras->next;
13749 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13750 }
13751
13752 return(err);
13753 }
13754
13755 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13756 // which may change the record list and/or question list.
13757 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13758 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13759 {
13760 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13761 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13762
13763 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13764 {
13765 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13766 return(mStatus_BadReferenceErr);
13767 }
13768 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13769 {
13770 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13771 // Avoid race condition:
13772 // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13773 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13774 // If the client happens to deregister the service in the middle of that process, then
13775 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13776 // instead of incorrectly promoting it to mStatus_NameConflict.
13777 // This race condition is exposed particularly when the conformance test generates
13778 // a whole batch of simultaneous conflicts across a range of services all advertised
13779 // using the same system default name, and if we don't take this precaution then
13780 // we end up incrementing m->nicelabel multiple times instead of just once.
13781 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13782 sr->Conflict = mDNSfalse;
13783 return(mStatus_NoError);
13784 }
13785 else
13786 {
13787 mDNSu32 i;
13788 mStatus status;
13789 ExtraResourceRecord *e;
13790 mDNS_Lock(m);
13791 e = sr->Extras;
13792
13793 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13794 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13795 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13796 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13797 mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13798
13799 // We deregister all of the extra records, but we leave the sr->Extras list intact
13800 // in case the client wants to do a RenameAndReregister and reinstate the registration
13801 while (e)
13802 {
13803 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13804 e = e->next;
13805 }
13806
13807 for (i=0; i<sr->NumSubTypes; i++)
13808 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13809
13810 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13811 mDNS_Unlock(m);
13812 return(status);
13813 }
13814 }
13815
13816 // Create a registration that asserts that no such service exists with this name.
13817 // This can be useful where there is a given function is available through several protocols.
13818 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13819 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13820 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13821 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13822 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13823 const domainlabel *const name, const domainname *const type, const domainname *const domain,
13824 const domainname *const host,
13825 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13826 {
13827 AuthRecType artype;
13828
13829 artype = setAuthRecType(InterfaceID, flags);
13830
13831 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13832 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13833 rr->resrec.rdata->u.srv.priority = 0;
13834 rr->resrec.rdata->u.srv.weight = 0;
13835 rr->resrec.rdata->u.srv.port = zeroIPPort;
13836 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13837 else rr->AutoTarget = Target_AutoHost;
13838 return(mDNS_Register(m, rr));
13839 }
13840
13841 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13842 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13843 {
13844 AuthRecType artype;
13845
13846 if (InterfaceID == mDNSInterface_LocalOnly)
13847 artype = AuthRecordLocalOnly;
13848 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13849 artype = AuthRecordP2P;
13850 else
13851 artype = AuthRecordAny;
13852 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13853 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13854 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13855 return(mDNS_Register(m, rr));
13856 }
13857
13858 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13859 {
13860 AuthRecord *r;
13861 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13862 return mDNSfalse;
13863 }
13864
13865 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13866 {
13867 DNSQuestion *q;
13868 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13869 return mDNSfalse;
13870 }
13871
13872 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13873 {
13874 mDNSOpaque16 id;
13875 int i;
13876
13877 for (i=0; i<10; i++)
13878 {
13879 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13880 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13881 }
13882
13883 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13884
13885 return id;
13886 }
13887
13888 // ***************************************************************************
13889 #if COMPILER_LIKES_PRAGMA_MARK
13890 #pragma mark -
13891 #pragma mark - Sleep Proxy Server
13892 #endif
13893
13894 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13895 {
13896 // If we see an ARP from a machine we think is sleeping, then either
13897 // (i) the machine has woken, or
13898 // (ii) it's just a stray old packet from before the machine slept
13899 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13900 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13901 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13902 // If it was a stray old packet, then after 10 seconds we'll probe again and then start answering ARPs again. In this case we *do*
13903 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13904 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13905
13906 rr->resrec.RecordType = kDNSRecordTypeUnique;
13907 rr->ProbeCount = DefaultProbeCountForTypeUnique;
13908 rr->ProbeRestartCount++;
13909
13910 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13911 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13912 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13913 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13914 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13915 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13916 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13917 InitializeLastAPTime(m, rr);
13918 else
13919 {
13920 rr->AnnounceCount = InitialAnnounceCount;
13921 rr->ThisAPInterval = mDNSPlatformOneSecond;
13922 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13923 SetNextAnnounceProbeTime(m, rr);
13924 }
13925 }
13926
13927 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13928 {
13929 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13930 AuthRecord *rr;
13931 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13932 if (!intf) return;
13933
13934 mDNS_Lock(m);
13935
13936 // Pass 1:
13937 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13938 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13939 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13940 // The times we might need to react to an ARP Announcement are:
13941 // (i) as an indication that the host in question has not gone to sleep yet (so we should delay beginning to proxy for it) or
13942 // (ii) if it's a conflicting Announcement from another host
13943 // -- and we check for these in Pass 2 below.
13944 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13945 {
13946 for (rr = m->ResourceRecords; rr; rr=rr->next)
13947 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13948 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13949 {
13950 static const char msg1[] = "ARP Req from owner -- re-probing";
13951 static const char msg2[] = "Ignoring ARP Request from ";
13952 static const char msg3[] = "Creating Local ARP Cache entry ";
13953 static const char msg4[] = "Answering ARP Request from ";
13954 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13955 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
13956 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4;
13957 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13958 intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b,
13959 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13960 if (msg == msg1)
13961 {
13962 if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13963 RestartARPProbing(m, rr);
13964 else
13965 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13966 }
13967 else if (msg == msg3)
13968 {
13969 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13970 }
13971 else if (msg == msg4)
13972 {
13973 SendARP(m, 2, rr, (mDNSv4Addr *)arp->tpa.b, &arp->sha, (mDNSv4Addr *)arp->spa.b, &arp->sha);
13974 }
13975 }
13976 }
13977
13978 // Pass 2:
13979 // For all types of ARP packet we check the Sender IP address to make sure it doesn't conflict with any AddressProxy record we're holding.
13980 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13981 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13982 // We ignore ARPs we sent ourselves (Sender MAC address is our MAC address) because our own proxy ARPs do not constitute a conflict that we need to handle.
13983 // If we see an apparently conflicting ARP, we check the sender hardware address:
13984 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13985 // If the sender hardware address is *not* the original owner, then this is a conflict, and we need to wake the sleeping machine to handle it.
13986 if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
13987 debugf("ARP from self for %.4a", arp->tpa.b);
13988 else
13989 {
13990 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
13991 for (rr = m->ResourceRecords; rr; rr=rr->next)
13992 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13993 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13994 {
13995 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13996 {
13997 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13998 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13999 }
14000 else
14001 {
14002 RestartARPProbing(m, rr);
14003 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
14004 {
14005 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
14006 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ",
14007 arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr));
14008 }
14009 else
14010 {
14011 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14012 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14013 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14014 }
14015 }
14016 }
14017 }
14018
14019 mDNS_Unlock(m);
14020 }
14021
14022 /*
14023 // Option 1 is Source Link Layer Address Option
14024 // Option 2 is Target Link Layer Address Option
14025 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14026 {
14027 const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14028 while (options < end)
14029 {
14030 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14031 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14032 options += options[1] * 8;
14033 }
14034 return mDNSNULL;
14035 }
14036 */
14037
14038 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
14039 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14040 {
14041 AuthRecord *rr;
14042 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
14043 if (!intf) return;
14044
14045 mDNS_Lock(m);
14046
14047 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14048 if (ndp->type == NDP_Sol)
14049 {
14050 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14051 (void)end;
14052 for (rr = m->ResourceRecords; rr; rr=rr->next)
14053 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14054 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
14055 {
14056 static const char msg1[] = "NDP Req from owner -- re-probing";
14057 static const char msg2[] = "Ignoring NDP Request from ";
14058 static const char msg3[] = "Creating Local NDP Cache entry ";
14059 static const char msg4[] = "Answering NDP Request from ";
14060 static const char msg5[] = "Answering NDP Probe from ";
14061 const char *const msg = mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
14062 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
14063 mDNSSameEthAddress(sha, &intf->MAC) ? msg3 :
14064 mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5;
14065 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14066 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14067 if (msg == msg1)
14068 {
14069 if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
14070 RestartARPProbing(m, rr);
14071 else
14072 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
14073 }
14074 else if (msg == msg3)
14075 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14076 else if (msg == msg4)
14077 SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
14078 else if (msg == msg5)
14079 SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
14080 }
14081 }
14082
14083 // Pass 2: For all types of NDP packet we check the Sender IP address to make sure it doesn't conflict with any AddressProxy record we're holding.
14084 if (mDNSSameEthAddress(sha, &intf->MAC))
14085 debugf("NDP from self for %.16a", &ndp->target);
14086 else
14087 {
14088 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14089 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14090 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14091 // Hence it is the NDP target address we care about, not the actual packet source address.
14092 if (ndp->type == NDP_Adv) spa = &ndp->target;
14093 if (!mDNSSameIPv6Address(*spa, zerov6Addr))
14094 for (rr = m->ResourceRecords; rr; rr=rr->next)
14095 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14096 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14097 {
14098 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14099 {
14100 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14101 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14102 }
14103 else
14104 {
14105 RestartARPProbing(m, rr);
14106 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
14107 {
14108 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
14109 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
14110 }
14111 else
14112 {
14113 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14114 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14115 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14116 }
14117 }
14118 }
14119 }
14120
14121 mDNS_Unlock(m);
14122 }
14123
14124 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
14125 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
14126 {
14127 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
14128 mDNSBool wake = mDNSfalse;
14129 mDNSBool kaWake = mDNSfalse;
14130
14131 switch (protocol)
14132 {
14133 #define XX wake ? "Received" : "Ignoring", end-p
14134 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
14135 break;
14136
14137 case 0x06: {
14138 AuthRecord *kr;
14139 mDNSu32 seq, ack;
14140 #define TH_FIN 0x01
14141 #define TH_SYN 0x02
14142 #define TH_RST 0x04
14143 #define TH_ACK 0x10
14144
14145 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
14146 if (kr)
14147 {
14148 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
14149 // Plan to wake if
14150 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14151 // (b) packet that contains new data and acks a sequence number higher than the one
14152 // we have been sending in the keepalive
14153
14154 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
14155 if (!wake)
14156 {
14157 mDNSu8 *ptr;
14158 mDNSu32 pseq, pack;
14159 mDNSBool data = mDNSfalse;
14160 mDNSu8 tcphlen;
14161
14162 // Convert to host order
14163 ptr = (mDNSu8 *)&seq;
14164 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14165
14166 ptr = (mDNSu8 *)&ack;
14167 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14168
14169 pseq = t->tcp.seq;
14170 ptr = (mDNSu8 *)&pseq;
14171 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14172
14173 pack = t->tcp.ack;
14174 ptr = (mDNSu8 *)&pack;
14175 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14176
14177 // If the other side is acking one more than our sequence number (keepalive is one
14178 // less than the last valid sequence sent) and it's sequence is more than what we
14179 // acked before
14180 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14181 tcphlen = ((t->tcp.offset >> 4) * 4);
14182 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
14183 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
14184
14185 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14186 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
14187 ((int)(ack - pseq) == 1))
14188 {
14189 // Send an ACK;
14190 mDNS_SendKeepaliveACK(m, kr);
14191 }
14192 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14193 end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
14194 }
14195 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
14196 kaWake = wake;
14197 }
14198 else
14199 {
14200 // Plan to wake if
14201 // (a) RST is not set, AND
14202 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14203 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
14204
14205 // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14206 // except for ssh connections, where we'll wake for plain data packets too
14207 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
14208
14209 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
14210 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
14211 (t->tcp.flags & 2) ? " SYN" : "",
14212 (t->tcp.flags & 1) ? " FIN" : "",
14213 (t->tcp.flags & 4) ? " RST" : "");
14214 }
14215 break;
14216 }
14217
14218 case 0x11: {
14219 #define ARD_AsNumber 3283
14220 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
14221 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header
14222 if (udplen >= sizeof(UDPHeader))
14223 {
14224 const mDNSu16 datalen = udplen - sizeof(UDPHeader);
14225 wake = mDNStrue;
14226
14227 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14228 if (mDNSSameIPPort(port, IPSECPort))
14229 {
14230 // Specifically ignore NAT keepalive packets
14231 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14232 else
14233 {
14234 // Skip over the Non-ESP Marker if present
14235 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14236 const IKEHeader *const ike = (IKEHeader *)(t + (NonESP ? 12 : 8));
14237 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14238 if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14239 if ((ike->Version & 0x10) == 0x10)
14240 {
14241 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14242 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters>
14243 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14244 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14245 }
14246 }
14247 }
14248
14249 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14250 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14251 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14252 // UDP header (8 bytes)
14253 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14254 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14255
14256 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14257 }
14258 }
14259 break;
14260
14261 case 0x3A: if (&t->bytes[len] <= end)
14262 {
14263 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14264 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14265 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14266 }
14267 break;
14268
14269 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14270 break;
14271 }
14272
14273 if (wake)
14274 {
14275 AuthRecord *rr, *r2;
14276
14277 mDNS_Lock(m);
14278 for (rr = m->ResourceRecords; rr; rr=rr->next)
14279 if (rr->resrec.InterfaceID == InterfaceID &&
14280 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14281 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14282 {
14283 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14284 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14285 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14286 r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14287 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14288 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14289 break;
14290 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14291 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record
14292 if (r2)
14293 {
14294 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14295 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14296 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14297 }
14298 else
14299 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14300 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14301 }
14302 mDNS_Unlock(m);
14303 }
14304 }
14305
14306 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14307 {
14308 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP
14309 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4
14310 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6
14311 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1)
14312 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800)
14313
14314 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14315 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14316 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14317 // since it points to a an address 14 bytes before pkt.
14318 const EthernetHeader *const eth = (const EthernetHeader *)p;
14319 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14320 mDNSAddr src, dst;
14321 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14322
14323 // Is ARP? Length must be at least 14 + 28 = 42 bytes
14324 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14325 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14326 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14327 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14328 {
14329 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14330 const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14331 if (transEnd > end) transEnd = end;
14332 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src.b, &pkt->v4.dst.b);
14333 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14334 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14335 if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14336 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14337 }
14338 // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14339 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14340 {
14341 const mDNSu8 *const trans = p + 54;
14342 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src.b, &pkt->v6.dst.b);
14343 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14344 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14345 if (end >= trans + RequiredCapLen(pkt->v6.pro))
14346 mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14347 (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14348 }
14349 }
14350
14351 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14352 {
14353 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14354 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14355 }
14356
14357 #ifndef SPC_DISABLED
14358 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14359 {
14360 if (result == mStatus_NameConflict)
14361 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14362 else if (result == mStatus_MemFree)
14363 {
14364 if (m->SleepState)
14365 m->SPSState = 3;
14366 else
14367 {
14368 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14369 if (m->SPSState)
14370 {
14371 domainlabel name;
14372 ConstructSleepProxyServerName(m, &name);
14373 mDNS_RegisterService(m, srs,
14374 &name, &SleepProxyServiceType, &localdomain,
14375 mDNSNULL, m->SPSSocket->port, // Host, port
14376 mDNSNULL,
14377 (mDNSu8 *)"", 1, // TXT data, length
14378 mDNSNULL, 0, // Subtypes (none)
14379 mDNSInterface_Any, // Interface ID
14380 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14381 }
14382 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14383 }
14384 }
14385 }
14386 #endif
14387
14388 // Called with lock held
14389 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14390 {
14391 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14392 mDNS_DropLockBeforeCallback();
14393
14394 // If turning off SPS, close our socket
14395 // (Do this first, BEFORE calling mDNS_DeregisterService below)
14396 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14397
14398 // If turning off, or changing type, deregister old name
14399 #ifndef SPC_DISABLED
14400 if (m->SPSState == 1 && sps != m->SPSType)
14401 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14402 #endif // SPC_DISABLED
14403
14404 // Record our new SPS parameters
14405 m->SPSType = sps;
14406 m->SPSPortability = port;
14407 m->SPSMarginalPower = marginalpower;
14408 m->SPSTotalPower = totpower;
14409 m->SPSFeatureFlags = features;
14410 // If turning on, open socket and advertise service
14411 if (sps)
14412 {
14413 if (!m->SPSSocket)
14414 {
14415 m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort);
14416 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14417 }
14418 #ifndef SPC_DISABLED
14419 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14420 #endif // SPC_DISABLED
14421 }
14422 else if (m->SPSState)
14423 {
14424 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14425 m->NextScheduledSPS = m->timenow;
14426 }
14427 fail:
14428 mDNS_ReclaimLockAfterCallback();
14429 }
14430
14431 // ***************************************************************************
14432 #if COMPILER_LIKES_PRAGMA_MARK
14433 #pragma mark -
14434 #pragma mark - Startup and Shutdown
14435 #endif
14436
14437 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14438 {
14439 if (storage && numrecords)
14440 {
14441 mDNSu32 i;
14442 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14443 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14444 storage[numrecords-1].next = m->rrcache_free;
14445 m->rrcache_free = storage;
14446 m->rrcache_size += numrecords;
14447 }
14448 }
14449
14450 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14451 {
14452 mDNS_Lock(m);
14453 mDNS_GrowCache_internal(m, storage, numrecords);
14454 mDNS_Unlock(m);
14455 }
14456
14457 mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p,
14458 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14459 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14460 {
14461 mDNSu32 slot;
14462 mDNSs32 timenow;
14463 mStatus result;
14464
14465 if (!rrcachestorage) rrcachesize = 0;
14466
14467 m->next_request_id = 1;
14468 m->p = p;
14469 m->NetworkChanged = 0;
14470 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14471 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses;
14472 m->DivertMulticastAdvertisements = mDNSfalse;
14473 m->mDNSPlatformStatus = mStatus_Waiting;
14474 m->UnicastPort4 = zeroIPPort;
14475 m->UnicastPort6 = zeroIPPort;
14476 m->PrimaryMAC = zeroEthAddr;
14477 m->MainCallback = Callback;
14478 m->MainContext = Context;
14479 m->rec.r.resrec.RecordType = 0;
14480
14481 // For debugging: To catch and report locking failures
14482 m->mDNS_busy = 0;
14483 m->mDNS_reentrancy = 0;
14484 m->ShutdownTime = 0;
14485 m->lock_rrcache = 0;
14486 m->lock_Questions = 0;
14487 m->lock_Records = 0;
14488
14489 // Task Scheduling variables
14490 result = mDNSPlatformTimeInit();
14491 if (result != mStatus_NoError) return(result);
14492 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14493 timenow = mDNS_TimeNow_NoLock(m);
14494
14495 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section
14496 m->timenow_last = timenow;
14497 m->NextScheduledEvent = timenow;
14498 m->SuppressSending = timenow;
14499 m->NextCacheCheck = timenow + FutureTime;
14500 m->NextScheduledQuery = timenow + FutureTime;
14501 m->NextScheduledProbe = timenow + FutureTime;
14502 m->NextScheduledResponse = timenow + FutureTime;
14503 m->NextScheduledNATOp = timenow + FutureTime;
14504 m->NextScheduledSPS = timenow + FutureTime;
14505 m->NextScheduledKA = timenow + FutureTime;
14506 m->NextScheduledStopTime = timenow + FutureTime;
14507 m->NextBLEServiceTime = 0; // zero indicates inactive
14508
14509 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14510 m->NextBonjourDisableTime = 0; // Timer active when non zero.
14511 m->BonjourEnabled = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14512 #endif
14513 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
14514 m->NextSuspiciousTimeout = 0;
14515 #endif
14516
14517 m->RandomQueryDelay = 0;
14518 m->RandomReconfirmDelay = 0;
14519 m->PktNum = 0;
14520 m->MPktNum = 0;
14521 m->LocalRemoveEvents = mDNSfalse;
14522 m->SleepState = SleepState_Awake;
14523 m->SleepSeqNum = 0;
14524 m->SystemWakeOnLANEnabled = mDNSfalse;
14525 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14526 m->DelaySleep = 0;
14527 m->SleepLimit = 0;
14528
14529 #if APPLE_OSX_mDNSResponder
14530 m->UnicastPacketsSent = 0;
14531 m->MulticastPacketsSent = 0;
14532 m->RemoteSubnet = 0;
14533 #endif // APPLE_OSX_mDNSResponder
14534
14535 // These fields only required for mDNS Searcher...
14536 m->Questions = mDNSNULL;
14537 m->NewQuestions = mDNSNULL;
14538 m->CurrentQuestion = mDNSNULL;
14539 m->LocalOnlyQuestions = mDNSNULL;
14540 m->NewLocalOnlyQuestions = mDNSNULL;
14541 m->RestartQuestion = mDNSNULL;
14542 m->ValidationQuestion = mDNSNULL;
14543 m->rrcache_size = 0;
14544 m->rrcache_totalused = 0;
14545 m->rrcache_active = 0;
14546 m->rrcache_report = 10;
14547 m->rrcache_free = mDNSNULL;
14548
14549 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14550 {
14551 m->rrcache_hash[slot] = mDNSNULL;
14552 m->rrcache_nextcheck[slot] = timenow + FutureTime;;
14553 }
14554
14555 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14556 m->rrauth.rrauth_free = mDNSNULL;
14557
14558 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14559 m->rrauth.rrauth_hash[slot] = mDNSNULL;
14560
14561 // Fields below only required for mDNS Responder...
14562 m->hostlabel.c[0] = 0;
14563 m->nicelabel.c[0] = 0;
14564 m->MulticastHostname.c[0] = 0;
14565 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14566 m->RandomizedHostname.c[0] = 0;
14567 #endif
14568 m->HIHardware.c[0] = 0;
14569 m->HISoftware.c[0] = 0;
14570 m->ResourceRecords = mDNSNULL;
14571 m->DuplicateRecords = mDNSNULL;
14572 m->NewLocalRecords = mDNSNULL;
14573 m->NewLocalOnlyRecords = mDNSfalse;
14574 m->CurrentRecord = mDNSNULL;
14575 m->HostInterfaces = mDNSNULL;
14576 m->ProbeFailTime = 0;
14577 m->NumFailedProbes = 0;
14578 m->SuppressProbes = 0;
14579
14580 #ifndef UNICAST_DISABLED
14581 m->NextuDNSEvent = timenow + FutureTime;
14582 m->NextSRVUpdate = timenow + FutureTime;
14583
14584 m->DNSServers = mDNSNULL;
14585
14586 m->Router = zeroAddr;
14587 m->AdvertisedV4 = zeroAddr;
14588 m->AdvertisedV6 = zeroAddr;
14589
14590 m->AuthInfoList = mDNSNULL;
14591
14592 m->ReverseMap.ThisQInterval = -1;
14593 m->StaticHostname.c[0] = 0;
14594 m->FQDN.c[0] = 0;
14595 m->Hostnames = mDNSNULL;
14596
14597 m->WABBrowseQueriesCount = 0;
14598 m->WABLBrowseQueriesCount = 0;
14599 m->WABRegQueriesCount = 0;
14600 m->AutoTargetServices = 0;
14601
14602 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14603 m->NumAllInterfaceRecords = 0;
14604 m->NumAllInterfaceQuestions = 0;
14605 #endif
14606 // NAT traversal fields
14607 m->LLQNAT.clientCallback = mDNSNULL;
14608 m->LLQNAT.clientContext = mDNSNULL;
14609 m->NATTraversals = mDNSNULL;
14610 m->CurrentNATTraversal = mDNSNULL;
14611 m->retryIntervalGetAddr = 0; // delta between time sent and retry
14612 m->retryGetAddr = timenow + FutureTime; // absolute time when we retry
14613 m->ExtAddress = zerov4Addr;
14614 m->PCPNonce[0] = mDNSRandom(-1);
14615 m->PCPNonce[1] = mDNSRandom(-1);
14616 m->PCPNonce[2] = mDNSRandom(-1);
14617
14618 m->NATMcastRecvskt = mDNSNULL;
14619 m->LastNATupseconds = 0;
14620 m->LastNATReplyLocalTime = timenow;
14621 m->LastNATMapResultCode = NATErr_None;
14622
14623 m->UPnPInterfaceID = 0;
14624 m->SSDPSocket = mDNSNULL;
14625 m->SSDPWANPPPConnection = mDNSfalse;
14626 m->UPnPRouterPort = zeroIPPort;
14627 m->UPnPSOAPPort = zeroIPPort;
14628 m->UPnPRouterURL = mDNSNULL;
14629 m->UPnPWANPPPConnection = mDNSfalse;
14630 m->UPnPSOAPURL = mDNSNULL;
14631 m->UPnPRouterAddressString = mDNSNULL;
14632 m->UPnPSOAPAddressString = mDNSNULL;
14633 m->SPSType = 0;
14634 m->SPSPortability = 0;
14635 m->SPSMarginalPower = 0;
14636 m->SPSTotalPower = 0;
14637 m->SPSFeatureFlags = 0;
14638 m->SPSState = 0;
14639 m->SPSProxyListChanged = mDNSNULL;
14640 m->SPSSocket = mDNSNULL;
14641 m->SPSBrowseCallback = mDNSNULL;
14642 m->ProxyRecords = 0;
14643
14644 m->DNSPushServers = mDNSNULL;
14645 m->DNSPushZones = mDNSNULL;
14646 #endif
14647
14648 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14649 if (WCFConnectionNew)
14650 {
14651 m->WCF = WCFConnectionNew();
14652 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14653 }
14654 #endif
14655
14656 return(result);
14657 }
14658
14659 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14660 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14661 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14662 {
14663 mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context);
14664 if (result != mStatus_NoError)
14665 return(result);
14666
14667 #if MDNS_MALLOC_DEBUGGING
14668 static mDNSListValidator lv;
14669 mDNSPlatformAddListValidator(&lv, mDNS_ValidateLists, "mDNS_ValidateLists", m);
14670 #endif
14671 result = mDNSPlatformInit(m);
14672
14673 #ifndef UNICAST_DISABLED
14674 // It's better to do this *after* the platform layer has set up the
14675 // interface list and security credentials
14676 uDNS_SetupDNSConfig(m); // Get initial DNS configuration
14677 #endif
14678
14679 return(result);
14680 }
14681
14682 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14683 {
14684 if (m->SPSState == 1)
14685 {
14686 domainlabel name, newname;
14687 #ifndef SPC_DISABLED
14688 domainname type, domain;
14689 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14690 #endif // SPC_DISABLED
14691 ConstructSleepProxyServerName(m, &newname);
14692 if (!SameDomainLabelCS(name.c, newname.c))
14693 {
14694 LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14695 // When SleepProxyServerCallback gets the mStatus_MemFree message,
14696 // it will reregister the service under the new name
14697 m->SPSState = 2;
14698 #ifndef SPC_DISABLED
14699 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14700 #endif // SPC_DISABLED
14701 }
14702 }
14703
14704 if (m->MainCallback)
14705 m->MainCallback(m, mStatus_ConfigChanged);
14706 }
14707
14708 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14709 {
14710 (void)m; // unused
14711 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14712 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14713 }
14714
14715 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr)
14716 {
14717 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14718 cr->resrec.rrtype == kDNSType_A ||
14719 cr->resrec.rrtype == kDNSType_AAAA ||
14720 cr->resrec.rrtype == kDNSType_SRV ||
14721 cr->resrec.rrtype == kDNSType_CNAME;
14722
14723 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14724 purge ? "purging" : "reconfirming",
14725 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
14726 cr->resrec.rDNSServer ? mDNSVal16(cr->resrec.rDNSServer->port) : -1,
14727 cr->resrec.rDNSServer ? cr->resrec.rDNSServer->domain.c : mDNSNULL, CRDisplayString(m, cr));
14728
14729 if (purge)
14730 {
14731 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14732 cr->resrec.mortality = Mortality_Mortal;
14733 mDNS_PurgeCacheResourceRecord(m, cr);
14734 }
14735 else
14736 {
14737 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14738 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14739 }
14740 }
14741
14742 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
14743 {
14744 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14745 CacheRecord *rp;
14746 mDNSu8 validatingResponse = 0;
14747
14748 // For DNSSEC questions, purge the corresponding RRSIGs also.
14749 if (DNSSECQuestion(q))
14750 {
14751 validatingResponse = q->ValidatingResponse;
14752 q->ValidatingResponse = mDNStrue;
14753 }
14754 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14755 {
14756 if (SameNameCacheRecordAnswersQuestion(rp, q))
14757 {
14758 LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
14759 mDNS_PurgeCacheResourceRecord(m, rp);
14760 }
14761 }
14762 if (DNSSECQuestion(q))
14763 {
14764 q->ValidatingResponse = validatingResponse;
14765 }
14766 }
14767
14768 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14769 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14770 // Just re-issuing the question for RRSIGs does not work in practice as the response
14771 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14772 //
14773 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14774 // have the cached NSECs, purge them. For positive responses, if we don't have the
14775 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14776 // them.
14777 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q)
14778 {
14779 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14780 CacheRecord *rp;
14781
14782 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14783 {
14784 if (SameNameCacheRecordAnswersQuestion(rp, q))
14785 {
14786 if (rp->resrec.RecordType != kDNSRecordTypePacketNegative || !rp->nsec)
14787 {
14788 if (!rp->CRDNSSECQuestion)
14789 {
14790 LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m, rp));
14791 mDNS_PurgeCacheResourceRecord(m, rp);
14792 }
14793 }
14794 }
14795 }
14796 }
14797
14798 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14799 {
14800 DNSQuestion *qptr;
14801
14802 (void) m;
14803
14804 if (q->DuplicateOf)
14805 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14806
14807 // Make sure all the duplicate questions point to the same DNSServer so that delivery
14808 // of events for all of them are consistent. Duplicates for a question are always inserted
14809 // after in the list.
14810 q->qDNSServer = new;
14811 for (qptr = q->next ; qptr; qptr = qptr->next)
14812 {
14813 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14814 }
14815 }
14816
14817 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14818 {
14819 McastResolver *mr;
14820 DNSServer *ptr;
14821
14822 if (delete)
14823 {
14824 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14825 {
14826 ptr->penaltyTime = 0;
14827 ptr->flags |= DNSServerFlag_Delete;
14828 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14829 if (ptr->flags & DNSServerFlag_Unreachable)
14830 NumUnreachableDNSServers--;
14831 #endif
14832 }
14833 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14834 // mcast resolvers. Today we get both mcast and ucast configuration using the same
14835 // API
14836 for (mr = m->McastResolvers; mr; mr = mr->next)
14837 mr->flags |= McastResolver_FlagDelete;
14838 }
14839 else
14840 {
14841 for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14842 {
14843 ptr->penaltyTime = 0;
14844 ptr->flags &= ~DNSServerFlag_Delete;
14845 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14846 if (ptr->flags & DNSServerFlag_Unreachable)
14847 NumUnreachableDNSServers++;
14848 #endif
14849 }
14850 for (mr = m->McastResolvers; mr; mr = mr->next)
14851 mr->flags &= ~McastResolver_FlagDelete;
14852 }
14853 }
14854
14855 mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn)
14856 {
14857 // Did our FQDN change?
14858 if (!SameDomainName(fqdn, &m->FQDN))
14859 {
14860 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14861
14862 AssignDomainName(&m->FQDN, fqdn);
14863
14864 if (m->FQDN.c[0])
14865 {
14866 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14867 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14868 }
14869 }
14870 }
14871
14872 // Even though this is called “Setup” it is not called just once at startup.
14873 // It’s actually called multiple times, every time there’s a configuration change.
14874 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14875 {
14876 mDNSu32 slot;
14877 CacheGroup *cg;
14878 CacheRecord *cr;
14879 mDNSAddr v4, v6, r;
14880 domainname fqdn;
14881 DNSServer *ptr, **p = &m->DNSServers;
14882 const DNSServer *oldServers = m->DNSServers;
14883 DNSQuestion *q;
14884 McastResolver *mr, **mres = &m->McastResolvers;
14885 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14886 DNSPushNotificationServer **psp;
14887 #endif
14888
14889 debugf("uDNS_SetupDNSConfig: entry");
14890
14891 // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14892 uDNS_SetupWABQueries(m);
14893
14894 mDNS_Lock(m);
14895
14896 // We need to first mark all the entries to be deleted. If the configuration changed, then
14897 // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14898 //
14899 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14900 // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14901 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14902 // for the dns configuration change notification.
14903 SetConfigState(m, mDNStrue);
14904 if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14905 {
14906 SetDynDNSHostNameIfChanged(m, &fqdn);
14907 SetConfigState(m, mDNSfalse);
14908 mDNS_Unlock(m);
14909 LogInfo("uDNS_SetupDNSConfig: No configuration change");
14910 return mStatus_NoError;
14911 }
14912 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
14913 // Reset suspicious mode on any DNS configuration change
14914 m->NextSuspiciousTimeout = 0;
14915 #endif
14916
14917 // For now, we just delete the mcast resolvers. We don't deal with cache or
14918 // questions here. Neither question nor cache point to mcast resolvers. Questions
14919 // do inherit the timeout values from mcast resolvers. But we don't bother
14920 // affecting them as they never change.
14921 while (*mres)
14922 {
14923 if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14924 {
14925 mr = *mres;
14926 *mres = (*mres)->next;
14927 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14928 mDNSPlatformMemFree(mr);
14929 }
14930 else
14931 {
14932 (*mres)->flags &= ~McastResolver_FlagNew;
14933 mres = &(*mres)->next;
14934 }
14935 }
14936
14937 // Update our qDNSServer pointers before we go and free the DNSServer object memory
14938 //
14939 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14940 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14941 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14942 // DNSServers and flush the cache.
14943 //
14944 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14945 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14946 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14947 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14948 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14949 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14950 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14951 // the same resGroupID.
14952 //
14953 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14954 // of the old followed by ADD of the new records.
14955 //
14956 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will
14957 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14958 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14959 //
14960 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14961 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14962 // non-scoped question and vice versa.
14963 //
14964 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14965 DNS64RestartQuestions(m);
14966 #endif
14967
14968 // First, restart questions whose suppression status will change. The suppression status of each question in a given
14969 // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14970 // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14971 // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14972 // suppressed (or non-suppressed).
14973 for (q = m->Questions; q; q = q->next)
14974 {
14975 DNSServer *s;
14976 const DNSServer *t;
14977 mDNSBool oldSuppressed;
14978
14979 if (mDNSOpaque16IsZero(q->TargetQID)) continue;
14980
14981 SetValidDNSServers(m, q);
14982 q->triedAllServersOnce = mDNSfalse;
14983 s = GetServerForQuestion(m, q);
14984 t = q->qDNSServer;
14985 if (s != t)
14986 {
14987 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
14988 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR ":%d (" PRI_DM_NAME ") to "
14989 PRI_IP_ADDR ":%d (" PRI_DM_NAME ") for question " PRI_DM_NAME " (" PUB_S ") (scope:%p)",
14990 q->request_id, mDNSVal16(q->TargetQID),
14991 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), DM_NAME_PARAM(t ? t->domain.c : (mDNSu8*)""),
14992 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), DM_NAME_PARAM(s ? s->domain.c : (mDNSu8*)""),
14993 DM_NAME_PARAM(q->qname.c), DNSTypeName(q->qtype), q->InterfaceID);
14994 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
14995 // If this question had a DNS Push server associated with it, substitute the new server for the
14996 // old one. If there is no new server, then we'll clean up the push server later.
14997 if (!q->DuplicateOf && (q->dnsPushServer != mDNSNULL))
14998 {
14999 if (q->dnsPushServer->qDNSServer == t)
15000 {
15001 q->dnsPushServer->qDNSServer = s; // which might be null
15002 }
15003 // If it is null, do the accounting and drop the push server.
15004 if (q->dnsPushServer->qDNSServer == mDNSNULL)
15005 {
15006 DNSPushReconcileConnection(m, q);
15007 }
15008 }
15009 #endif
15010 }
15011 oldSuppressed = q->Suppressed;
15012 q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15013 if (!q->Suppressed != !oldSuppressed) q->Restart = mDNStrue;
15014 }
15015 RestartUnicastQuestions(m);
15016
15017 // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
15018 // have already had their server changed by being restarted.
15019 for (q = m->Questions; q; q = q->next)
15020 {
15021 DNSServer *s;
15022 const DNSServer *t;
15023
15024 if (mDNSOpaque16IsZero(q->TargetQID) || q->DuplicateOf) continue;
15025
15026 SetValidDNSServers(m, q);
15027 q->triedAllServersOnce = mDNSfalse;
15028 s = GetServerForQuestion(m, q);
15029 t = q->qDNSServer;
15030 DNSServerChangeForQuestion(m, q, s);
15031 if (s == t) continue;
15032
15033 q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15034 q->unansweredQueries = 0;
15035 #if MDNSRESPONDER_SUPPORTS(APPLE, SUSPICIOUS_REPLY_DEFENSE)
15036 q->LastTargetQID = q->TargetQID;
15037 #endif
15038 q->TargetQID = mDNS_NewMessageID(m);
15039 if (!q->Suppressed) ActivateUnicastQuery(m, q, mDNStrue);
15040 }
15041
15042 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15043 // The above code may have found some DNS Push servers that are no longer valid. Now that we
15044 // are done running through the code, we need to drop our connections to those servers.
15045 // When we get here, any such servers should have zero questions associated with them.
15046 for (psp = &m->DNSPushServers; *psp != mDNSNULL; )
15047 {
15048 DNSPushNotificationServer *server = *psp;
15049
15050 // It's possible that a push server whose DNS server has been deleted could be still connected but
15051 // not referenced by any questions. In this case, we just delete the push server rather than trying
15052 // to figure out with which DNS server (if any) to associate it.
15053 if (server->qDNSServer != mDNSNULL && server->qDNSServer->flags & DNSServerFlag_Delete)
15054 {
15055 server->qDNSServer = mDNSNULL;
15056 }
15057
15058 if (server->qDNSServer == mDNSNULL)
15059 {
15060 // This would be a programming error, so should never happen.
15061 if (server->numberOfQuestions != 0)
15062 {
15063 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server->serverName);
15064 }
15065 DNSPushServerDrop(server);
15066 *psp = server->next;
15067 mDNSPlatformMemFree(server);
15068 }
15069 else
15070 {
15071 psp = &(*psp)->next;
15072 }
15073 }
15074 #endif
15075
15076 FORALL_CACHERECORDS(slot, cg, cr)
15077 {
15078 if (cr->resrec.InterfaceID) continue;
15079
15080 // We already walked the questions and restarted/reactivated them if the dns server
15081 // change affected the question. That should take care of updating the cache. But
15082 // what if there is no active question at this point when the DNS server change
15083 // happened ? There could be old cache entries lying around and if we don't flush
15084 // them, a new question after the DNS server change could pick up these stale
15085 // entries and get a wrong answer.
15086 //
15087 // For cache entries that have active questions we might have skipped rescheduling
15088 // the questions if they were suppressed (see above). To keep it simple, we walk
15089 // all the cache entries to make sure that there are no stale entries. We use the
15090 // active question's InterfaceID/ServiceID for looking up the right DNS server.
15091 //
15092 // Note: If GetServerForName returns NULL, it could either mean that there are no
15093 // DNS servers or no matching DNS servers for this question. In either case,
15094 // the cache should get purged below when we process deleted DNS servers.
15095 //
15096 // If it is a DNSSEC question, purge the cache as the DNSSEC capabilities of the
15097 // DNS server may have changed.
15098
15099 if (cr->CRActiveQuestion && !DNSSECQuestion(cr->CRActiveQuestion))
15100 {
15101 // Purge or Reconfirm if this cache entry would use the new DNS server
15102 ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion->InterfaceID, cr->CRActiveQuestion->ServiceID);
15103 if (ptr && (ptr != cr->resrec.rDNSServer))
15104 {
15105 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15106 CRDisplayString(m, cr), &ptr->addr,
15107 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL);
15108 PurgeOrReconfirmCacheRecord(m, cr);
15109
15110 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15111 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15112 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion->qDNSServer)
15113 {
15114 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->CRActiveQuestion->qDNSServer->addr, CRDisplayString(m, cr));
15115 cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer;
15116 }
15117 }
15118
15119 if (cr->resrec.rDNSServer && cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15120 {
15121 DNSQuestion *qptr = cr->CRActiveQuestion;
15122 if (qptr->qDNSServer == cr->resrec.rDNSServer)
15123 {
15124 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15125 " to be freed", CRDisplayString(m, cr),
15126 qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15127 &cr->resrec.rDNSServer->addr);
15128 qptr->validDNSServers = zeroOpaque128;
15129 qptr->qDNSServer = mDNSNULL;
15130 cr->resrec.rDNSServer = mDNSNULL;
15131 }
15132 else
15133 {
15134 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15135 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr),
15136 qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15137 &cr->resrec.rDNSServer->addr,
15138 qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL);
15139 cr->resrec.rDNSServer = qptr->qDNSServer;
15140 }
15141 PurgeOrReconfirmCacheRecord(m, cr);
15142 }
15143 }
15144 else if (!cr->resrec.rDNSServer || cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15145 {
15146 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
15147 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S ", DNS server " PUB_S " " PRI_IP_ADDR " " PUB_S,
15148 CRDisplayString(m, cr), !cr->resrec.rDNSServer ? "(to be deleted)" : "",
15149 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
15150 cr->resrec.rDNSServer ? DNSScopeToString(cr->resrec.rDNSServer->scopeType) : "" );
15151 cr->resrec.rDNSServer = mDNSNULL;
15152 cr->resrec.mortality = Mortality_Mortal;
15153 mDNS_PurgeCacheResourceRecord(m, cr);
15154 }
15155 }
15156
15157 // Delete all the DNS servers that are flagged for deletion
15158 while (*p)
15159 {
15160 if (((*p)->flags & DNSServerFlag_Delete) != 0)
15161 {
15162 ptr = *p;
15163 *p = (*p)->next;
15164 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
15165 mDNSPlatformMemFree(ptr);
15166 }
15167 else
15168 {
15169 p = &(*p)->next;
15170 }
15171 }
15172 LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m));
15173
15174 // If we now have no DNS servers at all and we used to have some, then immediately purge all unicast cache records (including for LLQs).
15175 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15176 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15177 // Similarly, if we now have some DNS servers and we used to have none, we want to purge any fake negative results we may have generated.
15178 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
15179 {
15180 int count = 0;
15181 FORALL_CACHERECORDS(slot, cg, cr)
15182 {
15183 if (!cr->resrec.InterfaceID)
15184 {
15185 mDNS_PurgeCacheResourceRecord(m, cr);
15186 count++;
15187 }
15188 }
15189 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15190 m->DNSServers ? "DNS server became" : "No DNS servers", count);
15191
15192 // Force anything that needs to get zone data to get that information again
15193 RestartRecordGetZoneData(m);
15194 }
15195
15196 SetDynDNSHostNameIfChanged(m, &fqdn);
15197
15198 mDNS_Unlock(m);
15199
15200 // handle router and primary interface changes
15201 v4 = v6 = r = zeroAddr;
15202 v4.type = r.type = mDNSAddrType_IPv4;
15203
15204 if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
15205 {
15206 mDNS_SetPrimaryInterfaceInfo(m,
15207 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
15208 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
15209 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL);
15210 }
15211 else
15212 {
15213 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
15214 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
15215 }
15216
15217 debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m));
15218 return mStatus_NoError;
15219 }
15220
15221 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
15222 {
15223 m->mDNSPlatformStatus = result;
15224 if (m->MainCallback)
15225 {
15226 mDNS_Lock(m);
15227 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback
15228 m->MainCallback(m, mStatus_NoError);
15229 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again
15230 mDNS_Unlock(m);
15231 }
15232 }
15233
15234 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
15235 {
15236 m->CurrentRecord = start;
15237 while (m->CurrentRecord)
15238 {
15239 AuthRecord *rr = m->CurrentRecord;
15240 LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15241 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating",
15242 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15243 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15244 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15245 else if (rr->AnnounceCount > 1)
15246 {
15247 rr->AnnounceCount = 1;
15248 rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15249 }
15250 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15251 // new records could have been added to the end of the list as a result of that call.
15252 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15253 m->CurrentRecord = rr->next;
15254 }
15255 }
15256
15257 mDNSexport void mDNS_StartExit(mDNS *const m)
15258 {
15259 AuthRecord *rr;
15260
15261 mDNS_Lock(m);
15262
15263 LogInfo("mDNS_StartExit");
15264 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15265
15266 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15267
15268 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15269 if (WCFConnectionDealloc)
15270 {
15271 if (m->WCF) WCFConnectionDealloc(m->WCF);
15272 }
15273 #endif
15274
15275 #ifndef UNICAST_DISABLED
15276 {
15277 SearchListElem *s;
15278 SuspendLLQs(m);
15279 // Don't need to do SleepRecordRegistrations() here
15280 // because we deregister all records and services later in this routine
15281 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15282
15283 // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15284 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15285 // and we may crash because the list still contains dangling pointers.
15286 for (s = SearchList; s; s = s->next)
15287 while (s->AuthRecs)
15288 {
15289 ARListElem *dereg = s->AuthRecs;
15290 s->AuthRecs = s->AuthRecs->next;
15291 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15292 }
15293 }
15294 #endif
15295
15296 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_All);
15297
15298 // Shut down all our active NAT Traversals
15299 while (m->NATTraversals)
15300 {
15301 NATTraversalInfo *t = m->NATTraversals;
15302 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15303
15304 // After stopping the NAT Traversal, we zero out the fields.
15305 // This has particularly important implications for our AutoTunnel records --
15306 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15307 // handlers to just turn around and attempt to re-register those same records.
15308 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15309 // to not do this.
15310 t->ExternalAddress = zerov4Addr;
15311 t->NewAddress = zerov4Addr;
15312 t->ExternalPort = zeroIPPort;
15313 t->RequestedPort = zeroIPPort;
15314 t->Lifetime = 0;
15315 t->Result = mStatus_NoError;
15316 }
15317
15318 // Make sure there are nothing but deregistering records remaining in the list
15319 if (m->CurrentRecord)
15320 LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
15321
15322 // We're in the process of shutting down, so queries, etc. are no longer available.
15323 // Consequently, determining certain information, e.g. the uDNS update server's IP
15324 // address, will not be possible. The records on the main list are more likely to
15325 // already contain such information, so we deregister the duplicate records first.
15326 LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15327 DeregLoop(m, m->DuplicateRecords);
15328 LogInfo("mDNS_StartExit: Deregistering resource records");
15329 DeregLoop(m, m->ResourceRecords);
15330
15331 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15332 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15333 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15334 {
15335 m->NextScheduledResponse = m->timenow;
15336 m->SuppressSending = 0;
15337 }
15338
15339 if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15340 else LogInfo("mDNS_StartExit: No deregistering records remain");
15341
15342 for (rr = m->DuplicateRecords; rr; rr = rr->next)
15343 LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
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 LogInfo("mDNS_StartExit: done");
15351 }
15352
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 LogInfo("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 LogInfo("mDNS_FinalExit: done");
15387 }
15388
15389 #ifdef UNIT_TEST
15390 #include "../unittests/mdns_ut.c"
15391 #endif